<commit_before>'use strict';
var React = require('react');
var url = require('url');
var _ = require('underscore');
var graph = require('./graph');
var globals = require('./globals');
var dbxref = require('./dbxref');
var search = require('./search');
var StatusLabel = require('./statuslabel').StatusLabel;
var Citation = require('./publication').Citation;
var audit = require('./audit');

var Graph = graph.Graph;
var JsonGraph = graph.JsonGraph;
var AuditIndicators = audit.AuditIndicators;
var AuditDetail = audit.AuditDetail;
var AuditMixin = audit.AuditMixin;

var DbxrefList = dbxref.DbxrefList;

var Panel = function (props) {
    // XXX not all panels have the same markup
    var context;
    if (props['@id']) {
        context = props;
        props = {context: context};
    }
    var PanelView = globals.panel_views.lookup(props.context);
    return <PanelView {...props} />;
};

var Pipeline = module.exports.Pipeline = React.createClass({
    mixins: [AuditMixin],

    getInitialState: function() {
        return {
            infoNodeId: '' // ID of node whose info panel is open
        };
    },

    assembleGraph: function() {
        var jsonGraph;

        // Only produce a graph if there's at least one analysis step
        if (this.props.context.analysis_steps) {
            // Create an empty graph architecture
            jsonGraph = new JsonGraph(this.props.context.accession);

            // Add files and their steps as nodes to the graph
            this.props.context.analysis_steps.forEach(function(step) {
                var stepId = step['@id'];

                // Make an array of step types
                var stepTypesList = step.analysis_step_types.map(function(type) {
                    return type;
                });

                // Assemble a single analysis step node.
                jsonGraph.addNode(stepId, stepTypesList.join(', '),
                    {cssClass: 'pipeline-node-analysis-step' + (this.state.infoNodeId === stepId ? ' active' : ''), type: 'step', shape: 'rect', cornerRadius: 4, ref: step});

                // If the node has parents, render the edges to those parents
                if (step.parents && step.parents.length) {
                    step.parents.forEach(function(parent) {
                        jsonGraph.addEdge(parent['@id'], stepId);
                    });
                }
            }, this);

            // If any analysis step parents haven't been seen yet,
            // add them to the graph too
            this.props.context.analysis_steps.forEach(function(step) {
                if (step.parents) {
                    step.parents.forEach(function(parent) {
                        var stepId = parent['@id'];
                        if (!jsonGraph.getNode(stepId)) {
                            // Make an array of step types
                            var stepTypesList = parent.analysis_step_types.map(function(type) {
                                return type;
                            });

                            // Assemble a single analysis step node.
                            jsonGraph.addNode(stepId, stepTypesList.join(', '),
                                {cssClass: 'pipeline-node-analysis-step' + (this.state.infoNodeId === stepId ? ' active' : ''), type: 'step', shape: 'rect', cornerRadius: 4, ref: parent});
                        }
                    }, this);
                }
            }, this);

        }
        return jsonGraph;
    },

    detailNodes: function(jsonGraph, infoNodeId) {
        var meta;

        // Find data matching selected node, if any
        if (infoNodeId) {
            var node = jsonGraph.getNode(infoNodeId);
            if (node) {
                meta = globals.graph_detail.lookup(node)(node);
            }
        }

        return meta;
    },

    handleNodeClick: function(e, nodeId) {
        e.stopPropagation(); e.preventDefault();
        this.setState({infoNodeId: this.state.infoNodeId !== nodeId ? nodeId : ''});
    },

    render: function() {
        var context = this.props.context;
        var itemClass = globals.itemClass(context, 'view-item');

        var documents = {};
        if (context.documents) {
            context.documents.forEach(function(doc, i) {
                documents[doc['@id']] = Panel({context: doc, key: i + 1});
            });
        }

        // Build node graph of the files and analysis steps with this experiment
        this.jsonGraph = this.assembleGraph();
        var meta = this.detailNodes(this.jsonGraph, this.state.infoNodeId);

        return (

{context.title}

                                <StatusLabel title="Status" status={context.status} />

                            <AuditIndicators audits={context.audit} id="biosample-audit" />

                <AuditDetail audits={context.audit} id="biosample-audit" />

Title

                            {context.source_url ?

{context.title}
 :

{context.title}

                            }

Assay

{context.assay_term_name}

                {context.analysis_steps && context.analysis_steps.length ?

Steps

                            {context.analysis_steps.map(function(props, i) {
                                return (

                                        {i > 0 ?
 : null}
                                        {AnalysisStep(props, i)}

                                );
                            })}

                : null}
                {Object.keys(documents).length ?

Documents

                            {documents}

                : null}
                {this.jsonGraph ?

Pipeline

                        <Graph graph={this.jsonGraph} nodeClickHandler={this.handleNodeClick}>

                                {meta ?
{meta}
 : null}

                        </Graph>

                : null}

        );
    }
});
globals.content_views.register(Pipeline, 'pipeline');

var AnalysisStep = module.exports.AnalysisStep = function (props, i) {
    var typesList = props.analysis_step_types.join(", ");

    return (

            {props.analysis_step_types.length ?

Category

{typesList}

            : null}
            {props.software_versions.length ?

 Software

                        {props.software_versions.map(function(software_version, i) {
                            return (  {
                                i > 0 ? ", ": ""
                            }
                            {software_version.software.title}
                            );
                        })}

            : null}

    );
};

// Display the metadata of the selected analysis step in the graph
var StepDetailView = module.exports.StepDetailView = function(node) {
    // The node is for a step. It can be called with analysis_step_run (for file graphs) or analysis_step (for pipeline graphs) nodes.
    // This code detects which is the case, and adjusts accordingly.
    var selectedStep = node.metadata.ref;
    var meta;

    if (selectedStep) {
        // The node is for an analysis step
        return (

Step type

{selectedStep.analysis_step_types.join(', ')}

                    {selectedStep.input_file_types && selectedStep.input_file_types.length ?

Input file types

{selectedStep.input_file_types.join(', ')}

                    : null}

                    {selectedStep.output_file_types && selectedStep.output_file_types.length ?

Output file types

{selectedStep.output_file_types.join(', ')}

                    : null}

                    {node.metadata.pipeline ?

Pipeline

{node.metadata.pipeline.title}

                    : null}

                    {selectedStep.qa_stats_generated && selectedStep.qa_stats_generated.length ?

QA statistics

{selectedStep.qa_stats_generated.join(', ')}

                    : null}

                    {selectedStep.software_versions && selectedStep.software_versions.length ?

Software

                                {selectedStep.software_versions.map(function(version, i) {
                                    var versionNum = version.version === 'unknown' ? 'version unknown' : version.version;
                                    return (

                                            {version.software.name}
                                            {version.version ?
                                                {versionNum}
                                            : null}

                                    );
                                })}

                    : null}

        );
    } else {
        return (
Missing step_run derivation information for {node.metadata.fileAccession}
);
    }
};

globals.graph_detail.register(StepDetailView, 'step');

var Listing = React.createClass({
    mixins: [search.PickerActionsMixin, AuditMixin],
    render: function() {
        var result = this.props.context;
        return (

                    {this.renderActions()}

Pipeline

                        {result.status ?
{' ' + result.status}
 : ''}
                        <AuditIndicators audits={result.audit} id={result['@id']} search />

                            {result['title']}

                <AuditDetail audits={result.audit} id={this.props.context['@id']} />

        );
    }
});
globals.listing_views.register(Listing, 'pipeline');

var PipelineTable = module.exports.PipelineTable = React.createClass({
    render: function() {
        var pipelines;

        // If there's a limit on entries to display and the array is greater than that
        // limit, then clone the array with just that specified number of elements
        if (this.props.limit && (this.props.limit < this.props.items.length)) {
            // Limit the pipelines list by cloning first {limit} elements
            pipelines = this.props.items.slice(0, this.props.limit);
        } else {
            // No limiting; just reference the original array
            pipelines = this.props.items;
        }

        // Get the software version numbers for all matching software
        var softwareId = url.parse(this.props.href).pathname;
        var swVers = [];
        pipelines.forEach(function(pipeline, i) {
            return pipeline.analysis_steps.some(function(analysis_step) {
                // Get the software_version object for any with a software @id matching softwareId, and save to array
                var matchedSwVers = _(analysis_step.software_versions).find(function(software_version) {
                    return software_version.software['@id'] === softwareId;
                });
                if (matchedSwVers) {
                    swVers[i] = matchedSwVers;
                }
                return matchedSwVers;
            });
        });

        return (

                            Pipeline
                            Assay
                            Version
                            Download checksum

                    {pipelines.map(function (pipeline, i) {
                        // Ensure this can work with search result columns too
                        return (

                                {pipeline.accession}
                                {pipeline.assay_term_name}
                                {swVers[i].version}
                                {swVers[i].download_checksum}

                        );
                    })}

                                {this.props.limit && (this.props.limit < this.props.total) ?

                                        {'Displaying '}{this.props.limit}{' pipelines out of '}{this.props.total}{' total related pipelines'}

                                : ''}

        );
    }
});
<commit_msg>Only include step parents in pipeline<commit_after>'use strict';
var React = require('react');
var url = require('url');
var _ = require('underscore');
var graph = require('./graph');
var globals = require('./globals');
var dbxref = require('./dbxref');
var search = require('./search');
var StatusLabel = require('./statuslabel').StatusLabel;
var Citation = require('./publication').Citation;
var audit = require('./audit');

var Graph = graph.Graph;
var JsonGraph = graph.JsonGraph;
var AuditIndicators = audit.AuditIndicators;
var AuditDetail = audit.AuditDetail;
var AuditMixin = audit.AuditMixin;

var DbxrefList = dbxref.DbxrefList;

var Panel = function (props) {
    // XXX not all panels have the same markup
    var context;
    if (props['@id']) {
        context = props;
        props = {context: context};
    }
    var PanelView = globals.panel_views.lookup(props.context);
    return <PanelView {...props} />;
};

var Pipeline = module.exports.Pipeline = React.createClass({
    mixins: [AuditMixin],

    getInitialState: function() {
        return {
            infoNodeId: '' // ID of node whose info panel is open
        };
    },

    assembleGraph: function() {
        var jsonGraph;
        var analysis_steps = this.props.context.analysis_steps;

        // Make an object with all step UUIDs in the pipeline
        var allSteps = {}
        analysis_steps.forEach(function(step) {
            allSteps[step.uuid] = step;
        });

        // Only produce a graph if there's at least one analysis step
        if (this.props.context.analysis_steps) {
            // Create an empty graph architecture
            jsonGraph = new JsonGraph(this.props.context.accession);

            // Add files and their steps as nodes to the graph
            analysis_steps.forEach(function(step) {
                var stepId = step['@id'];

                // Make an array of step types
                var stepTypesList = step.analysis_step_types.map(function(type) {
                    return type;
                });

                // Assemble a single analysis step node.
                jsonGraph.addNode(stepId, stepTypesList.join(', '),
                    {cssClass: 'pipeline-node-analysis-step' + (this.state.infoNodeId === stepId ? ' active' : ''), type: 'step', shape: 'rect', cornerRadius: 4, ref: step});

                // If the node has parents, render the edges to those parents
                if (step.parents && step.parents.length) {
                    step.parents.forEach(function(parent) {
                        if (parent.uuid in allSteps) {
                            jsonGraph.addEdge(parent['@id'], stepId);
                        }
                    });
                }
            }, this);

            // If any analysis step parents haven't been seen yet,
            // add them to the graph too
            analysis_steps.forEach(function(step) {
                if (step.parents && step.parents.length) {
                    step.parents.forEach(function(parent) {
                        if (parent.uuid in allSteps) {
                            var stepId = parent['@id'];
                            if (!jsonGraph.getNode(stepId)) {
                                // Make an array of step types
                                var stepTypesList = parent.analysis_step_types.map(function(type) {
                                    return type;
                                });

                                // Assemble a single analysis step node.
                                jsonGraph.addNode(stepId, stepTypesList.join(', '),
                                    {cssClass: 'pipeline-node-analysis-step' + (this.state.infoNodeId === stepId ? ' active' : ''), type: 'step', shape: 'rect', cornerRadius: 4, ref: parent});
                            }
                        }
                    }, this);
                }
            }, this);

        }
        return jsonGraph;
    },

    detailNodes: function(jsonGraph, infoNodeId) {
        var meta;

        // Find data matching selected node, if any
        if (infoNodeId) {
            var node = jsonGraph.getNode(infoNodeId);
            if (node) {
                meta = globals.graph_detail.lookup(node)(node);
            }
        }

        return meta;
    },

    handleNodeClick: function(e, nodeId) {
        e.stopPropagation(); e.preventDefault();
        this.setState({infoNodeId: this.state.infoNodeId !== nodeId ? nodeId : ''});
    },

    render: function() {
        var context = this.props.context;
        var itemClass = globals.itemClass(context, 'view-item');

        var documents = {};
        if (context.documents) {
            context.documents.forEach(function(doc, i) {
                documents[doc['@id']] = Panel({context: doc, key: i + 1});
            });
        }

        // Build node graph of the files and analysis steps with this experiment
        this.jsonGraph = this.assembleGraph();
        var meta = this.detailNodes(this.jsonGraph, this.state.infoNodeId);

        return (

{context.title}

                                <StatusLabel title="Status" status={context.status} />

                            <AuditIndicators audits={context.audit} id="biosample-audit" />

                <AuditDetail audits={context.audit} id="biosample-audit" />

Title

                            {context.source_url ?

{context.title}
 :

{context.title}

                            }

Assay

{context.assay_term_name}

                {context.analysis_steps && context.analysis_steps.length ?

Steps

                            {context.analysis_steps.map(function(props, i) {
                                return (

                                        {i > 0 ?
 : null}
                                        {AnalysisStep(props, i)}

                                );
                            })}

                : null}
                {Object.keys(documents).length ?

Documents

                            {documents}

                : null}
                {this.jsonGraph ?

Pipeline

                        <Graph graph={this.jsonGraph} nodeClickHandler={this.handleNodeClick}>

                                {meta ?
{meta}
 : null}

                        </Graph>

                : null}

        );
    }
});
globals.content_views.register(Pipeline, 'pipeline');

var AnalysisStep = module.exports.AnalysisStep = function (props, i) {
    var typesList = props.analysis_step_types.join(", ");

    return (

            {props.analysis_step_types.length ?

Category

{typesList}

            : null}
            {props.software_versions.length ?

 Software

                        {props.software_versions.map(function(software_version, i) {
                            return (  {
                                i > 0 ? ", ": ""
                            }
                            {software_version.software.title}
                            );
                        })}

            : null}

    );
};

// Display the metadata of the selected analysis step in the graph
var StepDetailView = module.exports.StepDetailView = function(node) {
    // The node is for a step. It can be called with analysis_step_run (for file graphs) or analysis_step (for pipeline graphs) nodes.
    // This code detects which is the case, and adjusts accordingly.
    var selectedStep = node.metadata.ref;
    var meta;

    if (selectedStep) {
        // The node is for an analysis step
        return (

Step type

{selectedStep.analysis_step_types.join(', ')}

Step name

{selectedStep.name}

                    {selectedStep.input_file_types && selectedStep.input_file_types.length ?

Input file types

{selectedStep.input_file_types.join(', ')}

                    : null}

                    {selectedStep.output_file_types && selectedStep.output_file_types.length ?

Output file types

{selectedStep.output_file_types.join(', ')}

                    : null}

                    {node.metadata.pipeline ?

Pipeline

{node.metadata.pipeline.title}

                    : null}

                    {selectedStep.qa_stats_generated && selectedStep.qa_stats_generated.length ?

QA statistics

{selectedStep.qa_stats_generated.join(', ')}

                    : null}

                    {selectedStep.software_versions && selectedStep.software_versions.length ?

Software

                                {selectedStep.software_versions.map(function(version, i) {
                                    var versionNum = version.version === 'unknown' ? 'version unknown' : version.version;
                                    return (

                                            {version.software.name}
                                            {version.version ?
                                                {versionNum}
                                            : null}

                                    );
                                })}

                    : null}

        );
    } else {
        return (
Missing step_run derivation information for {node.metadata.fileAccession}
);
    }
};

globals.graph_detail.register(StepDetailView, 'step');

var Listing = React.createClass({
    mixins: [search.PickerActionsMixin, AuditMixin],
    render: function() {
        var result = this.props.context;
        return (

                    {this.renderActions()}

Pipeline

                        {result.status ?
{' ' + result.status}
 : ''}
                        <AuditIndicators audits={result.audit} id={result['@id']} search />

                            {result['title']}

                <AuditDetail audits={result.audit} id={this.props.context['@id']} />

        );
    }
});
globals.listing_views.register(Listing, 'pipeline');

var PipelineTable = module.exports.PipelineTable = React.createClass({
    render: function() {
        var pipelines;

        // If there's a limit on entries to display and the array is greater than that
        // limit, then clone the array with just that specified number of elements
        if (this.props.limit && (this.props.limit < this.props.items.length)) {
            // Limit the pipelines list by cloning first {limit} elements
            pipelines = this.props.items.slice(0, this.props.limit);
        } else {
            // No limiting; just reference the original array
            pipelines = this.props.items;
        }

        // Get the software version numbers for all matching software
        var softwareId = url.parse(this.props.href).pathname;
        var swVers = [];
        pipelines.forEach(function(pipeline, i) {
            return pipeline.analysis_steps.some(function(analysis_step) {
                // Get the software_version object for any with a software @id matching softwareId, and save to array
                var matchedSwVers = _(analysis_step.software_versions).find(function(software_version) {
                    return software_version.software['@id'] === softwareId;
                });
                if (matchedSwVers) {
                    swVers[i] = matchedSwVers;
                }
                return matchedSwVers;
            });
        });

        return (

                            Pipeline
                            Assay
                            Version
                            Download checksum

                    {pipelines.map(function (pipeline, i) {
                        // Ensure this can work with search result columns too
                        return (

                                {pipeline.accession}
                                {pipeline.assay_term_name}
                                {swVers[i].version}
                                {swVers[i].download_checksum}

                        );
                    })}

                                {this.props.limit && (this.props.limit < this.props.total) ?

                                        {'Displaying '}{this.props.limit}{' pipelines out of '}{this.props.total}{' total related pipelines'}

                                : ''}

        );
    }
});
<|endoftext|>


<commit_before>import ModelArray from './model_array';

var get = Ember.get, set = Ember.set;

export default ModelArray.extend({

  name: null,
  owner: null,
  session: Ember.computed.alias('owner.session'),

  replace: function(idx, amt, objects) {
    if(this.session) {
      objects = objects.map(function(model) {
        return this.session.add(model);
      }, this);
    }
    return this._super(idx, amt, objects);
  },

  arrayContentWillChange: function(index, removed, added) {
    var model = get(this, 'owner'),
        name = get(this, 'name'),
        session = get(this, 'session');

    if(session) {
      session.modelWillBecomeDirty(model);
      if (!model._suspendedRelationships) {
        for (var i=index; i<index+removed; i++) {
          var inverseModel = this.objectAt(i);
          session.inverseManager.unregisterRelationship(model, name, inverseModel);
        }
      }
    }

    return this._super.apply(this, arguments);
  },

  arrayContentDidChange: function(index, removed, added) {
    this._super.apply(this, arguments);

    var model = get(this, 'owner'),
        name = get(this, 'name'),
        session = get(this, 'session');

    if (session && !model._suspendedRelationships) {
      for (var i=index; i<index+added; i++) {
        var inverseModel = this.objectAt(i);
        session.inverseManager.registerRelationship(model, name, inverseModel);
      }
    }
  },

});
<commit_msg>has_many now pulls from session on access<commit_after>import ModelArray from './model_array';

var get = Ember.get, set = Ember.set;

export default ModelArray.extend({

  name: null,
  owner: null,
  session: Ember.computed(function() {
    return get(this, 'owner.session');
  }).volatile(),

  replace: function(idx, amt, objects) {
    var session = get(this, 'session');

    if(session) {
      objects = objects.map(function(model) {
        return session.add(model);
      }, this);
    }
    return this._super(idx, amt, objects);
  },

  // XXX: this deviates from coalesce proper
  objectAtContent: function(index) {
    var content = get(this, 'content'),
        model = content.objectAt(index),
        session = get(this, 'session');

    if (session && model) {
      // This will replace proxies with their actual models
      // if they are loaded
      return session.add(model);
    }
    return model;
  },

  arrayContentWillChange: function(index, removed, added) {
    var model = get(this, 'owner'),
        name = get(this, 'name'),
        session = get(this, 'session');

    if(session) {
      session.modelWillBecomeDirty(model);
      if (!model._suspendedRelationships) {
        for (var i=index; i<index+removed; i++) {
          var inverseModel = this.objectAt(i);
          session.inverseManager.unregisterRelationship(model, name, inverseModel);
        }
      }
    }

    return this._super.apply(this, arguments);
  },

  arrayContentDidChange: function(index, removed, added) {
    this._super.apply(this, arguments);

    var model = get(this, 'owner'),
        name = get(this, 'name'),
        session = get(this, 'session');

    if (session && !model._suspendedRelationships) {
      for (var i=index; i<index+added; i++) {
        var inverseModel = this.objectAt(i);
        session.inverseManager.registerRelationship(model, name, inverseModel);
      }
    }
  },

});
<|endoftext|>


<commit_before>// @flow
import * as I from 'immutable'
import * as React from 'react'
import * as FsGen from '../../actions/fs-gen'
import * as Types from '../../constants/types/fs'
import * as Constants from '../../constants/fs'
import {globalStyles, globalColors, globalMargins, platformStyles} from '../../styles'
import {Box, ClickableBox, Text, Icon} from '../../common-adapters'
import {navigateUp} from '../../actions/route-tree'
import {connect, type Dispatch, type TypedState} from '../../util/container'
import {type BarePreviewProps} from './bare-preview'
import View from './view-container'

const mapStateToProps = (state: TypedState, {routeProps}: BarePreviewProps) => {
  const path = Types.stringToPath(routeProps.get('path', Constants.defaultPath))
  return {
    path,
    _pathItem: state.fs.pathItems.get(path) || Constants.makeUnknownPathItem(),
  }
}

const mapDispatchToProps = (dispatch: Dispatch, {routePath}) => ({
  onBack: () => dispatch(navigateUp()),
  _onAction: (path: Types.Path, type: Types.PathType, evt?: SyntheticEvent<>) =>
    dispatch(
      FsGen.createFileActionPopup({
        path,
        type,
        targetRect: Constants.syntheticEventToTargetRect(evt),
        routePath,
      })
    ),
})

const mergeProps = ({path, _pathItem}, {onBack, _onAction}, {routePath}) => ({
  path,
  routePath,
  onBack,
  onAction: (event: SyntheticEvent<>) => _onAction(path, _pathItem.type, event),
})

type ConnectedBarePreviewProps = {
  path: Types.Path,
  routePath: I.List<string>,

  onBack: () => void,
  onAction: (evt?: SyntheticEvent<>) => void,
}

const BarePreview = (props: ConnectedBarePreviewProps) => (
  <Box style={stylesContainer}>
    <Box style={stylesHeader}>
      <ClickableBox onClick={props.onBack}>
        <Text type="Body" style={stylesText}>
          Close
        </Text>
      </ClickableBox>
    </Box>
    <Box style={stylesContentContainer}>
      <View path={props.path} routePath={props.routePath} />
    </Box>
    <Box style={stylesFooter}>
      <Icon type="iconfont-ellipsis" onClick={props.onAction} color={globalColors.white} />
    </Box>
  </Box>
)

const stylesContainer = platformStyles({
  common: {
    ...globalStyles.flexBoxColumn,
    ...globalStyles.flexGrow,
    backgroundColor: globalColors.black,
  },
  isIOS: {
    marginTop: -20, // top status bar
  },
})

const stylesText = {
  color: globalColors.white,
}

const stylesHeader = {
  ...globalStyles.flexBoxRow,
  alignItems: 'center',
  height: 32,
  paddingLeft: globalMargins.tiny,
}

const stylesContentContainer = {
  ...globalStyles.flexGrow,
}

const stylesFooter = {
  ...globalStyles.flexBoxRow,
  alignItems: 'center',
  height: 32,
  paddingLeft: globalMargins.tiny,
}

export default connect(mapStateToProps, mapDispatchToProps, mergeProps)(BarePreview)
<commit_msg>fs: make images zoomable (#12400)<commit_after>// @flow
import * as I from 'immutable'
import * as React from 'react'
import * as FsGen from '../../actions/fs-gen'
import * as Types from '../../constants/types/fs'
import * as Constants from '../../constants/fs'
import {globalStyles, globalColors, globalMargins, platformStyles} from '../../styles'
import {Box, ClickableBox, Text, Icon} from '../../common-adapters'
import {ZoomableBox} from '../../common-adapters/mobile.native'
import {navigateUp} from '../../actions/route-tree'
import {connect, type Dispatch, type TypedState} from '../../util/container'
import {type BarePreviewProps} from './bare-preview'
import View from './view-container'

const mapStateToProps = (state: TypedState, {routeProps}: BarePreviewProps) => {
  const path = Types.stringToPath(routeProps.get('path', Constants.defaultPath))
  return {
    path,
    _pathItem: state.fs.pathItems.get(path) || Constants.makeUnknownPathItem(),
  }
}

const mapDispatchToProps = (dispatch: Dispatch, {routePath}) => ({
  onBack: () => dispatch(navigateUp()),
  _onAction: (path: Types.Path, type: Types.PathType, evt?: SyntheticEvent<>) =>
    dispatch(
      FsGen.createFileActionPopup({
        path,
        type,
        targetRect: Constants.syntheticEventToTargetRect(evt),
        routePath,
      })
    ),
})

const mergeProps = ({path, _pathItem}, {onBack, _onAction}, {routePath}) => ({
  path,
  routePath,
  onBack,
  onAction: (event: SyntheticEvent<>) => _onAction(path, _pathItem.type, event),
})

type ConnectedBarePreviewProps = {
  path: Types.Path,
  routePath: I.List<string>,

  onBack: () => void,
  onAction: (evt?: SyntheticEvent<>) => void,
}

const BarePreview = (props: ConnectedBarePreviewProps) => (
  <Box style={stylesContainer}>
    <Box style={stylesHeader}>
      <ClickableBox onClick={props.onBack}>
        <Text type="Body" style={stylesText}>
          Close
        </Text>
      </ClickableBox>
    </Box>
    <ZoomableBox
      contentContainerStyle={stylesContentContainer}
      maxZoom={10}
      showsHorizontalScrollIndicator={false}
      showsVerticalScrollIndicator={false}
    >
      <View path={props.path} routePath={props.routePath} />
    </ZoomableBox>
    <Box style={stylesFooter}>
      <Icon type="iconfont-ellipsis" onClick={props.onAction} color={globalColors.white} />
    </Box>
  </Box>
)

const stylesContainer = platformStyles({
  common: {
    ...globalStyles.flexBoxColumn,
    ...globalStyles.flexGrow,
    backgroundColor: globalColors.black,
  },
  isIOS: {
    marginTop: -20, // top status bar
  },
})

const stylesText = {
  color: globalColors.white,
}

const stylesHeader = {
  ...globalStyles.flexBoxRow,
  alignItems: 'center',
  height: 32,
  paddingLeft: globalMargins.tiny,
}

const stylesContentContainer = {
  ...globalStyles.flexGrow,
}

const stylesFooter = {
  ...globalStyles.flexBoxRow,
  alignItems: 'center',
  height: 32,
  paddingLeft: globalMargins.tiny,
}

export default connect(mapStateToProps, mapDispatchToProps, mergeProps)(BarePreview)
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2020 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.nanos.medusa',
  name: 'MedusaAdapterDAO',
  extends: 'foam.dao.ProxyDAO',

  documentation: `Entry point into the Medusa system.
This DAO intercepts MDAO 'put' operations and creates a medusa entry for argument model.
It then marshalls it to the primary mediator, and waits on a response.`,

  javaImports: [
    'foam.core.FObject',
    'foam.dao.DOP',
    'foam.dao.RemoveSink',
    'foam.lib.formatter.FObjectFormatter',
    'foam.lib.formatter.JSONFObjectFormatter',
    'foam.nanos.logger.PrefixLogger',
    'foam.nanos.logger.Logger',
    'foam.nanos.pm.PM',
    'foam.util.SafetyUtil'
  ],

  properties: [
    {
      name: 'nSpec',
      class: 'FObjectProperty',
      of: 'foam.nanos.boot.NSpec'
    },
    {
      name: 'medusaEntryDAO',
      class: 'FObjectProperty',
      of: 'foam.dao.DAO',
      javaFactory: 'return (foam.dao.DAO) getX().get("localMedusaEntryDAO");'
    },
    {
      name: 'clientDAO',
      class: 'FObjectProperty',
      of: 'foam.dao.DAO',
      javaFactory: `
      return new foam.nanos.medusa.ClusterClientDAO.Builder(getX())
        .setNSpec(getNSpec())
        .setDelegate(new foam.dao.NullDAO(getX(), getDelegate().getOf()))
        .build();
      `
    },
    {
      name: 'logger',
      class: 'FObjectProperty',
      of: 'foam.nanos.logger.Logger',
      visibility: 'HIDDEN',
      javaFactory: `
        return new PrefixLogger(new Object[] {
          this.getClass().getSimpleName(),
          getNSpec().getName()
        }, (Logger) getX().get("logger"));
      `
    }
  ],

  axioms: [
    {
      name: 'javaExtras',
      buildJavaClass: function(cls) {
        cls.extras.push(foam.java.Code.create({
          data: `
  protected static final ThreadLocal<FObjectFormatter> formatter_ = new ThreadLocal<FObjectFormatter>() {
    @Override
    protected JSONFObjectFormatter initialValue() {
      JSONFObjectFormatter formatter = new JSONFObjectFormatter();
      formatter.setQuoteKeys(false); // default
      formatter.setOutputShortNames(true); // default
      formatter.setOutputDefaultValues(true);
      formatter.setOutputClassNames(true); // default
      formatter.setOutputDefaultClassNames(true); // default
      formatter.setOutputReadableDates(false);
      formatter.setPropertyPredicate(new foam.lib.StoragePropertyPredicate());
      return formatter;
    }

    @Override
    public FObjectFormatter get() {
      FObjectFormatter formatter = super.get();
      formatter.reset();
      return formatter;
    }
  };
          `
        }));
      }
    }
  ],

  methods: [
    {
      name: 'put_',
      javaCode: `
      return update(x, obj, DOP.PUT);
      `
    },
    {
      name: 'remove_',
      javaCode: `
      return update(x, obj, DOP.REMOVE);
      `
    },
    {
      name: 'removeAll_',
      javaCode: `
      getDelegate().select_(x, new RemoveSink(x, this), skip, limit, order, predicate);
      `
    },
    {
      documentation: `
      1. If primary mediator, then delegate to medusaAdapter, accept result.
      2. If secondary mediator, proxy to next 'server', find result.
      3. If not mediator, proxy to the next 'server', put result.`,
      name: 'update',
      args: [
        {
          name: 'x',
          type: 'Context'
        },
        {
          name: 'obj',
          type: 'foam.core.FObject'
        },
        {
          name: 'dop',
          type: 'foam.dao.DOP'
        }
      ],
      javaType: 'foam.core.FObject',
      javaCode: `
      getLogger().debug("update");
      if ( ! ( DOP.PUT == dop ||
               DOP.REMOVE == dop ) ) {
        getLogger().warning("Unsupported operation", dop.getLabel());
        throw new UnsupportedOperationException(dop.getLabel());
      }

      if ( obj instanceof Clusterable &&
           ! ((Clusterable) obj).getClusterable() ) {
        getLogger().debug("update", dop.getLabel(), "not clusterable", obj.getClass().getSimpleName(), obj.getProperty("id").toString());
        if ( DOP.PUT == dop ) return getDelegate().put_(x, obj);
        if ( DOP.REMOVE == dop ) return getDelegate().remove_(x, obj);
      }

      ClusterConfigSupport support = (ClusterConfigSupport) x.get("clusterConfigSupport");
      ClusterConfig config = support.getConfig(x, support.getConfigId());

      if ( config.getIsPrimary() ) {
        // Primary instance - put to MDAO (delegate)

        ClusterCommand cmd = null;
        if ( obj instanceof ClusterCommand ) {
          cmd = (ClusterCommand) obj;
          obj = cmd.getData();
        }

        getLogger().debug("update", dop.getLabel(), "primary", obj.getClass().getSimpleName());
        FObject old = getDelegate().find_(x, obj.getProperty("id"));
        FObject nu = null;
        String data = null;
        if ( DOP.PUT == dop ) {
          nu = getDelegate().put_(x, obj);
          data = data(x, nu, old, dop);
        } else if ( DOP.REMOVE == dop ) {
          getDelegate().remove_(x, obj);
          data = data(x, obj, null, dop);
        }
        if ( SafetyUtil.isEmpty(data) ) {
          getLogger().debug("update", "primary", obj.getProperty("id"), "data", "no delta");
        } else {
          MedusaEntry entry = (MedusaEntry) submit(x, data, dop);
          if ( cmd != null ) {
            getLogger().debug("update", "primary", obj.getProperty("id"), "setMedusaEntryId", entry.toSummary());
            cmd.setMedusaEntryId((Long) entry.getId());
            if ( DOP.PUT == dop ) {
              cmd.setData(nu);
            } else if ( DOP.REMOVE == dop ) {
              cmd.setData(null);
            }
          }
        }
        if ( cmd != null ) {
          return cmd;
        }
        return nu;
      }

      ClusterCommand cmd = new ClusterCommand(x, getNSpec().getName(), dop, obj);
      getLogger().debug("update", dop.getLabel(), "client", "cmd", obj.getProperty("id"), "send");
      // PM pm = PM.create(x, this.getClass().getSimpleName(), "cmd");
      PM pm = new PM(this.getClass().getSimpleName(), "cmd");
      cmd = (ClusterCommand) getClientDAO().cmd_(x, cmd);
      pm.log(x);
      cmd.logHops(x);
      getLogger().debug("update", dop.getLabel(), "client", "cmd", obj.getProperty("id"), "receive", cmd.getMedusaEntryId());
      if ( DOP.PUT == dop ) {
        FObject result = cmd.getData();
        if ( result != null ) {
          FObject nu = getDelegate().find_(x, result.getProperty("id"));
          if ( nu == null ) {
            // Occurs if we've clustered a NullDAO (EasyDAO nullify)
            getLogger().warning("update", dop.getLabel(), "delegate", "find", result.getProperty("id"), "null");
          }
          return nu;
        }
        // TODO/REVIEW
        getLogger().warning("update", dop.getLabel(), obj.getProperty("id"), "result,null");
        return result;
      } else { // if ( DOP.REMOVE == dop ) {
        return getDelegate().remove_(x, obj);
      }
      `
    },
    {
      name: 'cmd_',
      javaCode: `
      getLogger().debug("cmd");
      if ( foam.dao.MDAO.GET_MDAO_CMD.equals(obj) ) {
        return getDelegate();
      }
      if ( obj instanceof ClusterCommand ) {
        ClusterConfigSupport support = (ClusterConfigSupport) x.get("clusterConfigSupport");
        ClusterConfig config = support.getConfig(x, support.getConfigId());
        ClusterCommand cmd = (ClusterCommand) obj;

        if ( config.getIsPrimary() ) {
          getLogger().debug("cmd", "ClusterCommand", "primary");
          if ( DOP.PUT == cmd.getDop() ) {
            return put_(x, cmd);
          } else if ( DOP.REMOVE == cmd.getDop() ) {
            return remove_(x, cmd);
          } else {
            getLogger().warning("Unsupported operation", cmd.getDop().getLabel());
            throw new UnsupportedOperationException(cmd.getDop().getLabel());
          }
        }

        getLogger().debug("cmd", "ClusterCommand", "non-primary");
        cmd = (ClusterCommand) getClientDAO().cmd_(x, obj);

        if ( config.getType() == MedusaType.MEDIATOR ) {
          Long id = cmd.getMedusaEntryId();
          if ( id != null &&
               id > 0L ) {
            MedusaRegistry registry = (MedusaRegistry) x.get("medusaRegistry");
            registry.wait(x, id);
          } else {
            getLogger().debug("cmd", "ClusterCommand", "medusaEntry", "null");
          }
        }
        getLogger().debug("cmd", "ClusterCommand", "return");
        return cmd;
      }
      getLogger().debug("cmd", "getClientDAO");
      return getClientDAO().cmd_(x, obj);
      `
    },
    {
      name: 'data',
      args: [
        {
          name: 'x',
          type: 'Context'
        },
        {
          name: 'obj',
          type: 'FObject'
        },
        {
          name: 'old',
          type: 'FObject'
        },
        {
          name: 'dop',
          type: 'foam.dao.DOP'
        }
      ],
      type: 'String',
      javaCode: `
      PM pm = PM.create(x, this.getClass().getSimpleName(), "data");
      String data = null;
      try {
        FObjectFormatter formatter = formatter_.get();
        if ( old != null ) {
          formatter.maybeOutputDelta(old, obj);
        } else {
          formatter.output(obj);
        }
        data = formatter.builder().toString();
      } finally {
        pm.log(x);
      }
      return data;
      `
    },
    {
      name: 'submit',
      args: [
        {
          name: 'x',
          type: 'Context'
        },
        {
          name: 'data',
          type: 'String'
        },
        {
          name: 'dop',
          type: 'foam.dao.DOP'
        }
      ],
      type: 'FObject',
      javaCode: `
      // PM pm = PM.create(x, this.getClass().getSimpleName(), "submit");
      PM pm = new PM(this.getClass().getSimpleName(), "submit");
      MedusaEntry entry = x.create(MedusaEntry.class);
      try {
        PM pmLink = new PM(this.getClass().getSimpleName(), "submit", "link");
        DaggerService dagger = (DaggerService) x.get("daggerService");
        entry = dagger.link(x, entry);
        entry.setNSpecName(getNSpec().getName());
        entry.setDop(dop);
        entry.setData(data);
        pmLink.log(x);

        getLogger().debug("submit", entry.getId());

        MedusaRegistry registry = (MedusaRegistry) x.get("medusaRegistry");
        registry.register(x, (Long) entry.getId());
        PM pmPut = new PM(this.getClass().getSimpleName(), "submit", "put");
        entry = (MedusaEntry) getMedusaEntryDAO().put_(x, entry);
        pmPut.log(x);
        PM pmWait = new PM(this.getClass().getSimpleName(), "submit", "wait");
        registry.wait(x, (Long) entry.getId());
        pmWait.log(x);
        return entry;
      } catch (Throwable t) {
        pm.error(x, entry.toSummary(), t);
        getLogger().error("submit", entry.toSummary(), t.getMessage(), t);
        throw t;
      } finally {
        pm.log(x);
      }
      `
    }
  ]
});
<commit_msg>Add additional logging to report detla after secondary -> primary put (#4737)<commit_after>/**
 * @license
 * Copyright 2020 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.nanos.medusa',
  name: 'MedusaAdapterDAO',
  extends: 'foam.dao.ProxyDAO',

  documentation: `Entry point into the Medusa system.
This DAO intercepts MDAO 'put' operations and creates a medusa entry for argument model.
It then marshalls it to the primary mediator, and waits on a response.`,

  javaImports: [
    'foam.core.FObject',
    'foam.dao.DOP',
    'foam.dao.RemoveSink',
    'foam.lib.formatter.FObjectFormatter',
    'foam.lib.formatter.JSONFObjectFormatter',
    'foam.nanos.logger.PrefixLogger',
    'foam.nanos.logger.Logger',
    'foam.nanos.pm.PM',
    'foam.util.SafetyUtil'
  ],

  properties: [
    {
      name: 'nSpec',
      class: 'FObjectProperty',
      of: 'foam.nanos.boot.NSpec'
    },
    {
      name: 'medusaEntryDAO',
      class: 'FObjectProperty',
      of: 'foam.dao.DAO',
      javaFactory: 'return (foam.dao.DAO) getX().get("localMedusaEntryDAO");'
    },
    {
      name: 'clientDAO',
      class: 'FObjectProperty',
      of: 'foam.dao.DAO',
      javaFactory: `
      return new foam.nanos.medusa.ClusterClientDAO.Builder(getX())
        .setNSpec(getNSpec())
        .setDelegate(new foam.dao.NullDAO(getX(), getDelegate().getOf()))
        .build();
      `
    },
    {
      name: 'logger',
      class: 'FObjectProperty',
      of: 'foam.nanos.logger.Logger',
      visibility: 'HIDDEN',
      javaFactory: `
        return new PrefixLogger(new Object[] {
          this.getClass().getSimpleName(),
          getNSpec().getName()
        }, (Logger) getX().get("logger"));
      `
    }
  ],

  axioms: [
    {
      name: 'javaExtras',
      buildJavaClass: function(cls) {
        cls.extras.push(foam.java.Code.create({
          data: `
  protected static final ThreadLocal<FObjectFormatter> formatter_ = new ThreadLocal<FObjectFormatter>() {
    @Override
    protected JSONFObjectFormatter initialValue() {
      JSONFObjectFormatter formatter = new JSONFObjectFormatter();
      formatter.setQuoteKeys(false); // default
      formatter.setOutputShortNames(true); // default
      formatter.setOutputDefaultValues(true);
      formatter.setOutputClassNames(true); // default
      formatter.setOutputDefaultClassNames(true); // default
      formatter.setOutputReadableDates(false);
      formatter.setPropertyPredicate(new foam.lib.StoragePropertyPredicate());
      return formatter;
    }

    @Override
    public FObjectFormatter get() {
      FObjectFormatter formatter = super.get();
      formatter.reset();
      return formatter;
    }
  };
          `
        }));
      }
    }
  ],

  methods: [
    {
      name: 'put_',
      javaCode: `
      return update(x, obj, DOP.PUT);
      `
    },
    {
      name: 'remove_',
      javaCode: `
      return update(x, obj, DOP.REMOVE);
      `
    },
    {
      name: 'removeAll_',
      javaCode: `
      getDelegate().select_(x, new RemoveSink(x, this), skip, limit, order, predicate);
      `
    },
    {
      documentation: `
      1. If primary mediator, then delegate to medusaAdapter, accept result.
      2. If secondary mediator, proxy to next 'server', find result.
      3. If not mediator, proxy to the next 'server', put result.`,
      name: 'update',
      args: [
        {
          name: 'x',
          type: 'Context'
        },
        {
          name: 'obj',
          type: 'foam.core.FObject'
        },
        {
          name: 'dop',
          type: 'foam.dao.DOP'
        }
      ],
      javaType: 'foam.core.FObject',
      javaCode: `
      getLogger().debug("update");
      if ( ! ( DOP.PUT == dop ||
               DOP.REMOVE == dop ) ) {
        getLogger().warning("Unsupported operation", dop.getLabel());
        throw new UnsupportedOperationException(dop.getLabel());
      }

      if ( obj instanceof Clusterable &&
           ! ((Clusterable) obj).getClusterable() ) {
        getLogger().debug("update", dop.getLabel(), "not clusterable", obj.getClass().getSimpleName(), obj.getProperty("id").toString());
        if ( DOP.PUT == dop ) return getDelegate().put_(x, obj);
        if ( DOP.REMOVE == dop ) return getDelegate().remove_(x, obj);
      }

      ClusterConfigSupport support = (ClusterConfigSupport) x.get("clusterConfigSupport");
      ClusterConfig config = support.getConfig(x, support.getConfigId());

      if ( config.getIsPrimary() ) {
        // Primary instance - put to MDAO (delegate)

        ClusterCommand cmd = null;
        if ( obj instanceof ClusterCommand ) {
          cmd = (ClusterCommand) obj;
          obj = cmd.getData();
        }

        getLogger().debug("update", dop.getLabel(), "primary", obj.getClass().getSimpleName());
        FObject old = getDelegate().find_(x, obj.getProperty("id"));
        FObject nu = null;
        String data = null;
        if ( DOP.PUT == dop ) {
          nu = getDelegate().put_(x, obj);
          data = data(x, nu, old, dop);
        } else if ( DOP.REMOVE == dop ) {
          getDelegate().remove_(x, obj);
          data = data(x, obj, null, dop);
        }
        if ( SafetyUtil.isEmpty(data) ) {
          getLogger().debug("update", "primary", obj.getProperty("id"), "data", "no delta");
        } else {
          MedusaEntry entry = (MedusaEntry) submit(x, data, dop);
          if ( cmd != null ) {
            getLogger().debug("update", "primary", obj.getProperty("id"), "setMedusaEntryId", entry.toSummary());
            cmd.setMedusaEntryId((Long) entry.getId());
            if ( DOP.PUT == dop ) {
              cmd.setData(nu);
            } else if ( DOP.REMOVE == dop ) {
              cmd.setData(null);
            }
          }
        }
        if ( cmd != null ) {
          return cmd;
        }
        return nu;
      }

      ClusterCommand cmd = new ClusterCommand(x, getNSpec().getName(), dop, obj);
      getLogger().debug("update", dop.getLabel(), "client", "cmd", obj.getProperty("id"), "send");
      // PM pm = PM.create(x, this.getClass().getSimpleName(), "cmd");
      PM pm = new PM(this.getClass().getSimpleName(), "cmd");
      cmd = (ClusterCommand) getClientDAO().cmd_(x, cmd);
      pm.log(x);
      cmd.logHops(x);
      getLogger().debug("update", dop.getLabel(), "client", "cmd", obj.getProperty("id"), "receive", cmd.getMedusaEntryId());
      if ( DOP.PUT == dop ) {
        FObject result = cmd.getData();
        if ( result != null ) {
          FObject nu = getDelegate().find_(x, result.getProperty("id"));
          if ( nu == null ) {
            // Occurs if we've clustered a NullDAO (EasyDAO nullify)
            getLogger().warning("update", dop.getLabel(), "cmd", "find", result.getProperty("id"), "null");
          } else {
            FObjectFormatter formatter = formatter_.get();
            if ( formatter.maybeOutputDelta(result, nu) ) {
              getLogger().warning("update", dop.getLabel(), "cmd", "delta", formatter.builder().toString());
            }
          }
          return nu;
        }
        // TODO/REVIEW
        getLogger().warning("update", dop.getLabel(), obj.getProperty("id"), "result,null");
        return result;
      } else { // if ( DOP.REMOVE == dop ) {
        return getDelegate().remove_(x, obj);
      }
      `
    },
    {
      name: 'cmd_',
      javaCode: `
      getLogger().debug("cmd");
      if ( foam.dao.MDAO.GET_MDAO_CMD.equals(obj) ) {
        return getDelegate();
      }
      if ( obj instanceof ClusterCommand ) {
        ClusterConfigSupport support = (ClusterConfigSupport) x.get("clusterConfigSupport");
        ClusterConfig config = support.getConfig(x, support.getConfigId());
        ClusterCommand cmd = (ClusterCommand) obj;

        if ( config.getIsPrimary() ) {
          getLogger().debug("cmd", "ClusterCommand", "primary");
          if ( DOP.PUT == cmd.getDop() ) {
            return put_(x, cmd);
          } else if ( DOP.REMOVE == cmd.getDop() ) {
            return remove_(x, cmd);
          } else {
            getLogger().warning("Unsupported operation", cmd.getDop().getLabel());
            throw new UnsupportedOperationException(cmd.getDop().getLabel());
          }
        }

        getLogger().debug("cmd", "ClusterCommand", "non-primary");
        cmd = (ClusterCommand) getClientDAO().cmd_(x, obj);

        if ( config.getType() == MedusaType.MEDIATOR ) {
          Long id = cmd.getMedusaEntryId();
          if ( id != null &&
               id > 0L ) {
            MedusaRegistry registry = (MedusaRegistry) x.get("medusaRegistry");
            registry.wait(x, id);
          } else {
            getLogger().debug("cmd", "ClusterCommand", "medusaEntry", "null");
          }
        }
        getLogger().debug("cmd", "ClusterCommand", "return");
        return cmd;
      }
      getLogger().debug("cmd", "getClientDAO");
      return getClientDAO().cmd_(x, obj);
      `
    },
    {
      name: 'data',
      args: [
        {
          name: 'x',
          type: 'Context'
        },
        {
          name: 'obj',
          type: 'FObject'
        },
        {
          name: 'old',
          type: 'FObject'
        },
        {
          name: 'dop',
          type: 'foam.dao.DOP'
        }
      ],
      type: 'String',
      javaCode: `
      PM pm = PM.create(x, this.getClass().getSimpleName(), "data");
      String data = null;
      try {
        FObjectFormatter formatter = formatter_.get();
        if ( old != null ) {
          formatter.maybeOutputDelta(old, obj);
        } else {
          formatter.output(obj);
        }
        data = formatter.builder().toString();
      } finally {
        pm.log(x);
      }
      return data;
      `
    },
    {
      name: 'submit',
      args: [
        {
          name: 'x',
          type: 'Context'
        },
        {
          name: 'data',
          type: 'String'
        },
        {
          name: 'dop',
          type: 'foam.dao.DOP'
        }
      ],
      type: 'FObject',
      javaCode: `
      // PM pm = PM.create(x, this.getClass().getSimpleName(), "submit");
      PM pm = new PM(this.getClass().getSimpleName(), "submit");
      MedusaEntry entry = x.create(MedusaEntry.class);
      try {
        PM pmLink = new PM(this.getClass().getSimpleName(), "submit", "link");
        DaggerService dagger = (DaggerService) x.get("daggerService");
        entry = dagger.link(x, entry);
        entry.setNSpecName(getNSpec().getName());
        entry.setDop(dop);
        entry.setData(data);
        pmLink.log(x);

        getLogger().debug("submit", entry.getId());

        MedusaRegistry registry = (MedusaRegistry) x.get("medusaRegistry");
        registry.register(x, (Long) entry.getId());
        PM pmPut = new PM(this.getClass().getSimpleName(), "submit", "put");
        entry = (MedusaEntry) getMedusaEntryDAO().put_(x, entry);
        pmPut.log(x);
        PM pmWait = new PM(this.getClass().getSimpleName(), "submit", "wait");
        registry.wait(x, (Long) entry.getId());
        pmWait.log(x);
        return entry;
      } catch (Throwable t) {
        pm.error(x, entry.toSummary(), t);
        getLogger().error("submit", entry.toSummary(), t.getMessage(), t);
        throw t;
      } finally {
        pm.log(x);
      }
      `
    }
  ]
});
<|endoftext|>


<commit_before>Package.describe({
  summary: "Logging facility.",
  version: '1.0.6'
});

Npm.depends({
  "cli-color": "0.2.3"
});

Npm.strip({
  "es5-ext": ["test/"]
});

Cordova.depends({
  'org.apache.cordova.console': '0.2.12'
});

Package.onUse(function (api) {
  api.export('Log');
  api.use(['underscore', 'ejson']);
  api.addFiles('logging.js');
  api.addFiles('logging_cordova.js', 'web.cordova');
});

Package.onTest(function (api) {
  api.use(['tinytest', 'underscore', 'ejson']);
  api.use('logging', ['client', 'server']);
  api.addFiles('logging_test.js', ['server', 'client']);
});
<commit_msg>Bump com.apache.cordova.console dep to 0.2.13<commit_after>Package.describe({
  summary: "Logging facility.",
  version: '1.0.6'
});

Npm.depends({
  "cli-color": "0.2.3"
});

Npm.strip({
  "es5-ext": ["test/"]
});

Cordova.depends({
  'org.apache.cordova.console': '0.2.13'
});

Package.onUse(function (api) {
  api.export('Log');
  api.use(['underscore', 'ejson']);
  api.addFiles('logging.js');
  api.addFiles('logging_cordova.js', 'web.cordova');
});

Package.onTest(function (api) {
  api.use(['tinytest', 'underscore', 'ejson']);
  api.use('logging', ['client', 'server']);
  api.addFiles('logging_test.js', ['server', 'client']);
});
<|endoftext|>


<commit_before>if (window.location.href.indexOf('kevinchappell.github.io') === -1) {
  ((window.gitter = {}).chat = {}).options = {
    room: 'kevinchappell/formBuilder'
  };

  var getStyles = function() {
    var styles = [];
    var extStyles = [
      '//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.2.0/styles/monokai-sublime.min.css'
    ];
    for (var i = extStyles.length - 1; i >= 0; i--) {
      var style = document.createElement('link');
      style.appendChild(document.createTextNode(''));
      style.setAttribute('href', extStyles[i]);
      style.setAttribute('rel', 'stylesheet');
      style.setAttribute('type', 'text/css');
      document.head.appendChild(style);
      styles.push(style);
    }
    return styles;
  };

  var getScripts = function() {
    var scripts = [];
    var extScripts = [
      '//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.2.0/highlight.min.js',
      'https://sidecar.gitter.im/dist/sidecar.v1.js'
    ];
    for (var i = extScripts.length - 1; i >= 0; i--) {
      var script = document.createElement('script');
      script.appendChild(document.createTextNode(''));
      script.setAttribute('src', extScripts[i]);
      script.setAttribute('type', 'text/javascript');
      document.body.appendChild(script);
      scripts.push(script);
    }
    return scripts;
  };

  getStyles();
  getScripts();

  document.addEventListener('viewData', function() {
    var code = document.querySelector('.data-dialog code');
    window.hljs.highlightBlock(code);
  }, false);

  (function(i, s, o, g, r, a, m) {
    i['GoogleAnalyticsObject'] = r;
    i[r] = i[r] || function() {
      (i[r].q = i[r].q || []).push(arguments);
    }, i[r].l = 1 * new Date();
    a = s.createElement(o),
      m = s.getElementsByTagName(o)[0];
    a.async = 1;
    a.src = g;
    m.parentNode.insertBefore(a, m);
  })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');

  ga('create', 'UA-4784386-21', 'auto');
  ga('send', 'pageview');
}
<commit_msg>minor update 3rd party script for demo<commit_after>if (window.location.href.indexOf('kevinchappell.github.io') !== -1) {
  ((window.gitter = {}).chat = {}).options = {
    room: 'kevinchappell/formBuilder'
  };

  var getStyles = function() {
    var styles = [];
    var extStyles = [
      '//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.2.0/styles/monokai-sublime.min.css'
    ];
    for (var i = extStyles.length - 1; i >= 0; i--) {
      var style = document.createElement('link');
      style.appendChild(document.createTextNode(''));
      style.setAttribute('href', extStyles[i]);
      style.setAttribute('rel', 'stylesheet');
      style.setAttribute('type', 'text/css');
      document.head.appendChild(style);
      styles.push(style);
    }
    return styles;
  };

  var getScripts = function() {
    var scripts = [];
    var extScripts = [
      '//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.2.0/highlight.min.js',
      'https://sidecar.gitter.im/dist/sidecar.v1.js'
    ];
    for (var i = extScripts.length - 1; i >= 0; i--) {
      var script = document.createElement('script');
      script.appendChild(document.createTextNode(''));
      script.setAttribute('src', extScripts[i]);
      script.setAttribute('type', 'text/javascript');
      document.body.appendChild(script);
      scripts.push(script);
    }
    return scripts;
  };

  getStyles();
  getScripts();

  document.addEventListener('viewData', function() {
    var code = document.querySelector('.data-dialog code');
    window.hljs.highlightBlock(code);
  }, false);

  (function(i, s, o, g, r, a, m) {
    i['GoogleAnalyticsObject'] = r;
    i[r] = i[r] || function() {
      (i[r].q = i[r].q || []).push(arguments);
    }, i[r].l = 1 * new Date();
    a = s.createElement(o),
      m = s.getElementsByTagName(o)[0];
    a.async = 1;
    a.src = g;
    m.parentNode.insertBefore(a, m);
  })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');

  ga('create', 'UA-4784386-21', 'auto');
  ga('send', 'pageview');
}
<|endoftext|>


<commit_before>
var data, labels;
var layer_defs, net, trainer;

// create neural net
var t = "layer_defs = [];\n\
layer_defs.push({type:'input', out_sx:1, out_sy:1, out_depth:2}); // 2 inputs: x, y \n\
layer_defs.push({type:'fc', num_neurons:20, activation:'relu'});\n\
layer_defs.push({type:'fc', num_neurons:20, activation:'relu'});\n\
layer_defs.push({type:'fc', num_neurons:20, activation:'relu'});\n\
layer_defs.push({type:'fc', num_neurons:20, activation:'relu'});\n\
layer_defs.push({type:'fc', num_neurons:20, activation:'relu'});\n\
layer_defs.push({type:'fc', num_neurons:20, activation:'relu'});\n\
layer_defs.push({type:'fc', num_neurons:20, activation:'relu'});\n\
layer_defs.push({type:'regression', num_neurons:3}); // 3 outputs: r,g,b \n\
\n\
net = new convnetjs.Net();\n\
net.makeLayers(layer_defs);\n\
\n\
trainer = new convnetjs.SGDTrainer(net, {learning_rate:0.01, momentum:0.9, batch_size:5, l2_decay:0.0});\n\
";

var batches_per_iteration = 100;
var mod_skip_draw = 100;
var smooth_loss = -1;

function update(){
  // forward prop the data
  var W = nn_canvas.width;
  var H = nn_canvas.height;

  var p = oridata.data;// Original Color Data

  var v = new convnetjs.Vol(1,1,2);
  var loss = 0;
  var lossi = 0;
  var N = batches_per_iteration;
  for(var iters=0;iters<trainer.batch_size;iters++) {
    for(var i=0;i<N;i++) {
      // sample a coordinate
      var x = convnetjs.randi(0, W);//Get Random Coordinate for Trainning
      var y = convnetjs.randi(0, H);
      var ix = ((W*y)+x)*4; //Start color data index
      var r = [p[ix]/255.0, p[ix+1]/255.0, p[ix+2]/255.0]; //Get r g b value 0~1
      v.w[0] = (x-W/2)/W; //Get Coordinate x -0.5~0.5
      v.w[1] = (y-H/2)/H; //Get Coordinate y -0.5~0.5
      var stats = trainer.train(v, r); //Train net by Coordinate & Color
      loss += stats.loss; //Add Loss of pixel
      lossi += 1; //Increase learning count
    }
  }
  loss /= lossi; //Get Final loss

  if(counter === 0) smooth_loss = loss; //First tick, assign loss to smooth_loss
  else smooth_loss = 0.99*smooth_loss + 0.01*loss; //Next Tick, add 1% effect to smooth_loss based on current loss

  var t = '';
  t += 'loss: ' + smooth_loss;
  t += '
'
  t += 'iteration: ' + counter;
  $("#report").html(t); //Display current loss & iteration
}

//Draw target image
function draw() {
  if(counter % mod_skip_draw !== 0) return;

  // iterate over all pixels in the target array, evaluate them
  // and draw
  var W = nn_canvas.width;
  var H = nn_canvas.height;

  var g = nn_ctx.getImageData(0, 0, W, H);
  var v = new convnetjs.Vol(1, 1, 2);
  for(var x=0;x<W;x++) {
    v.w[0] = (x-W/2)/W;
    for(var y=0;y<H;y++) {
      v.w[1] = (y-H/2)/H;

      var ix = ((W*y)+x)*4; // Start color data index
      var r = net.forward(v); //Input coordinate and get forward color output
      g.data[ix+0] = Math.floor(255*r.w[0]); //Red
      g.data[ix+1] = Math.floor(255*r.w[1]); //Green
      g.data[ix+2] = Math.floor(255*r.w[2]); //Blue
      g.data[ix+3] = 255; // alpha...
    }
  }
  nn_ctx.putImageData(g, 0, 0);
}

function tick() {
  update();
  draw();
  counter += 1; //Increase Tick Count
}

function reload() {
  counter = 0;
  eval($("#layerdef").val());
  //$("#slider").slider("value", Math.log(trainer.learning_rate) / Math.LN10);
  //$("#lr").html('Learning rate: ' + trainer.learning_rate);
}
function refreshSwatch() {
  var lr = $("#slider").slider("value");
  trainer.learning_rate = Math.pow(10, lr);
  $("#lr").html('Learning rate: ' + trainer.learning_rate);
}

var ori_canvas, nn_canvas, ori_ctx, nn_ctx, oridata;
var sz = 200; // size of our drawing area
var counter = 0;
$(function() {
    // dynamically load lena image into original image canvas
    var image = new Image();
    //image.src = "lena.png";
    image.onload = function() {

      ori_canvas = document.getElementById('canv_original');
      nn_canvas = document.getElementById('canv_net');
      ori_canvas.width = sz;
      ori_canvas.height = sz;
      nn_canvas.width = sz;
      nn_canvas.height = sz;

      ori_ctx = ori_canvas.getContext("2d");
      nn_ctx = nn_canvas.getContext("2d");
      ori_ctx.drawImage(image, 0, 0, sz, sz);
      oridata = ori_ctx.getImageData(0, 0, sz, sz); // grab the data pointer. Our dataset.

      // start the regression!
      setInterval(tick, 1);
    }
    image.src = "imgs/cat.jpg";

    // init put text into textarea
    $("#layerdef").val(t);

    // load the net
    reload();

    // set up slider for learning rate
    $("#slider").slider({
      orientation: "horizontal",
      min: -4,
      max: -1,
      step: 0.05,
      value: Math.log(trainer.learning_rate) / Math.LN10,
      slide: refreshSwatch,
      change: refreshSwatch
    });
    $("#lr").html('Learning rate: ' + trainer.learning_rate);

    $("#f").on('change', function(ev) {
      var f = ev.target.files[0];
      var fr = new FileReader();
      fr.onload = function(ev2) {
        var image = new Image();
        image.onload = function(){
          ori_ctx.drawImage(image, 0, 0, sz, sz);
          oridata = ori_ctx.getImageData(0, 0, sz, sz);
          reload();
        }
        image.src = ev2.target.result;
      };
      fr.readAsDataURL(f);
    });

    $('.ci').click(function(){
      var src = $(this).attr('src');
      ori_ctx.drawImage(this, 0, 0, sz, sz);
      oridata = ori_ctx.getImageData(0, 0, sz, sz);
      reload();
    });
});
<commit_msg>Comment Ticker<commit_after>
var data, labels;
var layer_defs, net, trainer;

// create neural net
var t = "layer_defs = [];\n\
layer_defs.push({type:'input', out_sx:1, out_sy:1, out_depth:2}); // 2 inputs: x, y \n\
layer_defs.push({type:'fc', num_neurons:20, activation:'relu'});\n\
layer_defs.push({type:'fc', num_neurons:20, activation:'relu'});\n\
layer_defs.push({type:'fc', num_neurons:20, activation:'relu'});\n\
layer_defs.push({type:'fc', num_neurons:20, activation:'relu'});\n\
layer_defs.push({type:'fc', num_neurons:20, activation:'relu'});\n\
layer_defs.push({type:'fc', num_neurons:20, activation:'relu'});\n\
layer_defs.push({type:'fc', num_neurons:20, activation:'relu'});\n\
layer_defs.push({type:'regression', num_neurons:3}); // 3 outputs: r,g,b \n\
\n\
net = new convnetjs.Net();\n\
net.makeLayers(layer_defs);\n\
\n\
trainer = new convnetjs.SGDTrainer(net, {learning_rate:0.01, momentum:0.9, batch_size:5, l2_decay:0.0});\n\
";

var batches_per_iteration = 100;
var mod_skip_draw = 100;
var smooth_loss = -1;

function update(){
  // forward prop the data
  var W = nn_canvas.width;
  var H = nn_canvas.height;

  var p = oridata.data;// Original Color Data

  var v = new convnetjs.Vol(1,1,2);
  var loss = 0;
  var lossi = 0;
  var N = batches_per_iteration;
  for(var iters=0;iters<trainer.batch_size;iters++) {
    for(var i=0;i<N;i++) {
      // sample a coordinate
      var x = convnetjs.randi(0, W);//Get Random Coordinate for Trainning
      var y = convnetjs.randi(0, H);
      var ix = ((W*y)+x)*4; //Start color data index
      var r = [p[ix]/255.0, p[ix+1]/255.0, p[ix+2]/255.0]; //Get r g b value 0~1
      v.w[0] = (x-W/2)/W; //Get Coordinate x -0.5~0.5
      v.w[1] = (y-H/2)/H; //Get Coordinate y -0.5~0.5
      var stats = trainer.train(v, r); //Train net by Coordinate & Color
      loss += stats.loss; //Add Loss of pixel
      lossi += 1; //Increase learning count
    }
  }
  loss /= lossi; //Get Final loss

  if(counter === 0) smooth_loss = loss; //First tick, assign loss to smooth_loss
  else smooth_loss = 0.99*smooth_loss + 0.01*loss; //Next Tick, add 1% effect to smooth_loss based on current loss

  var t = '';
  t += 'loss: ' + smooth_loss;
  t += '
'
  t += 'iteration: ' + counter;
  $("#report").html(t); //Display current loss & iteration
}

//Draw target image
function draw() {
  if(counter % mod_skip_draw !== 0) return;

  // iterate over all pixels in the target array, evaluate them
  // and draw
  var W = nn_canvas.width;
  var H = nn_canvas.height;

  var g = nn_ctx.getImageData(0, 0, W, H);
  var v = new convnetjs.Vol(1, 1, 2);
  //Forward Net for each coordinate to get full image
  for(var x=0;x<W;x++) { //Loop for each x coordinate
    v.w[0] = (x-W/2)/W;
    for(var y=0;y<H;y++) { //Loop for each y coordinate
      v.w[1] = (y-H/2)/H;
      var ix = ((W*y)+x)*4; // Start color data index
      var r = net.forward(v); //Input coordinate and get forward color output
      g.data[ix+0] = Math.floor(255*r.w[0]); //Red
      g.data[ix+1] = Math.floor(255*r.w[1]); //Green
      g.data[ix+2] = Math.floor(255*r.w[2]); //Blue
      g.data[ix+3] = 255; // alpha...
    }
  }
  nn_ctx.putImageData(g, 0, 0);
}

function tick() {
  update();
  draw();
  counter += 1; //Increase Tick Count
}

function reload() {
  counter = 0;
  eval($("#layerdef").val());
  //$("#slider").slider("value", Math.log(trainer.learning_rate) / Math.LN10);
  //$("#lr").html('Learning rate: ' + trainer.learning_rate);
}
function refreshSwatch() {
  var lr = $("#slider").slider("value");
  trainer.learning_rate = Math.pow(10, lr);
  $("#lr").html('Learning rate: ' + trainer.learning_rate);
}

var ori_canvas, nn_canvas, ori_ctx, nn_ctx, oridata;
var sz = 200; // size of our drawing area
var counter = 0;
$(function() {
    // dynamically load lena image into original image canvas
    var image = new Image();
    //image.src = "lena.png";
    image.onload = function() {

      ori_canvas = document.getElementById('canv_original');
      nn_canvas = document.getElementById('canv_net');
      ori_canvas.width = sz;
      ori_canvas.height = sz;
      nn_canvas.width = sz;
      nn_canvas.height = sz;

      ori_ctx = ori_canvas.getContext("2d");
      nn_ctx = nn_canvas.getContext("2d");
      ori_ctx.drawImage(image, 0, 0, sz, sz);
      oridata = ori_ctx.getImageData(0, 0, sz, sz); // grab the data pointer. Our dataset.

      // start the regression!
      setInterval(tick, 1); //Tick per 1 ms
    }
    image.src = "imgs/cat.jpg";

    // init put text into textarea
    $("#layerdef").val(t);

    // load the net
    reload();

    // set up slider for learning rate
    $("#slider").slider({
      orientation: "horizontal",
      min: -4,
      max: -1,
      step: 0.05,
      value: Math.log(trainer.learning_rate) / Math.LN10,
      slide: refreshSwatch,
      change: refreshSwatch
    });
    $("#lr").html('Learning rate: ' + trainer.learning_rate);

    $("#f").on('change', function(ev) {
      var f = ev.target.files[0];
      var fr = new FileReader();
      fr.onload = function(ev2) {
        var image = new Image();
        image.onload = function(){
          ori_ctx.drawImage(image, 0, 0, sz, sz);
          oridata = ori_ctx.getImageData(0, 0, sz, sz);
          reload();
        }
        image.src = ev2.target.result;
      };
      fr.readAsDataURL(f);
    });

    $('.ci').click(function(){
      var src = $(this).attr('src');
      ori_ctx.drawImage(this, 0, 0, sz, sz);
      oridata = ori_ctx.getImageData(0, 0, sz, sz);
      reload();
    });
});
<|endoftext|>


<commit_before>/* @flow */

import { Card, CardTitle, CardMedia, CardActions } from "material-ui/Card";
import Chip from "material-ui/Chip";
import MoreVertIcon from "material-ui/svg-icons/navigation/more-vert";
import Dialog from "material-ui/Dialog";
import Download from "material-ui/svg-icons/file/file-download";
import IconMenu from "material-ui/IconMenu";
import IconButton from "material-ui/IconButton";
import MenuItem from "material-ui/MenuItem";
import RaisedButton from "material-ui/RaisedButton";
import { grey400 } from "material-ui/styles/colors";
import * as React from "react";
import { createFragmentContainer, graphql } from "react-relay";

import { flattenPermissions } from "../utils";
import theme from "../theme";
import type { PermissionArray, PermissionObject, Viewer } from "../types";

import PermissionChips from "./PermissionChips";
import PermissionField from "./PermissionField";
import TagField from "./TagField";

type Props = {
  id: string,
  filename: string,
  isImage: boolean,
  memberGroupId: string,
  onSavePermissions: (string, PermissionArray, string[], () => void) => {},
  onSetProjectPoster: (string) => {},
  organization: {},
  permissions: PermissionObject,
  path: string,
  searchTag: (string) => {},
  tags: string[],
  thumbnailPath: string,
  viewer: Viewer,
};

type State = {
  editPermissions: boolean,
  permissions: PermissionArray,
  tags: string[],
};

class FileItem extends React.Component<Props, State> {
  state = {
    editPermissions: false,
    permissions: flattenPermissions(this.props.permissions),
    tags: this.props.tags || [],
  };

  onPermissionChange = (permissions) => {
    this.setState({ permissions });
  };

  onTagChange = (tags) => {
    this.setState({ tags });
  };

  setProjectPoster = () => {
    this.props.onSetProjectPoster(this.props.id);
  };

  savePermissions = (event) => {
    event.preventDefault();
    this.props.onSavePermissions(
      this.props.id,
      this.state.permissions,
      this.state.tags,
      () => {
        this.setState({
          editPermissions: false,
        });
      },
    );
  };

  closeEditPermissions = () => {
    this.setState({
      editPermissions: false,
    });
  };

  toggleEditPermissions = () => {
    this.setState({
      editPermissions: !this.state.editPermissions,
    });
  };

  searchTag = (tag) => {
    this.props.searchTag(tag);
  };

  render() {
    const { desktopGutterLess } = theme.spacing;
    return (
      <Card
        key={this.props.id}
        style={{
          width: 300,
          marginLeft: desktopGutterLess,
          marginRight: desktopGutterLess,
          marginBottom: desktopGutterLess,
        }}
      >
        <CardTitle style={{ paddingBottom: 0 }}>

            <IconMenu
              iconButtonElement={
                <IconButton
                  style={{ padding: 0, height: "inherit", width: "inherit" }}
                >
                  <MoreVertIcon />
                </IconButton>
              }
              anchorOrigin={{ vertical: "top", horizontal: "right" }}
              targetOrigin={{ vertical: "top", horizontal: "right" }}
            >
              <MenuItem
                primaryText="Rediger filegenskaper"
                onTouchTap={this.toggleEditPermissions}
              />
              {this.props.onSetProjectPoster ? (
                <MenuItem
                  primaryText="Bruk som prosjektplakat"
                  onTouchTap={this.setProjectPoster}
                />
              ) : null}
            </IconMenu>

            {this.props.filename}

        </CardTitle>
        {this.props.isImage ? (
          <CardMedia>

          </CardMedia>
        ) : (

            <Download style={{ height: 100, width: "100%" }} color={grey400} />

        )}
        <CardActions style={{ display: "flex", flexWrap: "wrap" }}>
          <PermissionChips
            memberGroupId={this.props.memberGroupId}
            permissions={flattenPermissions(this.props.permissions)}
          />
          {this.props.tags &&
            this.props.tags.map((tag) => {
              return (
                <Chip
                  key={tag}
                  onTouchTap={() => {
                    this.searchTag(tag);
                  }}
                >
                  {tag}
                </Chip>
              );
            })}
        </CardActions>
        {this.state.editPermissions ? (
          <Dialog
            title="Rediger rettigheter"
            open={this.state.editPermissions}
            onRequestClose={this.closeEditPermissions}
            autoScrollBodyContent
          >
            <PermissionField
              permissions={this.state.permissions}
              onChange={this.onPermissionChange}
              groups={this.props.viewer.groups}
              users={[]}
            />
            <TagField
              organization={this.props.organization}
              onChange={this.onTagChange}
              fileTags={this.state.tags}
            />
            <RaisedButton
              label="Lagre"
              onClick={this.savePermissions}
              primary
            />
          </Dialog>
        ) : null}
      </Card>
    );
  }
}

export default createFragmentContainer(FileItem, {
  organization: graphql`
    fragment FileItem_organization on Organization {
      ...TagField_organization
    }
  `,
});
<commit_msg>Show four files per row in file list<commit_after>/* @flow */

import { Card, CardTitle, CardMedia, CardActions } from "material-ui/Card";
import Chip from "material-ui/Chip";
import MoreVertIcon from "material-ui/svg-icons/navigation/more-vert";
import Dialog from "material-ui/Dialog";
import Download from "material-ui/svg-icons/file/file-download";
import IconMenu from "material-ui/IconMenu";
import IconButton from "material-ui/IconButton";
import MenuItem from "material-ui/MenuItem";
import RaisedButton from "material-ui/RaisedButton";
import { grey400 } from "material-ui/styles/colors";
import * as React from "react";
import { createFragmentContainer, graphql } from "react-relay";

import { flattenPermissions } from "../utils";
import theme from "../theme";
import type { PermissionArray, PermissionObject, Viewer } from "../types";

import PermissionChips from "./PermissionChips";
import PermissionField from "./PermissionField";
import TagField from "./TagField";

type Props = {
  id: string,
  filename: string,
  isImage: boolean,
  memberGroupId: string,
  onSavePermissions: (string, PermissionArray, string[], () => void) => {},
  onSetProjectPoster: (string) => {},
  organization: {},
  permissions: PermissionObject,
  path: string,
  searchTag: (string) => {},
  tags: string[],
  thumbnailPath: string,
  viewer: Viewer,
};

type State = {
  editPermissions: boolean,
  permissions: PermissionArray,
  tags: string[],
};

class FileItem extends React.Component<Props, State> {
  state = {
    editPermissions: false,
    permissions: flattenPermissions(this.props.permissions),
    tags: this.props.tags || [],
  };

  onPermissionChange = (permissions) => {
    this.setState({ permissions });
  };

  onTagChange = (tags) => {
    this.setState({ tags });
  };

  setProjectPoster = () => {
    this.props.onSetProjectPoster(this.props.id);
  };

  savePermissions = (event) => {
    event.preventDefault();
    this.props.onSavePermissions(
      this.props.id,
      this.state.permissions,
      this.state.tags,
      () => {
        this.setState({
          editPermissions: false,
        });
      },
    );
  };

  closeEditPermissions = () => {
    this.setState({
      editPermissions: false,
    });
  };

  toggleEditPermissions = () => {
    this.setState({
      editPermissions: !this.state.editPermissions,
    });
  };

  searchTag = (tag) => {
    this.props.searchTag(tag);
  };

  render() {
    const { desktopGutterLess } = theme.spacing;
    return (
      <Card
        key={this.props.id}
        style={{
          width: 216,
          marginLeft: desktopGutterLess,
          marginRight: desktopGutterLess,
          marginBottom: desktopGutterLess,
        }}
      >
        <CardTitle style={{ paddingBottom: 0 }}>

            <IconMenu
              iconButtonElement={
                <IconButton
                  style={{ padding: 0, height: "inherit", width: "inherit" }}
                >
                  <MoreVertIcon />
                </IconButton>
              }
              anchorOrigin={{ vertical: "top", horizontal: "right" }}
              targetOrigin={{ vertical: "top", horizontal: "right" }}
            >
              <MenuItem
                primaryText="Rediger filegenskaper"
                onTouchTap={this.toggleEditPermissions}
              />
              {this.props.onSetProjectPoster ? (
                <MenuItem
                  primaryText="Bruk som prosjektplakat"
                  onTouchTap={this.setProjectPoster}
                />
              ) : null}
            </IconMenu>

            {this.props.filename}

        </CardTitle>
        {this.props.isImage ? (
          <CardMedia>

          </CardMedia>
        ) : (

            <Download style={{ height: 100, width: "100%" }} color={grey400} />

        )}
        <CardActions style={{ display: "flex", flexWrap: "wrap" }}>
          <PermissionChips
            memberGroupId={this.props.memberGroupId}
            permissions={flattenPermissions(this.props.permissions)}
          />
          {this.props.tags &&
            this.props.tags.map((tag) => {
              return (
                <Chip
                  key={tag}
                  onTouchTap={() => {
                    this.searchTag(tag);
                  }}
                >
                  {tag}
                </Chip>
              );
            })}
        </CardActions>
        {this.state.editPermissions ? (
          <Dialog
            title="Rediger rettigheter"
            open={this.state.editPermissions}
            onRequestClose={this.closeEditPermissions}
            autoScrollBodyContent
          >
            <PermissionField
              permissions={this.state.permissions}
              onChange={this.onPermissionChange}
              groups={this.props.viewer.groups}
              users={[]}
            />
            <TagField
              organization={this.props.organization}
              onChange={this.onTagChange}
              fileTags={this.state.tags}
            />
            <RaisedButton
              label="Lagre"
              onClick={this.savePermissions}
              primary
            />
          </Dialog>
        ) : null}
      </Card>
    );
  }
}

export default createFragmentContainer(FileItem, {
  organization: graphql`
    fragment FileItem_organization on Organization {
      ...TagField_organization
    }
  `,
});
<|endoftext|>


<commit_before>import {join} from 'path';
import pascalCase from 'pascal-case';
import merge from 'lodash.merge';
import template from './react-class.tmpl';

export default function createReactCodeFactory(application) {
	const config = application.configuration.transforms['react'] || {};

	return async function createReactCode(file, demo) {
		let result = convertCode(file);
		if (demo) {
			demo.dependencies = {
				pattern: file
			};
			merge(demo.dependencies, file.dependencies);
			let demoResult = convertCode(demo);
			file.demoSource = demo.source;
			file.demoBuffer = new Buffer(demoResult, 'utf-8');
		}

		file.buffer = result;
		file.in = config.inFormat;
		file.out = config.outFormat;
		return file;
	}
}

function convertCode(file, removeReact = false) {
	let source = file.buffer.toString('utf-8');
	if (source.indexOf('export default class') === -1 || source.indexOf('React.createClass') !== -1)	 {
		source = createWrappedRenderFunction(file, source);
	}
	let dependencies = convertDependencies(file);
	return fixDependencyImports(source, dependencies, removeReact);
}

function createWrappedRenderFunction(file, source) {
	let patternJson = loadPatternJson(file.path);
	let dependencies = writeDependencyImports(file).join('\n');
	return renderCodeTemplate(source, dependencies, template, pascalCase(patternJson.name));
}

function loadPatternJson(path) {
	return require(
		join(
			path.substring(0,
				path.lastIndexOf('/')), 'pattern.json'));
}

function writeDependencyImports(file) {
	let dependencies = [];
	for (let dependencyName of Object.keys(file.dependencies)) {
		dependencies.push(`import ${pascalCase(dependencyName)} from '${dependencyName}';`);
	}
	return dependencies;
}

function renderCodeTemplate(source, dependencies, template, className) {
	return template
		.replace('$$dependencies$$', dependencies)
		.replace('$$class-name$$', className)
		.replace('$$render-code$$', matchFirstJsxExpressionAndWrapWithReturn(source));
}

function matchFirstJsxExpressionAndWrapWithReturn(source) {
	return source
		.replace(/(<[a-z0-9]+(?:\s+[a-z0-9]+=["{][^"}]*?["}]|\s+\{\.\.\.[^}]+\})*\s*\/?>[^]*)/gi,
			'return (\n$1\n);')
}

function convertDependencies(file) {
	let dependencies = {};
	for (let dependencyName of Object.keys(file.dependencies)) {
		let dependencyFile = file.dependencies[dependencyName];
		dependencies[dependencyName] = convertCode(dependencyFile, true);
	}
	return dependencies;
}

function fixDependencyImports(source, dependencies, removeReact) {
	// Replace import statements (but react) with a dumb module loader
	return source.replace(/^\s*import\s+(?:\*\s+as\s+)?(.*?)\s+from\s+['"]([-_a-zA-Z0-9]+)['"].*$/gm, (match, name, module) => {
		if (name === 'React' || module === 'react') {
			if (removeReact) {
				return '';
			}
			return "import * as React from 'react'";
		}
		return `let ${name} = (() => {
			${dependencies[module].replace("import * as React from 'react';", '').replace('export default ', 'return ')}
		})();
		`;
	})
}
<commit_msg>Splitted attribute regexp between jsx and html<commit_after>import {join} from 'path';
import pascalCase from 'pascal-case';
import merge from 'lodash.merge';
import template from './react-class.tmpl';

export default function createReactCodeFactory(application) {
	const config = application.configuration.transforms['react'] || {};

	return async function createReactCode(file, demo) {
		let result = convertCode(file);
		if (demo) {
			demo.dependencies = {
				pattern: file
			};
			merge(demo.dependencies, file.dependencies);
			let demoResult = convertCode(demo);
			file.demoSource = demo.source;
			file.demoBuffer = new Buffer(demoResult, 'utf-8');
		}

		file.buffer = result;
		file.in = config.inFormat;
		file.out = config.outFormat;
		return file;
	}
}

function convertCode(file, removeReact = false) {
	let source = file.buffer.toString('utf-8');
	if (source.indexOf('export default class') === -1 || source.indexOf('React.createClass') !== -1)	 {
		source = createWrappedRenderFunction(file, source);
	}
	let dependencies = convertDependencies(file);
	return fixDependencyImports(source, dependencies, removeReact);
}

function createWrappedRenderFunction(file, source) {
	let patternJson = loadPatternJson(file.path);
	let dependencies = writeDependencyImports(file).join('\n');
	return renderCodeTemplate(source, dependencies, template, pascalCase(patternJson.name));
}

function loadPatternJson(path) {
	return require(
		join(
			path.substring(0,
				path.lastIndexOf('/')), 'pattern.json'));
}

function writeDependencyImports(file) {
	let dependencies = [];
	for (let dependencyName of Object.keys(file.dependencies)) {
		dependencies.push(`import ${pascalCase(dependencyName)} from '${dependencyName}';`);
	}
	return dependencies;
}

function renderCodeTemplate(source, dependencies, template, className) {
	return template
		.replace('$$dependencies$$', dependencies)
		.replace('$$class-name$$', className)
		.replace('$$render-code$$', matchFirstJsxExpressionAndWrapWithReturn(source));
}

function matchFirstJsxExpressionAndWrapWithReturn(source) {
	return source
		.replace(/(<[a-z0-9]+(?:\s+[a-z0-9]+=["][^"]*?["]|\s+[a-z0-9]+=[{][^}]*?[}]|\s+\{\.\.\.[^}]+\})*\s*\/?>[^]*)/gi,
			'return (\n$1\n);')
}

function convertDependencies(file) {
	let dependencies = {};
	for (let dependencyName of Object.keys(file.dependencies)) {
		let dependencyFile = file.dependencies[dependencyName];
		dependencies[dependencyName] = convertCode(dependencyFile, true);
	}
	return dependencies;
}

function fixDependencyImports(source, dependencies, removeReact) {
	// Replace import statements (but react) with a dumb module loader
	return source.replace(/^\s*import\s+(?:\*\s+as\s+)?(.*?)\s+from\s+['"]([-_a-zA-Z0-9]+)['"].*$/gm, (match, name, module) => {
		if (name === 'React' || module === 'react') {
			if (removeReact) {
				return '';
			}
			return "import * as React from 'react'";
		}
		return `let ${name} = (() => {
			${dependencies[module].replace("import * as React from 'react';", '').replace('export default ', 'return ')}
		})();
		`;
	})
}
<|endoftext|>