<commit_before>var AllEditors = new Array();

function showckeditor (Quel, id) {
	CKEDITOR.config.entities = false;
	CKEDITOR.config.entities_latin = false;
	CKEDITOR.config.htmlEncodeOutput = false;

	AllEditors[id] = CKEDITOR.replace( Quel, {
		language: '<?php echo \Auth::user()->language; ?>',
		height: 175,
		toolbar : [
			{ name: 'Fichiers', items: ['Source']},
			{ name: 'CopieColle', items: ['Cut','Copy','Paste','PasteText','PasteFromWord','RemoveFormat']},
			{ name: 'FaireDefaire', items: ['Undo','Redo','-','Find','Replace','-','SelectAll']},
			{ name: 'Polices', items: ['Bold','Italic','Underline','TextColor']},
			{ name: 'ListeDec', items: ['horizontalrule','table','JustifyLeft','JustifyCenter','JustifyRight','Outdent','Indent','Blockquote']},
			{ name: 'Liens', items: ['Image', 'NumberedList','BulletedList','-','Link','Unlink']}
		]
	} );
}

function AffichonsEditor(id) {
	var CeComment = document.getElementById('comment'+id);
	var SesDiv = CeComment.childNodes;
	var SousDiv = SesDiv[1].childNodes;
	document.getElementById('div_comment_' + id + '_Sdiv').style.display = "block";
	var SSousDiv = 'textarea_' + id + '_SSdiv';
	setTimeout(function() {
		showckeditor (SSousDiv, id);
	} , 167);
}

function CachonsEditor(id) {
	if (document.getElementById('div_comment_' + id + '_Sdiv')) {
		document.getElementById('div_comment_' + id + '_Sdiv').style.display = "none";
		AllEditors[id].setData(document.getElementById('div_comment_' + id + '_issue').innerHTML);
		return AllEditors['textarea_' + id + '_SSdiv'].getData();
	} else {
		return AllEditors[id].getData();
	}
}

function ChangeonsEditor(id, contenu) {
	return AllEditors[id].setData(contenu);
}

function ConservEditor(id) {
	alert("Nous voici en ligne 45");
	var SSdiv = 'textarea_' + id + '_SSdiv';
	AllEditors[SSdiv] = CKEDITOR.instances['textarea_' + id + '_SSdiv'].getData();
	var contenu = AllEditors[id].getData();
	//var contenu = document.getElementById(SSdiv).innerHTML;
	//var posi = contenu.indexOf("Telephone");
	alert("Voici le contenu lu : \ln" + contenu);
}

function SupprimonsEditor(id) {
	AllEditors[id].destroy();
}
<commit_msg>Avis de chantier<commit_after>var AllEditors = new Array();

function showckeditor (Quel, id) {
	CKEDITOR.config.entities = false;
	CKEDITOR.config.entities_latin = false;
	CKEDITOR.config.htmlEncodeOutput = false;

	AllEditors[id] = CKEDITOR.replace( Quel, {
		language: '<?php echo \Auth::user()->language; ?>',
		height: 175,
		toolbar : [
			{ name: 'Fichiers', items: ['Source']},
			{ name: 'CopieColle', items: ['Cut','Copy','Paste','PasteText','PasteFromWord','RemoveFormat']},
			{ name: 'FaireDefaire', items: ['Undo','Redo','-','Find','Replace','-','SelectAll']},
			{ name: 'Polices', items: ['Bold','Italic','Underline','TextColor']},
			{ name: 'ListeDec', items: ['horizontalrule','table','JustifyLeft','JustifyCenter','JustifyRight','Outdent','Indent','Blockquote']},
			{ name: 'Liens', items: ['Image', 'NumberedList','BulletedList','-','Link','Unlink']}
		]
	} );
}

function AffichonsEditor(id) {
	var CeComment = document.getElementById('comment'+id);
	var SesDiv = CeComment.childNodes;
	var SousDiv = SesDiv[1].childNodes;
	document.getElementById('div_comment_' + id + '_Sdiv').style.display = "block";
	var SSousDiv = 'textarea_' + id + '_SSdiv';
	setTimeout(function() {
		showckeditor (SSousDiv, id);
	} , 167);
}

function CachonsEditor(id) {
	if (document.getElementById('div_comment_' + id + '_Sdiv')) {
		document.getElementById('div_comment_' + id + '_Sdiv').style.display = "none";
		AllEditors[id].setData(document.getElementById('div_comment_' + id + '_issue').innerHTML);
		return AllEditors['textarea_' + id + '_SSdiv'].getData();
	} else {
		return AllEditors[id].getData();
	}
}

function ChangeonsEditor(id, contenu) {
	return AllEditors[id].setData(contenu);
}

function ConservEditor(id) {
	var SSdiv = 'textarea_' + id + '_SSdiv';
	AllEditors[SSdiv] = CKEDITOR.instances['textarea_' + id + '_SSdiv'].getData();
	var contenu = AllEditors[id].getData();
	alert("Nous sommes en chantier ici, veuillez patienter");
	//alert("Voici le contenu lu : \ln" + contenu);
}

function SupprimonsEditor(id) {
	AllEditors[id].destroy();
}
<|endoftext|>


<commit_before>import withWidth from '@material-ui/core/withWidth';
import {withStyles} from '@material-ui/core/styles';
import { Component } from 'react';
import PropTypes from 'prop-types';
import Dialog from "@material-ui/core/Dialog";
import DialogTitle from "@material-ui/core/DialogTitle";
import DialogContent from "@material-ui/core/DialogContent";
import DialogActions from "@material-ui/core/DialogActions";
import AppBar from "@material-ui/core/AppBar";
import Tab from "@material-ui/core/Tab";
import Tabs from "@material-ui/core/Tabs";
import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
import LinearProgress from '@material-ui/core/LinearProgress';
import IconButton from '@material-ui/core/IconButton';

import ConfirmDialog from '@iobroker/adapter-react/Dialogs/Confirm';
import Router from '@iobroker/adapter-react/Components/Router';

import MainSettingsDialog from "./MainSettingsDialog";
import RepositoriesDialog from "./RepositoriesDialog";
import SertificatsDialog from "./SertificatsDialog";
import SSLDialog from "./SSLDialog";
import ACLDialog from "./ACLDialog";
import StatisticsDialog from "./StatisticsDialog";

// icons
import CheckIcon from '@material-ui/icons/Check';
import CloseIcon from '@material-ui/icons/Close';

//fills
import lightBlue from '@material-ui/core/colors/lightBlue'

//style
import "../assets/css/style.css";

const styles = theme => ({
    tabPanel: {
        width: '100%',
        height: 'calc(100% - ' + theme.mixins.toolbar.minHeight + 'px)',
        overflow: 'hidden'
    },
    tab: {
        // backgroundColor:"#FFF",
        // color:lightBlue[500]
    },
    dialogTitle : {
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        padding:'0 0 0 20px',
    },
    dialog : {
        width:'100%',
        height:'100%',
        maxWidth:'100%'
    },
    content : {
        padding:'0!important'
    }
});

class SystemSettingsDialog extends Component
{
    constructor(props)
    {
        super(props);
        this.state =  {
            loading: true,
            confirmExit: false,
            systemSettings: null,
            systemRepositories: null,
        };
        this.getSettings(this.state.currentHost);
    }
    getSettings()
    {
        const newState = {loading: false};
         return this.props.socket.getSystemConfig(true)
            .then(systemSettings => {
                //console.log(systemSettings);
                newState.systemSettings = systemSettings && systemSettings.common ? systemSettings.common : {};
                return this.props.socket.getObject('system.repositories');
            })
                .then(systemRepositories => {
                    systemRepositories = JSON.parse(JSON.stringify(systemRepositories));
                    systemRepositories = systemRepositories || {};
                    systemRepositories.native = systemRepositories.native || {};
                    systemRepositories.native.repositories = systemRepositories.native.repositories || {};

                    Object.keys(systemRepositories.native.repositories).forEach(repo => {
                        if (systemRepositories.native.repositories[repo] &&
                            systemRepositories.native.repositories[repo].json) {
                            delete systemRepositories.native.repositories[repo].json;
                        }
                        if (systemRepositories.native.repositories[repo] &&
                            systemRepositories.native.repositories[repo].hash) {
                            delete systemRepositories.native.repositories[repo].hash;
                        }
                    });
                    this.originalRepositories = JSON.stringify(systemRepositories.native.repositories);
                    this.originalSettings = JSON.stringify(newState.systemSettings);
                    //console.log(systemRepositories.native.repositories);
                    newState.systemRepositories = systemRepositories.native.repositories;
                    return this.props.socket.getObject('system.config');
                })

                    .then(systemcConfig => {
                        console.log(systemcConfig);
                        this.originalConfig = JSON.stringify( systemcConfig );
                        newState.systemcConfig = systemcConfig;
                        // return this.props.socket.getObject('system.certificates');
                        return this.props.socket.getRawSocket().emit(
                            'sendToHost',
                            this.props.currentHost,
                            'getDiagData',
                            systemcConfig.common.diag,
                            diagData => {
                                //console.log(diagData);
                                newState.diagData = diagData;
                            });
                    })
                        /**/
                        .then(diagData => {
                            return this.props.socket.getUsers();
                        })
                            .then(users => {
                                //console.log(users);
                                newState.users = users;
                                return this.props.socket.getGroups();
                            })
                                .then(groups => {
                                    //console.log(groups);
                                    newState.groups = groups;
                                    return this.props.socket.getObject('system.certificates');
                                })
                                    .then(systemcCertificates => {
                                        //console.log(systemcCertificates);
                                        this.originalCertificates = JSON.stringify( systemcCertificates );
                                        newState.systemcCertificates = systemcCertificates;
                                        this.setState(newState);
                                    });
    }
    renderConfirmDialog()
    {
        if (this.state.confirmExit)
        {
            return <ConfirmDialog
                text={ this.props.t('Discard unsaved changes? ')}
                onClose={result =>
                    this.setState({ confirmExit: false }, () =>
                        result && this.props.onClose())}
            />;
        }
        else
        {
            return null;
        }
    }

    onSave()
    {
        return this.props.socket.getSystemConfig(true)
            .then(systemSettings => {
                systemSettings = systemSettings || {};
                console.log( systemSettings );
                if (JSON.stringify(systemSettings.common) !== JSON.stringify(this.state.systemSettings))
                {
                    systemSettings.common = this.state.systemSettings;
                    return this.props.socket.setSystemConfig(systemSettings);
                }
                else
                {
                    return Promise.resolve();
                }
            })
                .then(() => this.props.socket.setObject( 'system.config', this.state.systemcConfig ))
                    .then(() => this.props.socket.setObject( 'system.certificates', this.state.systemcCertificates ))
                        .then(() => this.props.socket.getObject('system.repositories'))
                            .then(systemRepositories => {
                                systemRepositories = systemRepositories || {};
                                systemRepositories.native = systemRepositories.native || {};
                                systemRepositories.native.repositories = systemRepositories.native.repositories || {};
                                const newRepo = JSON.parse(JSON.stringify(this.state.systemRepositories));

                                // merge new and existing info
                                Object.keys(newRepo).forEach(repo => {
                                    if (systemRepositories.native.repositories[repo] && systemRepositories.native.repositories[repo].json) {
                                        newRepo[repo].json = systemRepositories.native.repositories[repo].json;
                                    }
                                    if (systemRepositories.native.repositories[repo] && systemRepositories.native.repositories[repo].hash) {
                                        newRepo[repo].hash = systemRepositories.native.repositories[repo].hash;
                                    }
                                });
                                systemRepositories.native.repositories = newRepo;
                                this.getSettings();
                                alert("CHANGE SYSTEM CONFIG NEED");
                                return this.props.socket.setObject('system.repositories', systemRepositories);
                            })
                                .catch(e => window.alert('Cannot save system configuration: ' + e));
    }
    getTabs()
    {
        return [
            {
                id : 0,
                title: 'System settings',
                component: MainSettingsDialog,
                data: "systemSettings",
                data2:{},
                handle: null
            },
            {
                id : 1,
                title: 'Repositories',
                component: RepositoriesDialog,
                data: "systemRepositories",
                data2:{},
                handle: null
            },
            {
                id : 2,
                title: 'Certificates',
                component: SertificatsDialog,
                data: "systemcCertificates",
                data2:{},
                handle: null
            },
            {
                id : 3,
                title: "Let's encrypt SSL",
                component: SSLDialog,
                data: "systemcCertificates",
                data2:{},
                handle: null
            },
            {
                id : 4,
                title: "Default ACL",
                component: ACLDialog,
                data: "systemcConfig",
                data2:{},
                handle: null
            },
            {
                id : 5,
                title: "Statistics",
                component: StatisticsDialog,
                data: "systemcConfig",
                data2: "diagData",
                handle: type => this.onChangeStaticType(type)
            }
        ]
    }
    onChangeStaticType = type =>
    {
        console.log(type);
        this.props.socket.getRawSocket().emit(
            'sendToHost',
            this.props.currentHost,
            'getDiagData',
            type,
            diagData => {
               // console.log(diagData)
                this.setState({
                    diagData,
                    systemcConfig: {
                        ...this.state.systemcConfig,
                        common: {
                            ...this.state.systemcConfig.common,
                            diag: type
                        }
                    }
                });
            });
    }
    getDialogContent() {
       if(this.state.loading)
            return  <LinearProgress/> ;
       const _t =  this. getTabs().filter((e, i) => {
           return e.id == (this.props.currentTab.id ).toString() ||  e.id == parseInt(this.props.currentTab.id)
       }) [0] || this. getTabs()[0];
       const _Component =  _t.component;
       const {groups, users} = this.state;
       console.log( this.state );
       return

           <_Component
                onChange={(id, data) => this.onChangedTab(id, data, _t.data) }
                { ...this.state[_t.data] }
                data2= { this.state[_t.data2] }
                handle={ _t.handle }
                users={users}
                groups={groups}
                themeName={this.props.themeName}
                t={this.props.t}
           />

    }
    onTab = (event, newTab) => {
        Router.doNavigate(null, 'system', newTab)
    }
    onChangedTab (id, data, param )  {
        let state = {...this.state};
        state[ param ][ id ] = data;
        this.setState( state );
        console.log( id, data, param, state );
    }

    restoreState()
    {
        this.originalRepositories   = JSON.stringify( this.state.systemRepositories );
        this.originalSettings       = JSON.stringify( this.state.systemSettings );
        this.originalCertificates   = JSON.stringify( this.state.systemcCertificates );
        this.originalConfig         = JSON.stringify( this.state.systemcConfig );
        this.render();
        alert("Success update settings")
    }

    render() {
        //console.log(this.props)
        const changed = JSON.stringify(this.state.systemSettings)       !== this.originalSettings ||
                        JSON.stringify(this.state.systemRepositories)   !== this.originalRepositories ||
                        JSON.stringify(this.state.systemcConfig)        !== this.originalConfig ||
                        JSON.stringify(this.state.systemcCertificates)  !== this.originalCertificates;
        const tabs = this. getTabs().map((e,i) =>
        {
            return  <Tab
                label={ this.props.t( e.title ) }
                id={ (e.id).toString() }
                aria-controls={ 'simple-tabpanel-' +  e.id }
                key={i}
            />;
        })
        const curTab = parseInt(this.props.currentTab.id, 10) || 0;
        return <Dialog
            className={ this.props.classes.dialog }
            classes={{
                root: this.props.classes.dialog,
                paper: "dialog-setting"
            }}
            open={ true }
            onClose={ () => {} }
            fullWidth={ false }
            fullScreen={ false }
            aria-labelledby="system-settings-dialog-title"
        >
            <DialogContent className={ this.props.classes.content }>
                <AppBar position="static" color="default">

                        <Typography className="dialogName">
                            { this.props.t('Base settings') }
                        </Typography>
                        <Tabs
                            className={ this.props.classes.tab }
                            indicatorColor="primary"
                            value={ curTab }
                            onChange={ this.onTab }
                            variant="scrollable"
                            scrollButtons="auto"
                        >
                            { tabs }
                        </Tabs>
                        <IconButton
                            edge="start"
                            color="inherit"
                            onClick={ () => changed ? this.setState({confirmExit: true}) : this.props.onClose() }
                            aria-label="close"
                        >
                            <CloseIcon />
                        </IconButton>

                </AppBar>
                { this.getDialogContent()  }
                { this.renderConfirmDialog() }
            </DialogContent>
            <DialogActions>
                <Button
                    variant="contained"
                    disabled={ !changed }
                    onClick={ () => this.onSave() }
                    color="primary"
                >
                    <CheckIcon />
                    { this.props.t('Save') }
                </Button>
                <Button
                    variant="contained"
                    onClick={ () => changed ? this.setState({confirmExit: true}) : this.props.onClose() }
                >
                    <CloseIcon />
                    { changed ? this.props.t('Cancel') : this.props.t('Close') }
                </Button>
            </DialogActions>
        </Dialog>
    }
}

SystemSettingsDialog.propTypes = {
    t: PropTypes.func,
    lang: PropTypes.string,
    socket: PropTypes.object,
    themeName: PropTypes.string,
    onClose: PropTypes.func.isRequired,
    currentTab: PropTypes.object,
};

export default withWidth()(withStyles(styles)(SystemSettingsDialog));

function TabPanel(props) {
    const { children, value, index, ...other } = props;

    return (
      <div
        role="tabpanel"
        hidden={value !== index}
        id={`nav-tabpanel-${index}`}
        aria-labelledby={`nav-tab-${index}`}
        {...other}
      >
        {value === index && (
          <Box p={3}>
            <Typography>{children}</Typography>
          </Box>
        )}

    );
  }

  TabPanel.propTypes = {
    children: PropTypes.node,
    index: PropTypes.any.isRequired,
    value: PropTypes.any.isRequired,
  };<commit_msg>main save<commit_after>import withWidth from '@material-ui/core/withWidth';
import {withStyles} from '@material-ui/core/styles';
import { Component } from 'react';
import PropTypes from 'prop-types';
import Dialog from "@material-ui/core/Dialog";
import DialogTitle from "@material-ui/core/DialogTitle";
import DialogContent from "@material-ui/core/DialogContent";
import DialogActions from "@material-ui/core/DialogActions";
import AppBar from "@material-ui/core/AppBar";
import Tab from "@material-ui/core/Tab";
import Tabs from "@material-ui/core/Tabs";
import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
import LinearProgress from '@material-ui/core/LinearProgress';
import IconButton from '@material-ui/core/IconButton';

import ConfirmDialog from '@iobroker/adapter-react/Dialogs/Confirm';
import Router from '@iobroker/adapter-react/Components/Router';

import MainSettingsDialog from "./MainSettingsDialog";
import RepositoriesDialog from "./RepositoriesDialog";
import SertificatsDialog from "./SertificatsDialog";
import SSLDialog from "./SSLDialog";
import ACLDialog from "./ACLDialog";
import StatisticsDialog from "./StatisticsDialog";

// icons
import CheckIcon from '@material-ui/icons/Check';
import CloseIcon from '@material-ui/icons/Close';

//fills
import lightBlue from '@material-ui/core/colors/lightBlue'

//style
import "../assets/css/style.css";

const styles = theme => ({
    tabPanel: {
        width: '100%',
        height: 'calc(100% - ' + theme.mixins.toolbar.minHeight + 'px)',
        overflow: 'hidden'
    },
    tab: {
        // backgroundColor:"#FFF",
        // color:lightBlue[500]
    },
    dialogTitle : {
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        padding:'0 0 0 20px',
    },
    dialog : {
        width:'100%',
        height:'100%',
        maxWidth:'100%'
    },
    content : {
        padding:'0!important'
    }
});

class SystemSettingsDialog extends Component
{
    constructor(props)
    {
        super(props);
        this.state =  {
            loading: true,
            confirmExit: false,
            systemSettings: null,
            systemRepositories: null,
        };
        this.getSettings(this.state.currentHost);
    }
    getSettings()
    {
        const newState = {loading: false};
         return this.props.socket.getSystemConfig(true)
            .then(systemSettings => {
                //console.log(systemSettings);
                newState.systemSettings = systemSettings && systemSettings.common ? systemSettings.common : {};
                return this.props.socket.getObject('system.repositories');
            })
                .then(systemRepositories => {
                    systemRepositories = JSON.parse(JSON.stringify(systemRepositories));
                    systemRepositories = systemRepositories || {};
                    systemRepositories.native = systemRepositories.native || {};
                    systemRepositories.native.repositories = systemRepositories.native.repositories || {};

                    Object.keys(systemRepositories.native.repositories).forEach(repo => {
                        if (systemRepositories.native.repositories[repo] &&
                            systemRepositories.native.repositories[repo].json) {
                            delete systemRepositories.native.repositories[repo].json;
                        }
                        if (systemRepositories.native.repositories[repo] &&
                            systemRepositories.native.repositories[repo].hash) {
                            delete systemRepositories.native.repositories[repo].hash;
                        }
                    });
                    this.originalRepositories = JSON.stringify(systemRepositories.native.repositories);
                    this.originalSettings = JSON.stringify(newState.systemSettings);
                    //console.log(systemRepositories.native.repositories);
                    newState.systemRepositories = systemRepositories.native.repositories;
                    return this.props.socket.getObject('system.config');
                })

                    .then(systemcConfig => {
                        console.log(systemcConfig);
                        this.originalConfig = JSON.stringify( systemcConfig );
                        newState.systemcConfig = systemcConfig;
                        // return this.props.socket.getObject('system.certificates');
                        return this.props.socket.getRawSocket().emit(
                            'sendToHost',
                            this.props.currentHost,
                            'getDiagData',
                            systemcConfig.common.diag,
                            diagData => {
                                //console.log(diagData);
                                newState.diagData = diagData;
                            });
                    })
                        /**/
                        .then(diagData => {
                            return this.props.socket.getUsers();
                        })
                            .then(users => {
                                //console.log(users);
                                newState.users = users;
                                return this.props.socket.getGroups();
                            })
                                .then(groups => {
                                    //console.log(groups);
                                    newState.groups = groups;
                                    return this.props.socket.getObject('system.certificates');
                                })
                                    .then(systemcCertificates => {
                                        //console.log(systemcCertificates);
                                        this.originalCertificates = JSON.stringify( systemcCertificates );
                                        newState.systemcCertificates = systemcCertificates;
                                        this.setState(newState);
                                    });
    }
    renderConfirmDialog()
    {
        if (this.state.confirmExit)
        {
            return <ConfirmDialog
                text={ this.props.t('Discard unsaved changes? ')}
                onClose={result =>
                    this.setState({ confirmExit: false }, () =>
                        result && this.props.onClose())}
            />;
        }
        else
        {
            return null;
        }
    }

    onSave()
    {
        console.log(this.state);
        return this.props.socket.getSystemConfig(true)
            .then(systemSettings => {
                systemSettings = systemSettings || {};
                console.log( systemSettings );
                if (JSON.stringify(systemSettings.common) !== JSON.stringify(this.state.systemSettings))
                {
                    systemSettings.common = this.state.systemSettings;
                    console.log(systemSettings.common);
                    return this.props.socket.setSystemConfig(systemSettings);
                }
                else
                {
                    return Promise.resolve();
                }
            })
                // .then(() => this.props.socket.setObject( 'system.config', this.state.systemcConfig ))
                    .then(() => this.props.socket.setObject( 'system.certificates', this.state.systemcCertificates ))
                        .then(() => this.props.socket.getObject('system.repositories'))
                            .then(systemRepositories => {
                                systemRepositories = systemRepositories || {};
                                systemRepositories.native = systemRepositories.native || {};
                                systemRepositories.native.repositories = systemRepositories.native.repositories || {};
                                const newRepo = JSON.parse(JSON.stringify(this.state.systemRepositories));

                                // merge new and existing info
                                Object.keys(newRepo).forEach(repo => {
                                    if (systemRepositories.native.repositories[repo] && systemRepositories.native.repositories[repo].json) {
                                        newRepo[repo].json = systemRepositories.native.repositories[repo].json;
                                    }
                                    if (systemRepositories.native.repositories[repo] && systemRepositories.native.repositories[repo].hash) {
                                        newRepo[repo].hash = systemRepositories.native.repositories[repo].hash;
                                    }
                                });
                                systemRepositories.native.repositories = newRepo;
                                this.getSettings();
                                alert("CHANGE SYSTEM CONFIG NEED");
                                return this.props.socket.setObject('system.repositories', systemRepositories);
                            })
                                .catch(e => window.alert('Cannot save system configuration: ' + e));
    }
    getTabs()
    {
        return [
            {
                id : 0,
                title: 'System settings',
                component: MainSettingsDialog,
                data: "systemSettings",
                data2:{},
                handle: null
            },
            {
                id : 1,
                title: 'Repositories',
                component: RepositoriesDialog,
                data: "systemRepositories",
                data2:{},
                handle: null
            },
            {
                id : 2,
                title: 'Certificates',
                component: SertificatsDialog,
                data: "systemcCertificates",
                data2:{},
                handle: null
            },
            {
                id : 3,
                title: "Let's encrypt SSL",
                component: SSLDialog,
                data: "systemcCertificates",
                data2:{},
                handle: null
            },
            {
                id : 4,
                title: "Default ACL",
                component: ACLDialog,
                data: "systemcConfig",
                data2:{},
                handle: null
            },
            {
                id : 5,
                title: "Statistics",
                component: StatisticsDialog,
                data: "systemcConfig",
                data2: "diagData",
                handle: type => this.onChangeStaticType(type)
            }
        ]
    }
    onChangeStaticType = type =>
    {
        console.log(type);
        this.props.socket.getRawSocket().emit(
            'sendToHost',
            this.props.currentHost,
            'getDiagData',
            type,
            diagData => {
               // console.log(diagData)
                this.setState({
                    diagData,
                    systemcConfig: {
                        ...this.state.systemcConfig,
                        common: {
                            ...this.state.systemcConfig.common,
                            diag: type
                        }
                    }
                });
            });
    }
    getDialogContent() {
       if(this.state.loading)
            return  <LinearProgress/> ;
       const _t =  this. getTabs().filter((e, i) => {
           return e.id == (this.props.currentTab.id ).toString() ||  e.id == parseInt(this.props.currentTab.id)
       }) [0] || this. getTabs()[0];
       const _Component =  _t.component;
       const {groups, users} = this.state;
       console.log( this.state );
       return

           <_Component
                onChange={(id, data) => this.onChangedTab(id, data, _t.data) }
                { ...this.state[_t.data] }
                data2= { this.state[_t.data2] }
                handle={ _t.handle }
                users={users}
                groups={groups}
                themeName={this.props.themeName}
                t={this.props.t}
           />

    }
    onTab = (event, newTab) => {
        Router.doNavigate(null, 'system', newTab)
    }
    onChangedTab (id, data, param )  {
        console.log(id, data, param);
        let state = {...this.state};
        state[ param ][ id ] = data;
        this.setState( state );
        console.log( id, data, param, state );
    }

    restoreState()
    {
        this.originalRepositories   = JSON.stringify( this.state.systemRepositories );
        this.originalSettings       = JSON.stringify( this.state.systemSettings );
        this.originalCertificates   = JSON.stringify( this.state.systemcCertificates );
        this.originalConfig         = JSON.stringify( this.state.systemcConfig );
        this.render();
        alert("Success update settings")
    }

    render() {
        //console.log(this.props)
        const changed = JSON.stringify(this.state.systemSettings)       !== this.originalSettings ||
                        JSON.stringify(this.state.systemRepositories)   !== this.originalRepositories ||
                        JSON.stringify(this.state.systemcConfig)        !== this.originalConfig ||
                        JSON.stringify(this.state.systemcCertificates)  !== this.originalCertificates;
        const tabs = this. getTabs().map((e,i) =>
        {
            return  <Tab
                label={ this.props.t( e.title ) }
                id={ (e.id).toString() }
                aria-controls={ 'simple-tabpanel-' +  e.id }
                key={i}
            />;
        })
        const curTab = parseInt(this.props.currentTab.id, 10) || 0;
        return <Dialog
            className={ this.props.classes.dialog }
            classes={{
                root: this.props.classes.dialog,
                paper: "dialog-setting"
            }}
            open={ true }
            onClose={ () => {} }
            fullWidth={ false }
            fullScreen={ false }
            aria-labelledby="system-settings-dialog-title"
        >
            <DialogContent className={ this.props.classes.content }>
                <AppBar position="static" color="default">

                        <Typography className="dialogName">
                            { this.props.t('Base settings') }
                        </Typography>
                        <Tabs
                            className={ this.props.classes.tab }
                            indicatorColor="primary"
                            value={ curTab }
                            onChange={ this.onTab }
                            variant="scrollable"
                            scrollButtons="auto"
                        >
                            { tabs }
                        </Tabs>
                        <IconButton
                            edge="start"
                            color="inherit"
                            onClick={ () => changed ? this.setState({confirmExit: true}) : this.props.onClose() }
                            aria-label="close"
                        >
                            <CloseIcon />
                        </IconButton>

                </AppBar>
                { this.getDialogContent()  }
                { this.renderConfirmDialog() }
            </DialogContent>
            <DialogActions>
                <Button
                    variant="contained"
                    disabled={ !changed }
                    onClick={ () => this.onSave() }
                    color="primary"
                >
                    <CheckIcon />
                    { this.props.t('Save') }
                </Button>
                <Button
                    variant="contained"
                    onClick={ () => changed ? this.setState({confirmExit: true}) : this.props.onClose() }
                >
                    <CloseIcon />
                    { changed ? this.props.t('Cancel') : this.props.t('Close') }
                </Button>
            </DialogActions>
        </Dialog>
    }
}

SystemSettingsDialog.propTypes = {
    t: PropTypes.func,
    lang: PropTypes.string,
    socket: PropTypes.object,
    themeName: PropTypes.string,
    onClose: PropTypes.func.isRequired,
    currentTab: PropTypes.object,
};

export default withWidth()(withStyles(styles)(SystemSettingsDialog));

function TabPanel(props) {
    const { children, value, index, ...other } = props;

    return (
      <div
        role="tabpanel"
        hidden={value !== index}
        id={`nav-tabpanel-${index}`}
        aria-labelledby={`nav-tab-${index}`}
        {...other}
      >
        {value === index && (
          <Box p={3}>
            <Typography>{children}</Typography>
          </Box>
        )}

    );
  }

  TabPanel.propTypes = {
    children: PropTypes.node,
    index: PropTypes.any.isRequired,
    value: PropTypes.any.isRequired,
  };<|endoftext|>


<commit_before>import React, { createElement } from 'preact/compat';
import { setupScratch, teardown } from '../../../test/_util/helpers';

describe('compat createElement()', () => {
	/** @type {HTMLDivElement} */
	let scratch;

	beforeEach(() => {
		scratch = setupScratch();
	});

	afterEach(() => {
		teardown(scratch);
	});

	it('should normalize vnodes', () => {
		let vnode = (

				t

		);
		let $$typeof = 0xeac7;
		try {
			// eslint-disable-next-line
			if (
				Function.prototype.toString
					.call(eval('Symbol.for'))
					.match(/\[native code\]/)
			) {
				// concatenate these string literals to prevent the test
				// harness and/or Babel from modifying the symbol value.
				// eslint-disable-next-line
				$$typeof = eval('Sym' + 'bol.for("react.element")');
			}
		} catch (e) {}
		expect(vnode).to.have.property('$$typeof', $$typeof);
		expect(vnode).to.have.property('type', 'div');
		expect(vnode)
			.to.have.property('props')
			.that.is.an('object');
		expect(vnode.props).to.have.property('children');
		expect(vnode.props.children).to.have.property('$$typeof', $$typeof);
		expect(vnode.props.children).to.have.property('type', 'a');
		expect(vnode.props.children)
			.to.have.property('props')
			.that.is.an('object');
		expect(vnode.props.children.props).to.eql({ children: 't' });
	});
});
<commit_msg>Fix grammar<commit_after>import React, { createElement } from 'preact/compat';
import { setupScratch, teardown } from '../../../test/_util/helpers';

describe('compat createElement()', () => {
	/** @type {HTMLDivElement} */
	let scratch;

	beforeEach(() => {
		scratch = setupScratch();
	});

	afterEach(() => {
		teardown(scratch);
	});

	it('should normalize vnodes', () => {
		let vnode = (

				t

		);
		let $$typeof = 0xeac7;
		try {
			// eslint-disable-next-line
			if (
				Function.prototype.toString
					.call(eval('Symbol.for'))
					.match(/\[native code\]/)
			) {
				// Concatenate these string literals to prevent the test
				// harness and/or Babel from modifying the symbol value.
				// eslint-disable-next-line
				$$typeof = eval('Sym' + 'bol.for("react.element")');
			}
		} catch (e) {}
		expect(vnode).to.have.property('$$typeof', $$typeof);
		expect(vnode).to.have.property('type', 'div');
		expect(vnode)
			.to.have.property('props')
			.that.is.an('object');
		expect(vnode.props).to.have.property('children');
		expect(vnode.props.children).to.have.property('$$typeof', $$typeof);
		expect(vnode.props.children).to.have.property('type', 'a');
		expect(vnode.props.children)
			.to.have.property('props')
			.that.is.an('object');
		expect(vnode.props.children.props).to.eql({ children: 't' });
	});
});
<|endoftext|>


<commit_before>// Load in our dependencies
var $ = window.$ = window.jQuery = require('jquery');
var D = require('./domo');
var Overlay = require('./overlay');

// Deifne our constructor
function ImageSet(_containerEl, imageSetInfo) {
  // Create local variables for our image set
  var imgSetId = this.id = imageSetInfo.id;
  var imgSetHumanName = imageSetInfo.id;

  // Save our state
  this.state = {
    imagesEqual: imageSetInfo.imagesEqual
  };

  // Generate our image set element
  var imgSetEl = D.UL({'data-image-set': imgSetId}, [
    D.LI([
      // Row title
      this.saveEl('titleEl', D.A({
        class: 'image-set__title',
        href: 'javascript:void 0;', 'data-toggle': 'collapse',
        'data-target': '[data-image-set="' + imgSetId + '"] .image-set__collapse',
        'data-images-equal': imageSetInfo.imagesEqual,
        'aria-controls': imgSetId
      }, imgSetHumanName)),

      // Collapsable container for row
      // DEV: We use `data-id` as `id` has restrictions on characters
      D.DIV({
        // Make our first image set visible
        // DEV: If class names get too complex, use `classnames` library
        class: imageSetInfo.imagesEqual ? 'image-set__collapse collapse well' : 'image-set__collapse collapse in well'
      }, [
        // Action buttons
        D.DIV([
          D.BUTTON({
            class: 'btn btn-default',
            'data-action': 'accept-changes'
          }, '✓ Accept changes'),
          ' ',
          D.BUTTON({
            class: 'btn btn-default',
            'data-action': 'find-similar-images'
            // TODO: Make our button disabled and only enable when an overlay is drawn
            // TODO: When changes are accepted, reset all affected overlays and buttons
            // disabled: 'disabled'
          }, 'Find similar images with selection')
        ]),

        // Image set
        D.TABLE({class: 'table'}, [
          D.THEAD([
            D.TR([
              D.TH('Current:'),
              D.TH('Diff:'),
              D.TH('Ref:')
            ])
          ]),
          D.TBODY([
            D.TR([
              // DEV: We use `width: 33%` to guarantee no widths change when images are loading
              D.TD({style: 'width: 33%'}, [
                this.saveEl('currentImg', D.IMG({
                  'data-compare-type': 'current',
                  src: imageSetInfo.currentImgUrl,
                  style: 'max-width: 100%'
                }))
              ]),
              D.TD({style: 'width: 33%'}, [
                this.saveEl('diffImg', D.IMG({
                  'data-compare-type': 'diff',
                  src: imageSetInfo.diffImgUrl,
                  style: 'max-width: 100%'
                }))
              ]),
              D.TD({style: 'width: 33%'}, [
                this.saveEl('refImg', D.IMG({
                  'data-compare-type': 'ref',
                  src: imageSetInfo.refImgUrl,
                  style: 'max-width: 100%'
                }))
              ])
            ])
          ])
        ])
      ])
    ])
  ]);

  // Bind an overlay to diff image
  // TODO: Explore binding overlay to each of images (that jumps between them)
  // DEV: We use imgSetEl's collapse as a container so it hides on collapse
  var imgOverlay = new Overlay(imgSetEl.querySelector('img[data-compare-type=diff]'), {
    containerEl: imgSetEl.querySelector('.image-set__collapse')
  });

  // Save imgOverlay directly to imgSetEl
  imgSetEl.imgOverlay = imgOverlay;

  // Append our element to the container element
  _containerEl.appendChild(imgSetEl);
}

// Define class level helpers
ImageSet.cachebustImg = function (imgEl) {
  var originalSrc = imgEl.getAttribute('src');
  var newSrc = originalSrc.match(/\?1$/) ? originalSrc + '1' : originalSrc + '?1';
  imgEl.setAttribute('src', newSrc);
};

// Define prototype methods
ImageSet.prototype = {
  acceptChanges: function (acceptedImgBase64) {
    // Fade out diff and reference images to "loading" state
    this.diffImg.classList.add('loading');
    this.refImg.classList.add('loading');

    // Eagerly update our status
    // DEV: This won't be the scenario for update reference image (i.e. we are progressively updating images)
    var oldStatus = this.state.imagesEqual;
    this.titleEl.setAttribute('data-images-equal', 'true');

    // Make an AJAX call to accept our image
    // http://api.jquery.com/jQuery.ajax/#jqXHR
    var jqXHR = $.post('/update-image-set/' + encodeURIComponent(this.id), {
      ref: acceptedImgBase64
    });

    // If there is an error
    var that = this;
    jqXHR.fail(function handleFail (jqXHR, textStatus, errorThrown) {
      // TODO: Expose error to user so they can retry
      console.error('Error encountered "' + errorThrown + '" when updating image "' + that.id + '"');

      // Reset status to previous state
      // TODO: Test resetting to previous state on failure
      that.titleEl.setAttribute('data-images-equal', oldStatus);
    });

    // When we complete updating
    jqXHR.done(function handleDone (data, textStatus, jqXHR) {
      // Save new state
      // data = {imagesEqual: true}
      that.state.imagesEqual = data.imagesEqual;
    });

    // When loading completes, remove loading state and update image references
    jqXHR.always(function handleAlways (dataOrJqXHR, textStatus, jqXHROrErrorThrown) {
      that.diffImg.classList.remove('loading');
      that.refImg.classList.remove('loading');
      ImageSet.cachebustImg(that.diffImg);
      ImageSet.cachebustImg(that.refImg);
    });
  },
  saveEl: function (key, el) {
    this[key] = el;
    return el;
  }
};

// Export our constructor
module.exports = ImageSet;
<commit_msg>Updated accept changes method to support updates as well<commit_after>// Load in our dependencies
var $ = window.$ = window.jQuery = require('jquery');
var D = require('./domo');
var Overlay = require('./overlay');

// Deifne our constructor
function ImageSet(_containerEl, imageSetInfo) {
  // Create local variables for our image set
  var imgSetId = this.id = imageSetInfo.id;
  var imgSetHumanName = imageSetInfo.id;

  // Save our state
  this.state = {
    imagesEqual: imageSetInfo.imagesEqual
  };

  // Generate our image set element
  var imgSetEl = D.UL({'data-image-set': imgSetId}, [
    D.LI([
      // Row title
      this.saveEl('titleEl', D.A({
        class: 'image-set__title',
        href: 'javascript:void 0;', 'data-toggle': 'collapse',
        'data-target': '[data-image-set="' + imgSetId + '"] .image-set__collapse',
        'data-images-equal': imageSetInfo.imagesEqual,
        'aria-controls': imgSetId
      }, imgSetHumanName)),

      // Collapsable container for row
      // DEV: We use `data-id` as `id` has restrictions on characters
      D.DIV({
        // Make our first image set visible
        // DEV: If class names get too complex, use `classnames` library
        class: imageSetInfo.imagesEqual ? 'image-set__collapse collapse well' : 'image-set__collapse collapse in well'
      }, [
        // Action buttons
        D.DIV([
          D.BUTTON({
            class: 'btn btn-default',
            'data-action': 'accept-changes'
          }, '✓ Accept changes'),
          ' ',
          D.BUTTON({
            class: 'btn btn-default',
            'data-action': 'find-similar-images'
            // TODO: Make our button disabled and only enable when an overlay is drawn
            // TODO: When changes are accepted, reset all affected overlays and buttons
            // disabled: 'disabled'
          }, 'Find similar images with selection')
        ]),

        // Image set
        D.TABLE({class: 'table'}, [
          D.THEAD([
            D.TR([
              D.TH('Current:'),
              D.TH('Diff:'),
              D.TH('Ref:')
            ])
          ]),
          D.TBODY([
            D.TR([
              // DEV: We use `width: 33%` to guarantee no widths change when images are loading
              D.TD({style: 'width: 33%'}, [
                this.saveEl('currentImg', D.IMG({
                  'data-compare-type': 'current',
                  src: imageSetInfo.currentImgUrl,
                  style: 'max-width: 100%'
                }))
              ]),
              D.TD({style: 'width: 33%'}, [
                this.saveEl('diffImg', D.IMG({
                  'data-compare-type': 'diff',
                  src: imageSetInfo.diffImgUrl,
                  style: 'max-width: 100%'
                }))
              ]),
              D.TD({style: 'width: 33%'}, [
                this.saveEl('refImg', D.IMG({
                  'data-compare-type': 'ref',
                  src: imageSetInfo.refImgUrl,
                  style: 'max-width: 100%'
                }))
              ])
            ])
          ])
        ])
      ])
    ])
  ]);

  // Bind an overlay to diff image
  // TODO: Explore binding overlay to each of images (that jumps between them)
  // DEV: We use imgSetEl's collapse as a container so it hides on collapse
  var imgOverlay = new Overlay(imgSetEl.querySelector('img[data-compare-type=diff]'), {
    containerEl: imgSetEl.querySelector('.image-set__collapse')
  });

  // Save imgOverlay directly to imgSetEl
  imgSetEl.imgOverlay = imgOverlay;

  // Append our element to the container element
  _containerEl.appendChild(imgSetEl);
}

// Define class level helpers
ImageSet.cachebustImg = function (imgEl) {
  var originalSrc = imgEl.getAttribute('src');
  var newSrc = originalSrc.match(/\?1$/) ? originalSrc + '1' : originalSrc + '?1';
  imgEl.setAttribute('src', newSrc);
};

// Define prototype methods
ImageSet.prototype = {
  acceptChanges: function (imgBase64) {
    this._updateReferenceImage(imgBase64, 'true');
  },
  _updateReferenceImage: function (imgBase64, eagerStatus) {
    // Fade out diff and reference images to "loading" state
    this.diffImg.classList.add('loading');
    this.refImg.classList.add('loading');

    // If we have an eager status, use it
    // DEV: For an acceptance, we will eagerly update to 'imagesEqual: true'
    eagerStatus = eagerStatus || 'loading';

    // Update our status while updating
    var oldStatus = this.state.imagesEqual;
    this.titleEl.setAttribute('data-images-equal', eagerStatus);

    // Make an AJAX call to accept our image
    // http://api.jquery.com/jQuery.ajax/#jqXHR
    var jqXHR = $.post('/update-image-set/' + encodeURIComponent(this.id), {
      ref: imgBase64
    });

    // If there is an error
    var that = this;
    jqXHR.fail(function handleFail (jqXHR, textStatus, errorThrown) {
      // TODO: Expose error to user so they can retry
      console.error('Error encountered "' + errorThrown + '" when updating image "' + that.id + '"');

      // Reset status to previous state
      that.titleEl.setAttribute('data-images-equal', oldStatus);
    });

    // When we complete updating
    jqXHR.done(function handleDone (data, textStatus, jqXHR) {
      // Save new state and update status
      // data = {imagesEqual: true}
      that.state.imagesEqual = data.imagesEqual;
      that.titleEl.setAttribute('data-images-equal', data.imagesEqual);
    });

    // When loading completes, remove loading state and update image references
    jqXHR.always(function handleAlways (dataOrJqXHR, textStatus, jqXHROrErrorThrown) {
      that.diffImg.classList.remove('loading');
      that.refImg.classList.remove('loading');
      ImageSet.cachebustImg(that.diffImg);
      ImageSet.cachebustImg(that.refImg);
    });
  },
  updateReferenceImage: function (imgBase64) {
    this._updateReferenceImage(imgBase64);
  },
  saveEl: function (key, el) {
    this[key] = el;
    return el;
  }
};

// Export our constructor
module.exports = ImageSet;
<|endoftext|>


<commit_before>var doc = require('doc-js'),
    EventEmitter = require('events').EventEmitter,
    interact = require('interact-js'),
    crel = require('crel'),
    venfix = require('venfix');

function Flap(element){
    this.render(element);
    this.init();
}
Flap.prototype = Object.create(EventEmitter.prototype);

Flap.prototype.constructor = Flap;
Flap.prototype.distance = 0;
Flap.prototype.state = 'closed';
Flap.prototype.width = 280;
Flap.prototype.side = 'left';
Flap.prototype.gutter = 20;

Flap.prototype.render = function(element){
    this.element = element || crel('div',
        crel('div')
    );

    this.content = this.element.childNodes[0];
    this.element.flap = this;
};
Flap.prototype.bind = function(){
    var flap = this,
        delegateTarget = doc(this.delegateTarget)[0] || document;

    // Allow starting the drag on a delegate target
    interact.on('start', delegateTarget, flap._start.bind(flap));

    // Still use document for the other events for robustness.
    interact.on('drag', document, flap._drag.bind(flap));
    interact.on('end', document, flap._end.bind(flap));
    interact.on('cancel', document, flap._end.bind(flap));

    doc(this.element).on('click', flap._activate.bind(flap));
};
Flap.prototype.init = function(){
    var flap = this;
    doc.ready(function(){
        flap.bind();
        if(this.enabled !== false){
            flap.enable();
        }else{
            flap.disable();
        }
        flap.emit('ready');
    });
};
Flap.prototype.enable = function(){
    this.enabled = true;

    this.element.style.position = 'fixed';
    this.element.style.top = '0px';
    this.element.style.bottom = '0px';
    this.close();

    this.content.style[venfix('boxSizing')] = 'border-box';
    this.content.style.width = this.width + 'px';
    this.content.style.position = 'absolute';
    this.content.style.top = '0px';
    this.content.style.bottom = '0px';
    this.content.style.width = this.width + 'px';
    this.content.style['overflow-x'] = 'hidden';
    this.content.style['overflow-y'] = 'auto';

    if(this.side === 'left'){
        this.element.style.left = '0px';
        this.content.style.left = '0px';
    }else if(this.side === 'right'){
        this.element.style.right = '0px';
        this.content.style.left = '100%';
    }
    this.update();
};
Flap.prototype.disable = function(){
    this.enabled = false;

    this.element.style.position = null;
    this.element.style.top = null;
    this.element.style.bottom = null;
    this.element.style.width = null;
    this.element.style[venfix('pointerEvents')] = null;

    this.content.style[venfix('boxSizing')] = null;
    this.content.style[venfix('transform')] = null;
    this.content.style.width = null;
    this.content.style.position = null;
    this.content.style.top = null;
    this.content.style.bottom = null;
    this.content.style.width = null;
    this.content.style['overflow-x'] = null;
    this.content.style['overflow-y'] = null;

    this.element.style.left = null;
    this.content.style.left = null;
    this.element.style.right = null;
    this.content.style.left = null;
    this.update();
};
Flap.prototype._isValidInteraction = function(interaction){
    if(this.constructor.openFlap){
        return this.constructor.openFlap === this;
    }
    if(this.distance){
        return true;
    }
    if(this.side === 'left'){
        return interaction.pageX < this.distance + this.gutter;
    }else if(this.side === 'right'){
        return interaction.pageX > window.innerWidth - this.gutter;
    }
};
Flap.prototype._start = function(interaction){
    var flap = this;

    if(!this.enabled){
        return;
    }

    if(this._isValidInteraction(interaction)){
        this._setOpen();
    }
};
Flap.prototype._drag = function(interaction){
    var flap = this;

    if(this.constructor.openFlap === this){
        var angle = interaction.getCurrentAngle(true);
        if(angle && !this.beingDragged && ((angle > 45 && angle < 135) || (angle < -45 && angle > -135))){
            return;
        }

        interaction.preventDefault();

        flap.beingDragged = true;
        flap.startDistance = flap.startDistance || flap.distance;
        if(flap.side === 'left'){
            flap.distance = flap.startDistance + interaction.pageX - interaction.lastStart.pageX;
        }else{
            flap.distance = flap.startDistance - interaction.pageX + interaction.lastStart.pageX;
        }
        flap.distance = Math.max(Math.min(flap.distance, flap.width), 0);
        flap.update();
        flap.speed = flap.distance - flap.oldDistance;
        flap.oldDistance = flap.distance;
    }
};
Flap.prototype._end = function(interaction){
    if(this.constructor.openFlap !== this || !this.beingDragged){
        return;
    }

    this.startDistance = null;
    this.beingDragged = false;

    var direction = 'close';

    if(Math.abs(this.speed) >= 3){
        direction = this.speed < 0 ? 'close' : 'open';
    }else if(this.distance < this.width / 2){
        direction = 'close';
    }else{
        direction = 'open';
    }

    this.settle(direction);
};
Flap.prototype._activate = function(event){
    if(!this.enabled){
        return;
    }
    if(
        !doc(event.target).closest(this.content) &&
        this.constructor.openFlap === this
    ){
        event.preventDefault();
        this.beingDragged = false;
        this.settle('close');
    }
};
Flap.prototype._setOpen = function(){
    if(this.constructor.openFlap !== this){
        var flap = this;
        this.constructor.openFlap = this;
        this.element.style['width'] = '100%';
        this.state = 'open';
        this.emit('open');

        // This prevents the flap from screwing up
        // events on elements that may be under the swipe zone
        this._pointerEventTimeout = setTimeout(function(){
            flap.element.style[venfix('pointerEvents')] = 'all';
        },500);
    }
};
Flap.prototype._setClosed = function(){
    this.constructor.openFlap = null;
    clearTimeout(this._pointerEventTimeout);
    this.element.style[venfix('pointerEvents')] = 'none';
    this.element.style['width'] = this.gutter + 'px';
    this.state = 'closed';
    this.emit('close');
};
Flap.prototype.update = function(interaction){
    var flap = this;

    if(this.distance > 0){
        this._setOpen();
    }

    if(this.side === 'left'){
        this.displayPosition = flap.distance - flap.width;
    }else if(this.side === 'right'){
        this.displayPosition = -flap.distance;
    }

    if(flap.distance != flap.lastDistance){
        requestAnimationFrame(function(){
            flap.updateStyle(flap.displayPosition);
            flap.emit('move');
            flap.lastDistance = flap.distance;
        });
    }
};
Flap.prototype.updateStyle = function(displayPosition){
    if(this.enabled){
        this.content.style[venfix('transform')] = 'translate3d(' + (displayPosition) + 'px,0,0)';
    }
};
Flap.prototype.settle = function(direction){
    var flap = this;

    cancelAnimationFrame(this.settleFrame);

    if(this.beingDragged){
        return;
    }
    if(this.distance < 0){
        this.distance = 0;
        this._setClosed();
        this.update();
        this.emit('settle');
        return;
    }else if(this.distance > this.width){
        this.distance = this.width;
        this.update();
        this.emit('settle');
        return;
    }

    this.settleFrame = requestAnimationFrame(function(){
        var step = flap.tween(direction);
        flap.distance += direction === 'close' ? -step : step;
        flap.update();
        flap.settle(direction);
    });
};
Flap.prototype.tween = function(direction){
    return (this.width - this.distance) / 4 + 2;
};
Flap.prototype.percentOpen = function(){
    return parseInt(100 / this.width * this.distance);
};
Flap.prototype.open = function(){
    if(!this.enabled){
        return;
    }
    this.settle('open');
};
Flap.prototype.close = function(){
    if(!this.enabled){
        return;
    }
    this.settle('close');
};
module.exports = Flap;<commit_msg>flaps will now be invisible untill they are ready<commit_after>var doc = require('doc-js'),
    EventEmitter = require('events').EventEmitter,
    interact = require('interact-js'),
    crel = require('crel'),
    venfix = require('venfix');

function Flap(element){
    this.render(element);
    this.init();
}
Flap.prototype = Object.create(EventEmitter.prototype);

Flap.prototype.constructor = Flap;
Flap.prototype.distance = 0;
Flap.prototype.state = 'closed';
Flap.prototype.width = 280;
Flap.prototype.side = 'left';
Flap.prototype.gutter = 20;

Flap.prototype.render = function(element){
    this.element = element || crel('div',
        crel('div')
    );
    this.element.style.opacity = '0';

    this.content = this.element.childNodes[0];
    this.element.flap = this;
};
Flap.prototype.bind = function(){
    var flap = this,
        delegateTarget = doc(this.delegateTarget)[0] || document;

    // Allow starting the drag on a delegate target
    interact.on('start', delegateTarget, flap._start.bind(flap));

    // Still use document for the other events for robustness.
    interact.on('drag', document, flap._drag.bind(flap));
    interact.on('end', document, flap._end.bind(flap));
    interact.on('cancel', document, flap._end.bind(flap));

    doc(this.element).on('click', flap._activate.bind(flap));
};
Flap.prototype.init = function(){
    var flap = this;
    doc.ready(function(){
        flap.bind();
        if(this.enabled !== false){
            flap.enable();
        }else{
            flap.disable();
        }
        flap.emit('ready');
        flap.element.style.opacity = '1';
    });
};
Flap.prototype.enable = function(){
    this.enabled = true;

    this.element.style.position = 'fixed';
    this.element.style.top = '0px';
    this.element.style.bottom = '0px';
    this.close();

    this.content.style[venfix('boxSizing')] = 'border-box';
    this.content.style.width = this.width + 'px';
    this.content.style.position = 'absolute';
    this.content.style.top = '0px';
    this.content.style.bottom = '0px';
    this.content.style.width = this.width + 'px';
    this.content.style['overflow-x'] = 'hidden';
    this.content.style['overflow-y'] = 'auto';

    if(this.side === 'left'){
        this.element.style.left = '0px';
        this.content.style.left = '0px';
    }else if(this.side === 'right'){
        this.element.style.right = '0px';
        this.content.style.left = '100%';
    }
    this.update();
};
Flap.prototype.disable = function(){
    this.enabled = false;

    this.element.style.position = null;
    this.element.style.top = null;
    this.element.style.bottom = null;
    this.element.style.width = null;
    this.element.style[venfix('pointerEvents')] = null;

    this.content.style[venfix('boxSizing')] = null;
    this.content.style[venfix('transform')] = null;
    this.content.style.width = null;
    this.content.style.position = null;
    this.content.style.top = null;
    this.content.style.bottom = null;
    this.content.style.width = null;
    this.content.style['overflow-x'] = null;
    this.content.style['overflow-y'] = null;

    this.element.style.left = null;
    this.content.style.left = null;
    this.element.style.right = null;
    this.content.style.left = null;
    this.update();
};
Flap.prototype._isValidInteraction = function(interaction){
    if(this.constructor.openFlap){
        return this.constructor.openFlap === this;
    }
    if(this.distance){
        return true;
    }
    if(this.side === 'left'){
        return interaction.pageX < this.distance + this.gutter;
    }else if(this.side === 'right'){
        return interaction.pageX > window.innerWidth - this.gutter;
    }
};
Flap.prototype._start = function(interaction){
    var flap = this;

    if(!this.enabled){
        return;
    }

    if(this._isValidInteraction(interaction)){
        this._setOpen();
    }
};
Flap.prototype._drag = function(interaction){
    var flap = this;

    if(this.constructor.openFlap === this){
        var angle = interaction.getCurrentAngle(true);
        if(angle && !this.beingDragged && ((angle > 45 && angle < 135) || (angle < -45 && angle > -135))){
            return;
        }

        interaction.preventDefault();

        flap.beingDragged = true;
        flap.startDistance = flap.startDistance || flap.distance;
        if(flap.side === 'left'){
            flap.distance = flap.startDistance + interaction.pageX - interaction.lastStart.pageX;
        }else{
            flap.distance = flap.startDistance - interaction.pageX + interaction.lastStart.pageX;
        }
        flap.distance = Math.max(Math.min(flap.distance, flap.width), 0);
        flap.update();
        flap.speed = flap.distance - flap.oldDistance;
        flap.oldDistance = flap.distance;
    }
};
Flap.prototype._end = function(interaction){
    if(this.constructor.openFlap !== this || !this.beingDragged){
        return;
    }

    this.startDistance = null;
    this.beingDragged = false;

    var direction = 'close';

    if(Math.abs(this.speed) >= 3){
        direction = this.speed < 0 ? 'close' : 'open';
    }else if(this.distance < this.width / 2){
        direction = 'close';
    }else{
        direction = 'open';
    }

    this.settle(direction);
};
Flap.prototype._activate = function(event){
    if(!this.enabled){
        return;
    }
    if(
        !doc(event.target).closest(this.content) &&
        this.constructor.openFlap === this
    ){
        event.preventDefault();
        this.beingDragged = false;
        this.settle('close');
    }
};
Flap.prototype._setOpen = function(){
    if(this.constructor.openFlap !== this){
        var flap = this;
        this.constructor.openFlap = this;
        this.element.style['width'] = '100%';
        this.state = 'open';
        this.emit('open');

        // This prevents the flap from screwing up
        // events on elements that may be under the swipe zone
        this._pointerEventTimeout = setTimeout(function(){
            flap.element.style[venfix('pointerEvents')] = 'all';
        },500);
    }
};
Flap.prototype._setClosed = function(){
    this.constructor.openFlap = null;
    clearTimeout(this._pointerEventTimeout);
    this.element.style[venfix('pointerEvents')] = 'none';
    this.element.style['width'] = this.gutter + 'px';
    this.state = 'closed';
    this.emit('close');
};
Flap.prototype.update = function(interaction){
    var flap = this;

    if(this.distance > 0){
        this._setOpen();
    }

    if(this.side === 'left'){
        this.displayPosition = flap.distance - flap.width;
    }else if(this.side === 'right'){
        this.displayPosition = -flap.distance;
    }

    if(flap.distance != flap.lastDistance){
        requestAnimationFrame(function(){
            flap.updateStyle(flap.displayPosition);
            flap.emit('move');
            flap.lastDistance = flap.distance;
        });
    }
};
Flap.prototype.updateStyle = function(displayPosition){
    if(this.enabled){
        this.content.style[venfix('transform')] = 'translate3d(' + (displayPosition) + 'px,0,0)';
    }
};
Flap.prototype.settle = function(direction){
    var flap = this;

    cancelAnimationFrame(this.settleFrame);

    if(this.beingDragged){
        return;
    }
    if(this.distance < 0){
        this.distance = 0;
        this._setClosed();
        this.update();
        this.emit('settle');
        return;
    }else if(this.distance > this.width){
        this.distance = this.width;
        this.update();
        this.emit('settle');
        return;
    }

    this.settleFrame = requestAnimationFrame(function(){
        var step = flap.tween(direction);
        flap.distance += direction === 'close' ? -step : step;
        flap.update();
        flap.settle(direction);
    });
};
Flap.prototype.tween = function(direction){
    return (this.width - this.distance) / 4 + 2;
};
Flap.prototype.percentOpen = function(){
    return parseInt(100 / this.width * this.distance);
};
Flap.prototype.open = function(){
    if(!this.enabled){
        return;
    }
    this.settle('open');
};
Flap.prototype.close = function(){
    if(!this.enabled){
        return;
    }
    this.settle('close');
};
module.exports = Flap;<|endoftext|>


<commit_before>import React from "react";
import { FormattedMessage } from "react-intl";
import PropTypes from "prop-types";
import ComponentTypeIcons from "./ComponentTypeIcons";
import ComponentSummaryList from "./ComponentSummaryList";

class ListItemComponents extends React.Component {
  constructor() {
    super();
    this.state = { expanded: false };
  }

  componentWillReceiveProps(newProps) {
    // compare old value to new value, and if this component is getting new data,
    // then get the current expand state of the new value as it is in the old dom
    // and apply that expand state to this component
    const olditem = this.props.listItem.name;
    const newitem = newProps.listItem.name;
    const parent = this.props.listItemParent;
    if (olditem !== newitem) {
      if ($(`.${parent} [data-component="${newitem.name}"]`).hasClass("active")) {
        this.setState({ expanded: true });
      } else {
        this.setState({ expanded: false });
      }
    }
    if (this.state.expanded === true && newProps.listItem.dependencies === undefined) {
      this.props.fetchDetails(newProps.listItem);
    }
  }

  handleExpandComponent(event) {
    // the user clicked a list item in the blueprint contents area to expand or collapse
    if (!$(event.target).is("button, a, input, .fa-ellipsis-v")) {
      const expandState = !this.state.expanded;
      this.setState(prevState => ({ expanded: !prevState.expanded }));
      if (expandState === true && this.props.listItem.dependencies === undefined) {
        this.props.fetchDetails(this.props.listItem);
      }
    }
  }

  render() {
    const { listItem, noEditComponent, handleComponentDetails, handleRemoveComponent } = this.props;
    const { expanded } = this.state;
    return (
      <div className={`list-pf-item ${expanded ? "active" : ""}`} data-component={listItem.name}>

 this.handleExpandComponent(e)} role="presentation">

            <span className={`fa ${expanded ? "fa-angle-down" : "fa-angle-right"}`} />

            <input type="checkbox" />

              <ComponentTypeIcons
                componentType={listItem.ui_type}
                componentInBlueprint={listItem.inBlueprint}
                isSelected={listItem.userSelected}
              />

                   handleComponentDetails(e, listItem)}>
                    {listItem.name}

{listItem.summary}

                  <FormattedMessage
                    defaultMessage="Version {version}"
                    values={{
                      version: {listItem.version}
                    }}
                  />

                  <FormattedMessage
                    defaultMessage="Release {release}"
                    values={{
                      release: {listItem.release}
                    }}
                  />

            {noEditComponent !== true && (

                  <button
                    className="btn btn-link dropdown-toggle"
                    type="button"
                    id="dropdownKebabRight9"
                    data-toggle="dropdown"
                    aria-haspopup="true"
                    aria-expanded="true"
                  >

                  </button>

                       handleComponentDetails(e, listItem)}>
                        <FormattedMessage defaultMessage="View" />

                    {listItem.inBlueprint && listItem.userSelected && (

                         handleRemoveComponent(e, listItem.name)}>
                          <FormattedMessage defaultMessage="Remove" />

                    )}

            )}

        <div className={`list-pf-expansion collapse ${expanded ? "in" : ""}`}>

                        <FormattedMessage defaultMessage="Version" />

{listItem.version ? listItem.version :  }

                        <FormattedMessage defaultMessage="Release" />

{listItem.release ? listItem.release :  }

URL

                      {(listItem.homepage != null && (

                            {listItem.homepage}

                      )) ||

}

                    {listItem.dependencies && <ComponentSummaryList listItems={listItem.dependencies} />}

    );
  }
}

ListItemComponents.propTypes = {
  listItem: PropTypes.shape({
    arch: PropTypes.string,
    epoch: PropTypes.number,
    inBlueprint: PropTypes.bool,
    name: PropTypes.string,
    summary: PropTypes.string,
    release: PropTypes.string,
    ui_type: PropTypes.string,
    userSelected: PropTypes.bool,
    version: PropTypes.string,
    homepage: PropTypes.string,
    dependencies: PropTypes.arrayOf(PropTypes.object)
  }),
  listItemParent: PropTypes.string,
  componentDetailsParent: PropTypes.shape({
    active: PropTypes.bool,
    group_type: PropTypes.string,
    inBlueprint: PropTypes.bool,
    name: PropTypes.string,
    release: PropTypes.string,
    releaseSelected: PropTypes.string,
    summary: PropTypes.string,
    ui_type: PropTypes.string,
    userSelected: PropTypes.bool,
    version: PropTypes.string,
    versionSelected: PropTypes.string
  }),
  handleComponentDetails: PropTypes.func,
  handleRemoveComponent: PropTypes.func,
  noEditComponent: PropTypes.bool,
  fetchDetails: PropTypes.func
};

ListItemComponents.defaultProps = {
  listItem: {},
  listItemParent: "",
  componentDetailsParent: {},
  handleComponentDetails: function() {},
  handleRemoveComponent: function() {},
  noEditComponent: false,
  fetchDetails: function() {}
};

export default ListItemComponents;
<commit_msg>Remove checkboxes from ListItemComponents component since they were not used<commit_after>import React from "react";
import { FormattedMessage } from "react-intl";
import PropTypes from "prop-types";
import ComponentTypeIcons from "./ComponentTypeIcons";
import ComponentSummaryList from "./ComponentSummaryList";

class ListItemComponents extends React.Component {
  constructor() {
    super();
    this.state = { expanded: false };
  }

  componentWillReceiveProps(newProps) {
    // compare old value to new value, and if this component is getting new data,
    // then get the current expand state of the new value as it is in the old dom
    // and apply that expand state to this component
    const olditem = this.props.listItem.name;
    const newitem = newProps.listItem.name;
    const parent = this.props.listItemParent;
    if (olditem !== newitem) {
      if ($(`.${parent} [data-component="${newitem.name}"]`).hasClass("active")) {
        this.setState({ expanded: true });
      } else {
        this.setState({ expanded: false });
      }
    }
    if (this.state.expanded === true && newProps.listItem.dependencies === undefined) {
      this.props.fetchDetails(newProps.listItem);
    }
  }

  handleExpandComponent(event) {
    // the user clicked a list item in the blueprint contents area to expand or collapse
    if (!$(event.target).is("button, a, input, .fa-ellipsis-v")) {
      const expandState = !this.state.expanded;
      this.setState(prevState => ({ expanded: !prevState.expanded }));
      if (expandState === true && this.props.listItem.dependencies === undefined) {
        this.props.fetchDetails(this.props.listItem);
      }
    }
  }

  render() {
    const { listItem, noEditComponent, handleComponentDetails, handleRemoveComponent } = this.props;
    const { expanded } = this.state;
    return (
      <div className={`list-pf-item ${expanded ? "active" : ""}`} data-component={listItem.name}>

 this.handleExpandComponent(e)} role="presentation">

            <span className={`fa ${expanded ? "fa-angle-down" : "fa-angle-right"}`} />

              <ComponentTypeIcons
                componentType={listItem.ui_type}
                componentInBlueprint={listItem.inBlueprint}
                isSelected={listItem.userSelected}
              />

                   handleComponentDetails(e, listItem)}>
                    {listItem.name}

{listItem.summary}

                  <FormattedMessage
                    defaultMessage="Version {version}"
                    values={{
                      version: {listItem.version}
                    }}
                  />

                  <FormattedMessage
                    defaultMessage="Release {release}"
                    values={{
                      release: {listItem.release}
                    }}
                  />

            {noEditComponent !== true && (

                  <button
                    className="btn btn-link dropdown-toggle"
                    type="button"
                    id="dropdownKebabRight9"
                    data-toggle="dropdown"
                    aria-haspopup="true"
                    aria-expanded="true"
                  >

                  </button>

                       handleComponentDetails(e, listItem)}>
                        <FormattedMessage defaultMessage="View" />

                    {listItem.inBlueprint && listItem.userSelected && (

                         handleRemoveComponent(e, listItem.name)}>
                          <FormattedMessage defaultMessage="Remove" />

                    )}

            )}

        <div className={`list-pf-expansion collapse ${expanded ? "in" : ""}`}>

                        <FormattedMessage defaultMessage="Version" />

{listItem.version ? listItem.version :  }

                        <FormattedMessage defaultMessage="Release" />

{listItem.release ? listItem.release :  }

URL

                      {(listItem.homepage != null && (

                            {listItem.homepage}

                      )) ||

}

                    {listItem.dependencies && <ComponentSummaryList listItems={listItem.dependencies} />}

    );
  }
}

ListItemComponents.propTypes = {
  listItem: PropTypes.shape({
    arch: PropTypes.string,
    epoch: PropTypes.number,
    inBlueprint: PropTypes.bool,
    name: PropTypes.string,
    summary: PropTypes.string,
    release: PropTypes.string,
    ui_type: PropTypes.string,
    userSelected: PropTypes.bool,
    version: PropTypes.string,
    homepage: PropTypes.string,
    dependencies: PropTypes.arrayOf(PropTypes.object)
  }),
  listItemParent: PropTypes.string,
  componentDetailsParent: PropTypes.shape({
    active: PropTypes.bool,
    group_type: PropTypes.string,
    inBlueprint: PropTypes.bool,
    name: PropTypes.string,
    release: PropTypes.string,
    releaseSelected: PropTypes.string,
    summary: PropTypes.string,
    ui_type: PropTypes.string,
    userSelected: PropTypes.bool,
    version: PropTypes.string,
    versionSelected: PropTypes.string
  }),
  handleComponentDetails: PropTypes.func,
  handleRemoveComponent: PropTypes.func,
  noEditComponent: PropTypes.bool,
  fetchDetails: PropTypes.func
};

ListItemComponents.defaultProps = {
  listItem: {},
  listItemParent: "",
  componentDetailsParent: {},
  handleComponentDetails: function() {},
  handleRemoveComponent: function() {},
  noEditComponent: false,
  fetchDetails: function() {}
};

export default ListItemComponents;
<|endoftext|>


<commit_before>// boot jQuery
jQuery.noConflict();

// add load event
Event.observe(window, 'load', init_load_wym_editor, false);
var editors = new Array();
// These tokens are for Radiant CMS radius tags
//XhtmlLexer.prototype.addTokens = function()
//{
//  this.addEntryPattern("</?r:", 'Text', 'Text');
//  this.addExitPattern(">", 'Text');
//
//  this.addCommentTokens('Text');
//  this.addScriptTokens('Text');
//  this.addCssTokens('Text');
//  this.addTagTokens('Text');
//}

function text_input_method(index, filter) {
	if (index != null) {
		// control for page parts
		var elem = $('part_'+(index)+'_content');
		if (filter == "WymEditor") {
			boot_wym(elem);
		} else {
			unboot_wym(elem)
		}
	} else {
		// control for snippets
		var elem = $$('.textarea');
		if (filter == "WymEditor") {
			boot_wym(elem[0]);
		} else {
			unboot_wym(elem[0]);
		}
	}
}

// loads WYMeditor for page parts where "WymEditor" is the selected text filter
function init_load_wym_editor(){
	// add "wymupdate" class to the save buttons:
	for (var i = 0; i < $$(".button").length; i++){
		//$($$(".button")[i]).addClassName('wymupdate');
		// on save, run wymupdate and unboot on all instances;
		Event.observe($$(".button")[i], 'click', unboot_all_wym)
	}

  // check to see if we are working with a page or with a snippet
  if ($('part_0_filter_id'))
  {
    var parts = jQuery('.textarea');
    for (var i = 0; i < parts.length; i++)
    {
      if ($F('part_' + i + '_filter_id') == 'WymEditor') {
				// mark textarea's that need to be wymified
				$('part_'+i+'_content').addClassName('wymified');
      }
    }
		// boot wym on marked textarea's
		ta = $$(".wymified");
		for (var i = 0; i < ta.length; i++){
			boot_wym(ta[i]);
		}

  } else if ($('snippet_filter')) {
    if ($F('snippet_filter') == 'WymEditor') {
			boot_wym(jQuery('.textarea')[0]);
    }
  }
}

function adjustFramesize(iframe) {
  iframe.style.height = (iframe.contentWindow.document.body.offsetHeight + 35) + "px";
  setTimeout(function(){ adjustFramesize(iframe); }, 100);
}

function boot_wym(elem){
  jQuery(elem).wymeditor({
    lang: 'en',
    skin: 'radiant',
    iframeBasePath: '/wymeditor/wymeditor/iframe/radiant/',
    classesItems: [
		  {'name': 'float_left', 'title': 'Left', 'expr': 'p'},
		  {'name': 'float_right', 'title': 'Right', 'expr': 'p'},
		  {'name': 'centered', 'title': 'Centered', 'expr': 'p'},
		  {'name': 'justified', 'title': 'Justified', 'expr': 'p'}
		],
    editorStyles: [
		  {'name': '.float_left',
		   'css': 'color: #999; border: 2px solid #ccc;'},
		  {'name': '.float_right',
		   'css': 'color: #999; border: 2px solid #ccc;'},
		  {'name': '.maxwidth',
		   'css': 'color: #333; border: 2px solid #ccc;'},
		  {'name': '.narrow',
		   'css': 'color: #666; border: 2px solid #CCC;'},
		  {'name': '.radius_tag',
       'css': 'height:31px; background:url(/images/admin/wef_radiustag_bg.gif) no-repeat 0 0;'},
      {'name': 'div',
       'css': 'background:#fafceb url(/images/admin/lbl-div.png) no-repeat 2px 2px; margin:10px; padding:10px;'}
    ],
    postInit: function(wym) {
      // map the index of this instance to it's page_part
      editors[elem.id] = wym._index;
      bind_droppability(wym._iframe);
      adjustFramesize(wym._iframe);
    },

		preInit: function(wym) {
      //change_radius_to_imgs
      var content = (wym._html);
      var m = content.match(/(<r:([^\/><]*)?\/?>)|(<\/r:([^>]*)?>)/g);
      if (!(m == null)) {
        for (var i=0; i < m.length; i++) {
          var title = m[i].replace(/"/g, "'");
          title = title.substring(1,title.length-1);
          var match = escape(m[i].substring(1,m[i].length - 1));
          var regex = new RegExp('(' + m[i] + ')', 'i');
          var content = content.replace(regex, '
');
        }
      }
      wym._html = content;
    }
  });
}

function unboot_wym(elem){
  // hide wym
  jQuery(elem).parent().find(".wym_box").remove();
  // revert images to radius tags
  var content = elem.value;
  var regex = new RegExp('
', 'gi');
  var m = content.match(regex);
  if (!(m == null)) {
    for (var i=0; i<m.length; i++) {
      var match = unescape(m[i].replace(regex, '<$1>'));
      var content = content.replace(m[i], match);
    }
  }
  // fix urls to page attachments
  var regex = new RegExp('src="([\.\/]+)/page_attachments', 'g');
  var m = content.match(regex);
  if(!(m == null)) {
    for(var i=0; i<m.length; i++){
      var match = unescape(m[i].replace(regex, 'src="/page_attachments'));
      var content = content.replace(m[i], match)
    }
  }
  // fix urls to assets
  var regex = new RegExp('src="([\.\/]+)/assets', 'g');
  var m = content.match(regex);
  if(!(m == null)) {
    for(var i=0; i<m.length; i++){
      var match = unescape(m[i].replace(regex, 'src="/assets'));
      var content = content.replace(m[i], match)
    }
  }
  elem.value = content;
  // show textarea again
  jQuery(elem).show();
}

function unboot_all_wym() {
  // save button clicked, update all wym instances
  if ($('part_0_filter_id')) 								// We're on the page edit screen
  {
    for(var i=0;i<$$(".part").length;i++) {
      // Find all parts that have WYM set as filter
      filter_select = $("part_" + i + "_filter_id");
      if(filter_select.value == 'WymEditor'){
        var index = editors["part_" + i + "_content"];
        WYMeditor.INSTANCES[index].update();
      }
    }
  } else if ($('snippet_filter')) { 				// We're on the snippet edit screen
    if ($F('snippet_filter') == 'WymEditor') {
      WYMeditor.INSTANCES[0].update();
    }
  }
  return true;
}

function bind_droppability(box) {
  Droppables.add(box, {
    accept: 'asset',
    onDrop: function(element) {
      var classes = element.className.split(' ');
      var tag_type = classes[0];
      var link = element.select('a.bucket_link')[0];
      if(tag_type == 'image'){
        // copy the original image to WYM
        var tag = '';
      }
      else{
        // copy a link to WYM
        var asset_id = element.id.split('_').last();
        var tag = ''+ link.title +''
      }
      var wym_index = editors["part_" + (box.ancestors()[2].ancestors()[1].id.split('-')[1] - 1)  + "_content"];
      var wymm = WYMeditor.INSTANCES[wym_index];
      wymm.insert(tag);
    }
  });
  new Draggable('asset-bucket', { starteffect: 'none' });
}
<commit_msg>Restore original classes<commit_after>// boot jQuery
jQuery.noConflict();

// add load event
Event.observe(window, 'load', init_load_wym_editor, false);
var editors = new Array();
// These tokens are for Radiant CMS radius tags
//XhtmlLexer.prototype.addTokens = function()
//{
//  this.addEntryPattern("</?r:", 'Text', 'Text');
//  this.addExitPattern(">", 'Text');
//
//  this.addCommentTokens('Text');
//  this.addScriptTokens('Text');
//  this.addCssTokens('Text');
//  this.addTagTokens('Text');
//}

function text_input_method(index, filter) {
	if (index != null) {
		// control for page parts
		var elem = $('part_'+(index)+'_content');
		if (filter == "WymEditor") {
			boot_wym(elem);
		} else {
			unboot_wym(elem)
		}
	} else {
		// control for snippets
		var elem = $$('.textarea');
		if (filter == "WymEditor") {
			boot_wym(elem[0]);
		} else {
			unboot_wym(elem[0]);
		}
	}
}

// loads WYMeditor for page parts where "WymEditor" is the selected text filter
function init_load_wym_editor(){
	// add "wymupdate" class to the save buttons:
	for (var i = 0; i < $$(".button").length; i++){
		//$($$(".button")[i]).addClassName('wymupdate');
		// on save, run wymupdate and unboot on all instances;
		Event.observe($$(".button")[i], 'click', unboot_all_wym)
	}

  // check to see if we are working with a page or with a snippet
  if ($('part_0_filter_id'))
  {
    var parts = jQuery('.textarea');
    for (var i = 0; i < parts.length; i++)
    {
      if ($F('part_' + i + '_filter_id') == 'WymEditor') {
				// mark textarea's that need to be wymified
				$('part_'+i+'_content').addClassName('wymified');
      }
    }
		// boot wym on marked textarea's
		ta = $$(".wymified");
		for (var i = 0; i < ta.length; i++){
			boot_wym(ta[i]);
		}

  } else if ($('snippet_filter')) {
    if ($F('snippet_filter') == 'WymEditor') {
			boot_wym(jQuery('.textarea')[0]);
    }
  }
}

function adjustFramesize(iframe) {
  iframe.style.height = (iframe.contentWindow.document.body.offsetHeight + 35) + "px";
  setTimeout(function(){ adjustFramesize(iframe); }, 100);
}

function boot_wym(elem){
  jQuery(elem).wymeditor({
    lang: 'en',
    skin: 'radiant',
    iframeBasePath: '/wymeditor/wymeditor/iframe/radiant/',
    classesItems: [
          {'name': 'float_left', 'title': 'PARA: left', 'expr': 'p'},
          {'name': 'float_right', 'title': 'PARA: right', 'expr': 'p'},
          {'name': 'maxwidth', 'title': 'PARA: maxwidth', 'expr': 'p'},
          {'name': 'narrow', 'title': 'PARA: narrow', 'expr': 'p'}
		],
    editorStyles: [
		  {'name': '.float_left',
		   'css': 'color: #999; border: 2px solid #ccc;'},
		  {'name': '.float_right',
		   'css': 'color: #999; border: 2px solid #ccc;'},
		  {'name': '.maxwidth',
		   'css': 'color: #333; border: 2px solid #ccc;'},
		  {'name': '.narrow',
		   'css': 'color: #666; border: 2px solid #CCC;'},
		  {'name': '.radius_tag',
       'css': 'height:31px; background:url(/images/admin/wef_radiustag_bg.gif) no-repeat 0 0;'},
      {'name': 'div',
       'css': 'background:#fafceb url(/images/admin/lbl-div.png) no-repeat 2px 2px; margin:10px; padding:10px;'}
    ],
    postInit: function(wym) {
      // map the index of this instance to it's page_part
      editors[elem.id] = wym._index;
      bind_droppability(wym._iframe);
      adjustFramesize(wym._iframe);
    },

		preInit: function(wym) {
      //change_radius_to_imgs
      var content = (wym._html);
      var m = content.match(/(<r:([^\/><]*)?\/?>)|(<\/r:([^>]*)?>)/g);
      if (!(m == null)) {
        for (var i=0; i < m.length; i++) {
          var title = m[i].replace(/"/g, "'");
          title = title.substring(1,title.length-1);
          var match = escape(m[i].substring(1,m[i].length - 1));
          var regex = new RegExp('(' + m[i] + ')', 'i');
          var content = content.replace(regex, '
');
        }
      }
      wym._html = content;
    }
  });
}

function unboot_wym(elem){
  // hide wym
  jQuery(elem).parent().find(".wym_box").remove();
  // revert images to radius tags
  var content = elem.value;
  var regex = new RegExp('
', 'gi');
  var m = content.match(regex);
  if (!(m == null)) {
    for (var i=0; i<m.length; i++) {
      var match = unescape(m[i].replace(regex, '<$1>'));
      var content = content.replace(m[i], match);
    }
  }
  // fix urls to page attachments
  var regex = new RegExp('src="([\.\/]+)/page_attachments', 'g');
  var m = content.match(regex);
  if(!(m == null)) {
    for(var i=0; i<m.length; i++){
      var match = unescape(m[i].replace(regex, 'src="/page_attachments'));
      var content = content.replace(m[i], match)
    }
  }
  // fix urls to assets
  var regex = new RegExp('src="([\.\/]+)/assets', 'g');
  var m = content.match(regex);
  if(!(m == null)) {
    for(var i=0; i<m.length; i++){
      var match = unescape(m[i].replace(regex, 'src="/assets'));
      var content = content.replace(m[i], match)
    }
  }
  elem.value = content;
  // show textarea again
  jQuery(elem).show();
}

function unboot_all_wym() {
  // save button clicked, update all wym instances
  if ($('part_0_filter_id')) 								// We're on the page edit screen
  {
    for(var i=0;i<$$(".part").length;i++) {
      // Find all parts that have WYM set as filter
      filter_select = $("part_" + i + "_filter_id");
      if(filter_select.value == 'WymEditor'){
        var index = editors["part_" + i + "_content"];
        WYMeditor.INSTANCES[index].update();
      }
    }
  } else if ($('snippet_filter')) { 				// We're on the snippet edit screen
    if ($F('snippet_filter') == 'WymEditor') {
      WYMeditor.INSTANCES[0].update();
    }
  }
  return true;
}

function bind_droppability(box) {
  Droppables.add(box, {
    accept: 'asset',
    onDrop: function(element) {
      var classes = element.className.split(' ');
      var tag_type = classes[0];
      var link = element.select('a.bucket_link')[0];
      if(tag_type == 'image'){
        // copy the original image to WYM
        var tag = '';
      }
      else{
        // copy a link to WYM
        var asset_id = element.id.split('_').last();
        var tag = ''+ link.title +''
      }
      var wym_index = editors["part_" + (box.ancestors()[2].ancestors()[1].id.split('-')[1] - 1)  + "_content"];
      var wymm = WYMeditor.INSTANCES[wym_index];
      wymm.insert(tag);
    }
  });
  new Draggable('asset-bucket', { starteffect: 'none' });
}
<|endoftext|>


<commit_before>var CHROME_VERSION = '44';
var FIREFOX_VERSION = '40';
var SAFARI_VERSION = '8.1';
var IOS_VERSION = ' 9.0';       // Workaround for optimist converting to float
var ANDROID_VERSION = ' 5.1';

var browsers = {
  'mac-chrome'  : ['Mac 10.11', 'chrome', CHROME_VERSION],
  'mac-firefox' : ['Mac 10.11', 'firefox', FIREFOX_VERSION],
  'mac-safari'  : ['Mac 10.11', 'safari', SAFARI_VERSION],

  'windows-chrome'  : ['Windows 10', 'chrome', CHROME_VERSION],
  'windows-firefox' : ['Windows 10', 'firefox', FIREFOX_VERSION],
  'windows-ie-11'   : ['Windows 10', 'internet explorer', '11'],

  'windows-ie-10'   : ['Windows 7', 'internet explorer', '10'],
  'windows-ie-9'    : ['Windows 7', 'internet explorer', '9'],

  'linux-chrome'    : ['Linux', 'chrome', CHROME_VERSION],
  'linux-firefox'   : ['Linux', 'firefox', FIREFOX_VERSION],

  'iphone'  : ['Mac 10.10', 'iphone', IOS_VERSION],
  'ipad'    : ['Mac 10.10', 'ipad', IOS_VERSION],
  'android' : ['Linux', 'android', ANDROID_VERSION]
};

module.exports = browsers;
<commit_msg>replace ie9 with ms edge<commit_after>var CHROME_VERSION = '44';
var FIREFOX_VERSION = '40';
var SAFARI_VERSION = '8.1';
var IOS_VERSION = ' 9.0';       // Workaround for optimist converting to float
var ANDROID_VERSION = ' 5.1';

var browsers = {
  'mac-chrome'  : ['Mac 10.11', 'chrome', CHROME_VERSION],
  'mac-firefox' : ['Mac 10.11', 'firefox', FIREFOX_VERSION],
  'mac-safari'  : ['Mac 10.11', 'safari', SAFARI_VERSION],

  'windows-chrome'  : ['Windows 10', 'chrome', CHROME_VERSION],
  'windows-firefox' : ['Windows 10', 'firefox', FIREFOX_VERSION],
  'windows-ms-edge' : ['Windows 10', 'microsoftedge', '20.10240'],
  'windows-ie-11'   : ['Windows 10', 'internet explorer', '11'],
  'windows-ie-10'   : ['Windows 7', 'internet explorer', '10'],

  'linux-chrome'    : ['Linux', 'chrome', CHROME_VERSION],
  'linux-firefox'   : ['Linux', 'firefox', FIREFOX_VERSION],

  'iphone'  : ['Mac 10.10', 'iphone', IOS_VERSION],
  'ipad'    : ['Mac 10.10', 'ipad', IOS_VERSION],
  'android' : ['Linux', 'android', ANDROID_VERSION]
};

module.exports = browsers;
<|endoftext|>