<commit_before>import React, { Component } from 'react'
import { Form, Button, Input, Row, Col, Select, TreeSelect, message, Modal, Radio } from 'antd'
import Spin from 'COMPONENT/Spin'

const FormItem = Form.Item
const Option = Select.Option
const TreeNode = TreeSelect.TreeNode
const SHOW_PARENT = TreeSelect.SHOW_PARENT

const aCity = {11: '北京', 12: '天津', 13: '河北', 14: '山西', 15: '内蒙古', 21: '辽宁', 22: '吉林', 23: '黑龙江', 31: '上海', 32: '江苏', 33: '浙江', 34: '安徽', 35: '福建', 36: '江西', 37: '山东', 41: '河南', 42: '湖北', 43: '湖南', 44: '广东', 45: '广西', 46: '海南', 50: '重庆', 51: '四川', 52: '贵州', 53: '云南', 54: '西藏', 61: '陕西', 62: '甘肃', 63: '青海', 64: '宁夏', 65: '新疆', 71: '台湾', 81: '香港', 82: '澳门', 91: '国外'}

let BranchAdd = class BranchAddView extends Component {

  constructor(props) {
    super(props)
    this.state = {
      loading: false
    }
    this.certCheck = this.certCheck.bind(this)
  }

  componentWillMount() {
    this.props.form.resetFields()
  }

  onClose() {
    this.props.setAddUserBoxVsisible(false)
    this.onClear()
  }

  onClear() {
    this.props.cleanBranch()
    this.props.form.resetFields()
  }

  onSubmit() {
    const { form, postList, addUser, selectBranchId, branchList, branchAdd } = this.props
    const { getFieldsValue, validateFields, resetFields } = form
    validateFields((errors, values) => {
      if (!!errors) {
        message.error('填写内容有错误，请仔细填写!')
      } else {
        let params = getFieldsValue()

        // 取到岗位名
        let postId = params.postId
        let postName = ''
        postList.map(item => {
          if (postId && item.postId == postId) {
            postName = item.postName
          }
        })

        // 取到机构名
        let brhName = ''
        branchList.map(item => {
          if (selectBranchId && item.brhId == selectBranchId) {
            brhName = item.brhName
          }
        })

        let data = Object.assign({
        },
        getFieldsValue(), {
          brhName: brhName,
          brhId: selectBranchId,
          postName: postName
        })

        const showSpin = () => {
          this.setState({
            loading: true
          })
        }
        const hideSpin = () => {
          this.setState({
            loading: false
          })
        }

        console.log(data)
        showSpin()
        addUser(data, () => {
          hideSpin()
          this.onClear()
          this.onClose()
        }, hideSpin)
      }
    })
  }

  phoneNumberCheck(rule, value, callback) {
    let reg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/
    if (!reg.test(value)) {
      callback('请输入有效的手机号码！')
    } else {
      callback()
    }
  }

  pswdCheck(rule, value, callback) {
    const reg = /^\w{6,20}$/
    !reg.test(value) ?
    callback([new Error('密码为6~20位字符！')]) :
    callback()
  }

  certCheck(rule, value, callback) {
    const { getFieldValue } = this.props.form
    let key = getFieldValue('userCertType')
    if (key == '1') {
      var iSum = 0
      if (!/^\d{17}(\d|x)$/i.test(value)) {
        // callback('身份证长度或格式错误！')
        return
      }
      value = value.replace(/x$/i,'a')
      if (!aCity[parseInt(value.substring(0,2))]) {
        // callback('身份证地区非法！')
        return
      }
      let sBirthday = `${value.substr(6, 4)}/${Number(value.substr(10, 2))}/${Number(value.substr(12, 2))}`
      let birthDate = new Date(sBirthday)
      if (sBirthday != `${birthDate.getFullYear()}/${(birthDate.getMonth() + 1)}/${ birthDate.getDate()}`) {
        // callback('身份证出生日期非法！')
        return
      }
      for (var i = 17; i >= 0; i--) {
        iSum += (Math.pow(2, i) % 11) * parseInt(value.charAt(17 - i), 11)
      }
      if (iSum % 11 != 1) {
        // callback('身份证号非法！')
        return
      }
      callback()
    } else if (key == '2') {
      const hureg = /^\w{7,}$/
      if (!hureg.test(value)){
        //callback([new Error('请输入正确的护照！')])
        return
      }
      callback()
    } else if (key == '3') {
      const greg = /^[G|T|S|L|Q|D|C|W]\w{9,11}\S+$/;
      if (!greg.test(value)) {
        //callback([new Error('请输入正确的港澳通行证！')])
        return
      }
      callback()
    } else {
      callback([new Error('请先选择证件类型！')])
      return
    }

  }

  render() {
    const { visible, certType, postList, level, updateBranch, branchNodes, selectBranchId } = this.props
    const { getFieldDecorator, resetFields } = this.props.form

    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 16 }
    }

    const certTypeList = certType.map(item => <Option value={item.paramKey} key={item.paramKey} >{item.paramValue}</Option>)

    const postSelectList = postList.map(item => <Option key={item.postId} value={item.postId}>{item.postName}</Option>)

    const onChange = (value) => {
      updateBranch(value)
    }

    // 用户等级
    const userLevelList = level.map(
      item => <Option value={item.paramKey} key={item.paramKey} >{item.paramValue}</Option>
    )

    const treeProps  = {
      dropdownStyle: { maxHeight: 400, overflow: 'auto' },
      treeData: branchNodes,
      onChange: onChange,
      value: selectBranchId,
      placeholder: "请选择",
      treeDefaultExpandAll: true,
      treeCheckStrictly: false,
      treeCheckable: false,
      showCheckedStrategy: SHOW_PARENT
    }

    return (
      <div className="BranchAdd">
        <Modal
          title="新增用户"
          width={600}
          visible={visible}
          onOk={this.onSubmit}
          onCancel={e => this.onClose()}
          footer={[
              <Button
                key="back"
                type="ghost"
                size="large"
                onClick={(e) => this.onClose()}
              >
                返 回
              </Button>,

              <Button
                key="clean"
                type="ghost"
                size="large"
                onClick={(e) => this.onClear()}
              >
                清除所有
              </Button>,

              <Button
                key="submit"
                type="primary"
                size="large"
                onClick={(e) => this.onSubmit()}
              >
                提 交
              </Button>
            ]}
          >
            <Form horizontal>
              <Row>
                <Col span={12}>
                  <FormItem
                    label='用户姓名：'
                    {...formItemLayout}
                    required
                    hasFeedback
                  >
                    {
                      getFieldDecorator('userName', {
                        initialValue: '',
                        rules: [{
                          required: true,
                          whitespace:true,
                          message: ' '
                        }]
                      })(
                        <Input
                          placeholder='请输入用户名'
                          size='large'
                         />
                      )
                    }
                  </FormItem>
                </Col>
                <Col span={12}>
                  <FormItem
                    label='登录用户：'
                    {...formItemLayout}
                    required
                    hasFeedback
                  >
                    {
                      getFieldDecorator('userLoginName', {
                        initialValue: '',
                        rules: [{
                          required: true,
                          message: ' '
                        }]
                      })(
                        <Input
                          placeholder='请输入登录账号'
                          size='large'
                         />
                      )
                    }
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={12}>
                  <FormItem
                    label='登录密码：'
                    {...formItemLayout}
                    required
                    hasFeedback
                  >
                    {
                      getFieldDecorator('userPwd', {
                        initialValue: '',
                        rules: [{
                          required: true,
                          message: ' '
                        }, {
                          validator: this.pswdCheck
                        }]
                      })(
                        <Input
                          type='password'
                          placeholder='请输入密码'
                          size='large'
                         />
                      )
                    }
                  </FormItem>
                </Col>
                <Col span={12}>
                  <FormItem
                    label='用户描述：'
                    {...formItemLayout}
                  >
                    {
                      getFieldDecorator('userDesc', {
                        initialValue: '',
                      })(
                        <Input
                          placeholder='请填写用户描述'
                          size='large'
                         />
                      )
                    }
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={12}>
                  <FormItem
                    label='用户邮箱：'
                    {...formItemLayout}
                    required
                    hasFeedback
                  >
                    {
                      getFieldDecorator('userEmail', {
                        initialValue: '',
                        validate: [{
                          rules: [{
                            required: true,message:' '
                          }],
                          trigger: 'onBlur',
                         }, {
                          rules: [{
                            type: 'email',
                            message: ' '
                          }],
                          trigger: ['onBlur', 'onChange']
                         }]
                      })(
                        <Input
                          placeholder='请输入邮箱地址'
                          size='large'
                         />
                      )
                    }
                  </FormItem>
                </Col>
                <Col span={12}>
                  <FormItem
                    label='用户住址：'
                    {...formItemLayout}
                  >
                    {
                      getFieldDecorator('userAddress', {
                        initialValue: '',
                      })(
                        <Input
                          placeholder='请填写用户住址'
                          size='large'
                         />
                      )
                    }
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={12}>
                  <FormItem
                    label='证件类型：'
                    {...formItemLayout}
                    required
                    hasFeedback
                  >
                    {
                      getFieldDecorator('userCertType', {
                        initialValue: '',
                        rules: [{
                          required: true,
                          message: ' '
                        }]
                      })(
                        <Select placeholder='请选择证件类型'>
                          {certTypeList}
                        </Select>
                      )
                    }
                  </FormItem>
                </Col>
                <Col span={12}>
                  <FormItem
                    label='证件号码：'
                    {...formItemLayout}
                    required
                    hasFeedback
                  >
                    {
                      getFieldDecorator('userCertNo', {
                        initialValue: '',
                        rules: [{
                          required: true,
                          message: ' '
                        }, {
                          validator: this.certCheck
                        }]
                      })(
                        <Input
                          placeholder='请输入证件号码'
                          size='large'
                         />
                      )
                    }
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={12}>
                  <FormItem
                    label='手机号码：'
                    {...formItemLayout}
                    required
                    hasFeedback
                  >
                    {
                      getFieldDecorator('brhPhone', {
                        initialValue: '',
                        rules: [
                          {
                            required: true,
                            message: ' '
                          }, {
                            validator: this.phoneNumberCheck
                          }
                        ]
                      })(
                        <Input
                          placeholder='请输入手机号码'
                          size='large'
                        />
                      )
                    }
                  </FormItem>
                </Col>
                <Col span={12}>
                  <FormItem
                    label='所属机构：'
                    required
                    hasFeedback
                    {...formItemLayout}
                  >
                    {<TreeSelect
                      placeholder='请选择所属机构'
                      {...treeProps}
                      allowClear={true}
                    >
                    </TreeSelect>}
                  </FormItem>
                </Col>
              </Row>

              <Row>
                <Col span={12}>
                  <FormItem
                    label='岗位选择：'
                    {...formItemLayout}
                  >
                    {
                      getFieldDecorator('postId', {
                        initialValue: '',
                        rules: [{
                          message: ' '
                        }]
                      })(
                        <Select placeholder='请选择岗位'>
                          {postSelectList}
                        </Select>
                      )
                    }
                  </FormItem>
                </Col>
                <Col span={12}>
                  <FormItem
                    label='用户等级：'
                    {...formItemLayout}
                    required
                    hasFeedback
                  >
                    {
                      getFieldDecorator('userLevel', {
                        initialValue: '',
                        rules: [{
                          required: true,
                          message: ' '
                        }]
                      })(
                        <Select placeholder='请选择用户等级'>
                          {userLevelList}
                        </Select>
                      )
                    }
                  </FormItem>
                </Col>
              </Row>
            </Form>
            <Spin loading={this.state.loading}/>
          </Modal>
      </div>
    )
  }
}

export default Form.create()(BranchAdd)<commit_msg>记得修改用户管理页面的用户级别<commit_after>import React, { Component } from 'react'
import { Form, Button, Input, Row, Col, Select, TreeSelect, message, Modal, Radio } from 'antd'
import Spin from 'COMPONENT/Spin'

const FormItem = Form.Item
const Option = Select.Option
const TreeNode = TreeSelect.TreeNode
const RadioGroup = Radio.Group
const SHOW_PARENT = TreeSelect.SHOW_PARENT

const aCity = {11: '北京', 12: '天津', 13: '河北', 14: '山西', 15: '内蒙古', 21: '辽宁', 22: '吉林', 23: '黑龙江', 31: '上海', 32: '江苏', 33: '浙江', 34: '安徽', 35: '福建', 36: '江西', 37: '山东', 41: '河南', 42: '湖北', 43: '湖南', 44: '广东', 45: '广西', 46: '海南', 50: '重庆', 51: '四川', 52: '贵州', 53: '云南', 54: '西藏', 61: '陕西', 62: '甘肃', 63: '青海', 64: '宁夏', 65: '新疆', 71: '台湾', 81: '香港', 82: '澳门', 91: '国外'}

let BranchAdd = class BranchAddView extends Component {

  constructor(props) {
    super(props)
    this.state = {
      loading: false
    }
    this.certCheck = this.certCheck.bind(this)
  }

  componentWillMount() {
    this.props.form.resetFields()
  }

  onClose() {
    this.props.setAddUserBoxVsisible(false)
    this.onClear()
  }

  onClear() {
    this.props.cleanBranch()
    this.props.form.resetFields()
  }

  onSubmit() {
    const { form, postList, addUser, selectBranchId, branchList, branchAdd } = this.props
    const { getFieldsValue, validateFields, resetFields } = form
    validateFields((errors, values) => {
      if (!!errors) {
        message.error('填写内容有错误，请仔细填写！')
      } else {
        let params = getFieldsValue()

        // 取到岗位名
        let postId = params.postId
        let postName = ''
        postList.map(item => {
          if (postId && item.postId == postId) {
            postName = item.postName
          }
        })

        // 取到机构名
        let brhName = ''
        branchList.map(item => {
          if (selectBranchId && item.brhId == selectBranchId) {
            brhName = item.brhName
          }
        })

        let data = Object.assign({
        },
        getFieldsValue(), {
          brhName: brhName,
          brhId: selectBranchId,
          postName: postName
        })

        const showSpin = () => {
          this.setState({
            loading: true
          })
        }
        const hideSpin = () => {
          this.setState({
            loading: false
          })
        }

        console.log(data)
        showSpin()
        addUser(data, () => {
          hideSpin()
          this.onClear()
          this.onClose()
        }, hideSpin)
      }
    })
  }

  phoneNumberCheck(rule, value, callback) {
    let reg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/
    if (!reg.test(value)) {
      callback('请输入有效的手机号码')
    } else {
      callback()
    }
  }

  pswdCheck(rule, value, callback) {
    const reg = /^\w{6,20}$/
    !reg.test(value) ?
    callback([new Error('密码为6~20位字符')]) :
    callback()
  }

  certCheck(rule, value, callback) {
    const { getFieldValue } = this.props.form
    let key = getFieldValue('userCertType')
    if (key == '1') {
      var iSum = 0
      if (!/^\d{17}(\d|x)$/i.test(value)) {
        callback('身份证长度或格式错误')
        return
      }
      value = value.replace(/x$/i,'a')
      if (!aCity[parseInt(value.substring(0,2))]) {
        callback('身份证地区非法')
        return
      }
      let sBirthday = `${value.substr(6, 4)}/${Number(value.substr(10, 2))}/${Number(value.substr(12, 2))}`
      let birthDate = new Date(sBirthday)
      if (sBirthday != `${birthDate.getFullYear()}/${(birthDate.getMonth() + 1)}/${ birthDate.getDate()}`) {
        callback('身份证出生日期非法')
        return
      }
      for (var i = 17; i >= 0; i--) {
        iSum += (Math.pow(2, i) % 11) * parseInt(value.charAt(17 - i), 11)
      }
      if (iSum % 11 != 1) {
        callback('身份证号非法')
        return
      }
      callback()
    } else if (key == '2') {
      const hureg = /^\w{7,}$/
      if (!hureg.test(value)){
        callback([new Error('请输入正确的护照')])
        return
      }
      callback()
    } else if (key == '3') {
      const greg = /^[G|T|S|L|Q|D|C|W]\w{9,11}\S+$/;
      if (!greg.test(value)) {
        callback([new Error('请输入正确的港澳通行证')])
        return
      }
      callback()
    } else if (value) {
      callback([new Error('请先选择证件类型')])
      return
    } else {
      callback()
      return
    }

  }

  render() {
    const { visible, certType, postList, level, updateBranch, branchNodes, selectBranchId } = this.props
    const { getFieldDecorator, resetFields } = this.props.form

    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 16 }
    }

    const certTypeList = certType.map(item => <Option value={item.paramKey} key={item.paramKey} >{item.paramValue}</Option>)

    const postSelectList = postList.map(item => <Option key={item.postId} value={item.postId}>{item.postName}</Option>)

    const onChange = (value) => {
      updateBranch(value)
    }

    // 用户等级
    const userLevelList = level.map(
      item => <Option value={item.paramKey} key={item.paramKey} >{item.paramValue}</Option>
    )

    const treeProps  = {
      dropdownStyle: { maxHeight: 400, overflow: 'auto' },
      treeData: branchNodes,
      onChange: onChange,
      value: selectBranchId,
      placeholder: '请选择',
      treeDefaultExpandAll: true,
      treeCheckStrictly: false,
      treeCheckable: false,
      showCheckedStrategy: SHOW_PARENT
    }

    return (
      <div className='BranchAdd'>
        <Modal
          title='新增用户'
          width={600}
          visible={visible}
          onOk={this.onSubmit}
          onCancel={e => this.onClose()}
          footer={[
              <Button
                key='back'
                type='ghost'
                size='large'
                onClick={(e) => this.onClose()}
              >
                返 回
              </Button>,

              <Button
                key='clean'
                type='ghost'
                size='large'
                onClick={(e) => this.onClear()}
              >
                清除所有
              </Button>,

              <Button
                key='submit'
                type='primary'
                size='large'
                onClick={(e) => this.onSubmit()}
              >
                提 交
              </Button>
            ]}
          >
            <Form horizontal>
              <Row>
                <Col span={12}>
                  <FormItem
                    label='用户姓名：'
                    {...formItemLayout}
                    required
                    hasFeedback
                  >
                    {
                      getFieldDecorator('userName', {
                        initialValue: '',
                        validate: [{
                          rules: [{
                            required: true,
                            message: '请输入用户名'
                          }],
                          trigger: 'onBlur'
                        }]
                      })(
                        <Input
                          placeholder='请输入用户名'
                          size='large'
                         />
                      )
                    }
                  </FormItem>
                </Col>
                <Col span={12}>
                  <FormItem
                    label='登录用户：'
                    {...formItemLayout}
                    required
                    hasFeedback
                  >
                    {
                      getFieldDecorator('userLoginName', {
                        initialValue: '',
                        validate: [{
                          rules: [{
                            required: true,
                            message: '请输入登录账号'
                          }],
                          trigger: 'onBlur'
                        }]
                      })(
                        <Input
                          placeholder='请输入登录账号'
                          size='large'
                         />
                      )
                    }
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={12}>
                  <FormItem
                    label='登录密码：'
                    {...formItemLayout}
                    required
                    hasFeedback
                  >
                    {
                      getFieldDecorator('userPwd', {
                        initialValue: '',
                        rules: [{
                          required: true,
                          message: ' '
                        }, {
                          validator: this.pswdCheck
                        }]
                      })(
                        <Input
                          type='password'
                          placeholder='请输入密码'
                          size='large'
                         />
                      )
                    }
                  </FormItem>
                </Col>
                <Col span={12}>
                  <FormItem
                    label='用户描述：'
                    {...formItemLayout}
                  >
                    {
                      getFieldDecorator('userDesc', {
                        initialValue: '',
                      })(
                        <Input
                          placeholder='请填写用户描述'
                          size='large'
                         />
                      )
                    }
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={12}>
                  <FormItem
                    label='用户邮箱：'
                    {...formItemLayout}
                    required
                    hasFeedback
                  >
                    {
                      getFieldDecorator('userEmail', {
                        initialValue: '',
                        validate: [{
                          rules: [{
                            required: true,
                            message:'请输入邮箱地址'
                          }],
                          trigger: 'onBlur',
                         }, {
                          rules: [{
                            type: 'email',
                            message: '请输入正确邮箱地址'
                          }],
                          trigger: ['onBlur', 'onChange']
                         }]
                      })(
                        <Input
                          placeholder='请输入邮箱地址'
                          size='large'
                         />
                      )
                    }
                  </FormItem>
                </Col>
                <Col span={12}>
                  <FormItem
                    label='用户住址：'
                    {...formItemLayout}
                  >
                    {
                      getFieldDecorator('userAddress', {
                        initialValue: '',
                      })(
                        <Input
                          placeholder='请填写用户住址'
                          size='large'
                         />
                      )
                    }
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={12}>
                  <FormItem
                    label='证件类型：'
                    {...formItemLayout}
                    required
                    hasFeedback
                  >
                    {
                      getFieldDecorator('userCertType', {
                        initialValue: '',
                        rules: [{
                          required: true,
                          message: '请选择证件类型'
                        }]
                      })(
                        <Select placeholder='请选择证件类型'>
                          {certTypeList}
                        </Select>
                      )
                    }
                  </FormItem>
                </Col>
                <Col span={12}>
                  <FormItem
                    label='证件号码：'
                    {...formItemLayout}
                    required
                    hasFeedback
                  >
                    {
                      getFieldDecorator('userCertNo', {
                        initialValue: '',
                        rules: [{
                          required: true,
                          message: '请输入证件号码'
                        }, {
                          validator: this.certCheck
                        }]
                      })(
                        <Input
                          placeholder='请输入证件号码'
                          size='large'
                         />
                      )
                    }
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={12}>
                  <FormItem
                    label='手机号码：'
                    {...formItemLayout}
                    required
                    hasFeedback
                  >
                    {
                      getFieldDecorator('brhPhone', {
                        initialValue: '',
                        rules: [
                          {
                            required: true,
                            message: ' '
                          }, {
                            validator: this.phoneNumberCheck
                          }
                        ]
                      })(
                        <Input
                          placeholder='请输入手机号码'
                          size='large'
                        />
                      )
                    }
                  </FormItem>
                </Col>
                <Col span={12}>
                  <FormItem
                    label='所属机构：'
                    required
                    hasFeedback
                    {...formItemLayout}
                  >
                    {<TreeSelect
                      placeholder='请选择所属机构'
                      {...treeProps}
                      allowClear={true}
                    >
                    </TreeSelect>}
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={12}>
                  <FormItem
                    label='岗位选择：'
                    {...formItemLayout}
                  >
                    {
                      getFieldDecorator('postId', {
                        initialValue: '',
                        rules: [{
                          message: '请选择岗位'
                        }]
                      })(
                        <Select placeholder='请选择岗位'>
                          {postSelectList}
                        </Select>
                      )
                    }
                  </FormItem>
                </Col>
                <Col span={12}>
                  <FormItem
                    label='用户等级：'
                    {...formItemLayout}
                    required
                    hasFeedback
                  >
                    {
                      getFieldDecorator('userLevel', {
                        initialValue: '',
                        rules: [{
                          required: true,
                          message: '请选择用户等级'
                        }]
                      })(
                        <Select placeholder='请选择用户等级'>
                          {userLevelList}
                        </Select>
                      )
                    }
                  </FormItem>
                </Col>
              </Row>
                <Col span={12}>
                  <FormItem
                    label='审批权限：'
                    {...formItemLayout}
                    required
                  >
                    {
                      getFieldDecorator('userRight', {
                        initialValue: '00000000',
                        rules: [{
                          message: ' '
                        }]
                      })(
                        <RadioGroup>
                          <Radio key='a' value='00000100'>有</Radio>
                          <Radio key='b' value='00000000'>无</Radio>
                        </RadioGroup>
                      )
                    }
                  </FormItem>
                </Col>
              <Row>
              </Row>
            </Form>
            <Spin loading={this.state.loading}/>
          </Modal>
      </div>
    )
  }
}

export default Form.create()(BranchAdd)<|endoftext|>


<commit_before>/*!
 * ${copyright}
 */

sap.ui.define(["./PluginBase", "sap/ui/core/Core", "sap/ui/base/ManagedObjectObserver"],
	function(PluginBase, Core, ManagedObjectObserver) {
	"use strict";

	/**
	 * Constructor for a new DataStateIndicator plugin.
	 *
	 * @param {string} [sId] ID for the new DataStateIndicator, generated automatically if no ID is given
	 * @param {object} [mSettings] Initial settings for the DataStateIndicator
	 *
	 * @class
	 * This plugin implements a message strip used to show binding-related messages.
	 *
	 * @extends sap.ui.core.Element
	 * @author SAP SE
	 * @version ${version}
	 *
	 * @public
	 * @since 1.73
	 * @alias sap.m.plugins.DataStateIndicator
	 * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
	 */
	var DataStateIndicator = PluginBase.extend("sap.m.plugins.DataStateIndicator", /** @lends sap.m.plugins.DataStateIndicator.prototype */ { metadata: {
		library: "sap.m",
		properties: {
			/**
			 * Defines a predicate to test each message of the data state.
			 *
			 * This callback gets called using the {@link sap.ui.core.message.Message message} and {@link sap.ui.core.Control related control} parameters.
			 * Returns true to keep the message, false otherwise.
			 */
			filter: {type: "function", invalidate: false},

			/**
			 * Defines the text for the link in the message strip.
			 * @since 1.79
			 */
			messageLinkText: {type: "string", visibility: "hidden"},

			/**
			 * Defines the visibility of the link control in the message strip.
			 * @since 1.79
			 */
			messageLinkVisible: {type: "boolean", defaultValue: true, visibility: "hidden"}
		},
		events: {
			/**
			 * This event is fired when the {@link sap.ui.model.DataState data state} of the plugin parent is changed.
			 */
			dataStateChange: {
				allowPreventDefault: true,
				parameters: {
					/**
					 * The data state object.
					 */
					dataState: {type: "sap.ui.model.DataState"}
				}
			}
		}
	}});

	/**
	 * Defines the text to be shown for the link control of the message strip.
	 * @param {string} [sLinkText] The text for the link control
	 * @returns {sap.m.plugins.DataStateIndicator} The control instance
	 * @since 1.79
	 * @private
	 */
	DataStateIndicator.prototype.setMessageLinkText = function(sLinkText) {
		this.setProperty("messageLinkText", sLinkText, true);
		// update the link aggregation of the message strip
		this._updateMessageLinkControl();
		return this;
	};

	/**
	 * Returns the message link text.
	 * @returns {string} message link text
	 * @since 1.79
	 * @private
	 */
	DataStateIndicator.prototype.getMessageLinkText = function() {
		return this.getProperty("messageLinkText");
	};

	/**
	 * Defines the visibility of the link control in the message strip.
	 * @param {boolean} [bVisible] Visibility of the link control
	 * @return {sap.m.plugins.DataStateIndicator} The control instance
	 * @since 1.79
	 * @private
	 */
	DataStateIndicator.prototype.setMessageLinkVisible = function(bVisible) {
		this.setProperty("messageLinkVisible", bVisible, true);

		if (this._oLink) {
			this._oLink.setVisible(bVisible);
		}

		return this;
	};

	/**
	 * Returns the property value of messageLinkVisible.
	 * @returns {boolean} The messageLinkVisible property value
	 * @since 1.79
	 * @private
	 */
	DataStateIndicator.prototype.getMessageLinkVisible = function() {
		return this.getProperty("messageLinkVisible");
	};

	DataStateIndicator.prototype.isApplicable = function(oControl) {
		if (!oControl.addAriaLabelledBy ||
			!PluginBase.prototype.isApplicable.apply(this, arguments) ||
			!oControl.getMetadata().getAllPrivateAggregations()["_messageStrip"] ||
			!this._getBindingName()) {
			return false;
		}

		return true;
	};

	DataStateIndicator.prototype.onActivate = function(oControl) {
		var sBindingName = this._getBindingName();
		var oBinding = oControl.getBinding(sBindingName);

		if (oBinding) {
			oBinding.attachAggregatedDataStateChange(this._onAggregatedDataStateChange, this);
			this._processDataState(oBinding.getDataState());
		}

		this._oObserver = new ManagedObjectObserver(this._observeChanges.bind(this));
		this._oObserver.observe(oControl, { bindings: [sBindingName] });
	};

	DataStateIndicator.prototype.onDeactivate = function(oControl) {
		var sBindingName = this._getBindingName();
		var oBinding = oControl.getBinding(sBindingName);

		if (oBinding) {
			oBinding.detachAggregatedDataStateChange(this._onAggregatedDataStateChange, this);
			oBinding.getDataState().getMessages().forEach(function(oMessage) {
				oMessage.removeControlId(oControl.getId());
			});
		}

		if (this._oMessageStrip) {
			this._oMessageStrip.destroy();
			this._oMessageStrip = null;
		}

		if (this._oLink) {
			this._oLink.destroy();
			this._oLink = null;
		}

		this._oObserver.unobserve(oControl, { bindings: [sBindingName] });
		this._oObserver.destroy();
		this._oObserver = null;
	};

	/**
	 * Shows a message.
	 *
	 * @param {string} [sText] The message text, if empty, the message is hidden
	 * @param {sap.ui.core.ValueState} [sType] The message type
	 * @public
	 */
	DataStateIndicator.prototype.showMessage = function(sText, sType) {
		if (!this.getEnabled() || !this.getControl() || (!sText && !this._oMessageStrip)) {
			return;
		}

		if (this._oMessageStrip) {
			this._oMessageStrip.setText(sText).setType(sType).setVisible(!!sText);
			return;
		}

		sap.ui.require(["sap/m/MessageStrip"], function(MessageStrip) {
			var oControl = this.getControl();
			this._oMessageStrip = new MessageStrip({
				showCloseButton: true,
				showIcon: true
			}).addStyleClass("sapUiTinyMargin");

			// update the link aggregation of the message strip
			this._updateMessageLinkControl();

			oControl.setAggregation("_messageStrip", this._oMessageStrip);
			oControl.addAriaLabelledBy(this._oMessageStrip);
			this.showMessage(sText, sType);
		}.bind(this));
	};

	/**
	 * Creates or updates the link control of the message strip.
	 * @since 1.79
	 * @private
	 */
	DataStateIndicator.prototype._updateMessageLinkControl = function() {
		if (!this._oMessageStrip) {
			return;
		}

		var sMessageLinkText = this.getMessageLinkText();
		if (!sMessageLinkText) {
			this._oMessageStrip.setLink(null);
			return;
		} else if (this._oLink) {
			this._oLink.setText(sMessageLinkText);
			this._oMessageStrip.setLink(this._oLink);
		}

		if (!this._oLink) {
			sap.ui.require(["sap/m/Link"], function(Link) {
				this._oLink = new Link({
					text: sMessageLinkText,
					visible: this.getMessageLinkVisible(),
					press: [function() {
						// private event fired when the link is pressed
						this.fireEvent("messageLinkPressed");
					}, this]
				});
				this._oMessageStrip.setLink(this._oLink);
			}.bind(this));
		}
	};

	/**
	 * Refreshes the messages displayed for the current data state.
	 *
	 * The current data state is evaluated again, and the filters are applied.
	 *
	 * @public
	 */
	DataStateIndicator.prototype.refresh = function() {
		if (this.isActive()) {
			var sBindingName = this._getBindingName();
			var oBinding = this.getControl().getBinding(sBindingName);
			if (oBinding) {
				this._processDataState(oBinding.getDataState());
			}
		}
	};

	DataStateIndicator.prototype._getBindingName = function() {
		return this.getControlPluginConfig("defaultBindingName");
	};

	DataStateIndicator.prototype._translate = function(sBundleKey) {
		var sBundleText = "DATASTATE_" + sBundleKey;
		var oMetadata = this.getControl().getMetadata();
		var sLibraryName = oMetadata.getLibraryName();
		var sControlName = oMetadata.getName().split(".").pop().toUpperCase();
		var oResourceBundle = Core.getLibraryResourceBundle(sLibraryName);
		var sControlBundleText = sControlName + "_" + sBundleText;

		if (oResourceBundle.hasText(sControlBundleText)){
			return oResourceBundle.getText(sControlBundleText);
		}

		if (sLibraryName == "sap.m") {
			return oResourceBundle.getText(sBundleText);
		}

		return Core.getLibraryResourceBundle("sap.m").getText(sBundleText);
	};

	DataStateIndicator.prototype._getCombinedType = function(aMessages) {
		if (aMessages && aMessages.length) {
			var mTypes = {None: 0, Information: 1, Success: 2, Warning: 4, Error: 8};
			var iSeverity = 0;

			aMessages.forEach(function(oMessage) {
				iSeverity |= mTypes[oMessage.getType()];
			});

			if (iSeverity & mTypes.Error && iSeverity & mTypes.Warning) {
				return "Issue";
			} else if (iSeverity & mTypes.Error) {
				return "Error";
			} else if (iSeverity & mTypes.Warning) {
				return "Warning";
			} else if (iSeverity & mTypes.Success || iSeverity & mTypes.Information) {
				return "Notification";
			}
		}

		return "";
	};

	DataStateIndicator.prototype._processDataState = function(oDataState) {
		if (!oDataState || !oDataState.getChanges().messages) {
			return;
		}

		var aMessages = oDataState.getMessages();
		var oControl = this.getControl();
		var fnFilter = this.getFilter();
		if (fnFilter) {
			aMessages = aMessages.filter(function(oMessage) {
				return fnFilter(oMessage, oControl);
			});
		}

		if (!this.fireDataStateChange({ dataState: oDataState, filteredMessages: aMessages})) {
			return;
		}

		if (aMessages.length) {
			var oFirstMessage = aMessages[0];
			var sBindingName = this._getBindingName();
			var sBindingPath = oControl.getBinding(sBindingName).getPath();
			var bUpdateMessageModel = false;
			var sBundleKey = "";
			var sMessage = "";

			aMessages.forEach(function(oMessage) {
				if (oMessage.getControlIds().indexOf(oControl.getId()) == -1) {
					oMessage.addControlId(oControl.getId());
					bUpdateMessageModel = true;
				}
			});

			if (aMessages.length == 1 && oFirstMessage.getTarget() && oFirstMessage.getTarget().endsWith(sBindingPath)) {
				sMessage = oFirstMessage.getMessage();
			} else {
				sBundleKey = this._getCombinedType(aMessages);

				if (sBundleKey) {
					sMessage = this._translate(sBundleKey.toUpperCase());
				}
			}

			this.showMessage(sMessage, oFirstMessage.getType());

			if (bUpdateMessageModel) {
				Core.getMessageManager().getMessageModel().checkUpdate(false, true);
			}
		} else {
			this.showMessage("");
		}
	};

	DataStateIndicator.prototype._onAggregatedDataStateChange = function(oEvent) {
		this._processDataState(oEvent.getParameter("dataState"));
	};

	DataStateIndicator.prototype._observeChanges = function(mChange) {
		var oBinding = mChange.bindingInfo.binding;
		if (oBinding) {
			var sOperation = (mChange.mutation == "ready") ? "attach" : "detach";
			oBinding[sOperation + "AggregatedDataStateChange"](this._onAggregatedDataStateChange, this);
		}
	};

	/**
	 * Plugin-specific control configurations
	 */
	PluginBase.setConfig({
		"sap.m.ListBase": {
			defaultBindingName: "items"
		},
		"sap.ui.table.Table": {
			defaultBindingName: "rows"
		}
	}, DataStateIndicator);

	return DataStateIndicator;

});
<commit_msg>[INTERNAL] DataStateIndicator: Missing event parameter docu added<commit_after>/*!
 * ${copyright}
 */

sap.ui.define(["./PluginBase", "sap/ui/core/Core", "sap/ui/base/ManagedObjectObserver"],
	function(PluginBase, Core, ManagedObjectObserver) {
	"use strict";

	/**
	 * Constructor for a new DataStateIndicator plugin.
	 *
	 * @param {string} [sId] ID for the new DataStateIndicator, generated automatically if no ID is given
	 * @param {object} [mSettings] Initial settings for the DataStateIndicator
	 *
	 * @class
	 * This plugin implements a message strip used to show binding-related messages.
	 *
	 * @extends sap.ui.core.Element
	 * @author SAP SE
	 * @version ${version}
	 *
	 * @public
	 * @since 1.73
	 * @alias sap.m.plugins.DataStateIndicator
	 * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
	 */
	var DataStateIndicator = PluginBase.extend("sap.m.plugins.DataStateIndicator", /** @lends sap.m.plugins.DataStateIndicator.prototype */ { metadata: {
		library: "sap.m",
		properties: {
			/**
			 * Defines a predicate to test each message of the data state.
			 *
			 * This callback gets called using the {@link sap.ui.core.message.Message message} and {@link sap.ui.core.Control related control} parameters.
			 * Returns true to keep the message, false otherwise.
			 */
			filter: {type: "function", invalidate: false},

			/**
			 * Defines the text for the link in the message strip.
			 * @since 1.79
			 */
			messageLinkText: {type: "string", visibility: "hidden"},

			/**
			 * Defines the visibility of the link control in the message strip.
			 * @since 1.79
			 */
			messageLinkVisible: {type: "boolean", defaultValue: true, visibility: "hidden"}
		},
		events: {
			/**
			 * This event is fired when the {@link sap.ui.model.DataState data state} of the plugin parent is changed.
			 */
			dataStateChange: {
				allowPreventDefault: true,
				parameters: {
					/**
					 * The data state object.
					 */
					dataState: {type: "sap.ui.model.DataState"},
					/**
					 * The messages (@see sap.ui.core.message.Message) from the current dataState object filtered by the given filter function.
					 */
					filteredMessages: {type: "any[]"}
				}
			}
		}
	}});

	/**
	 * Defines the text to be shown for the link control of the message strip.
	 * @param {string} [sLinkText] The text for the link control
	 * @returns {sap.m.plugins.DataStateIndicator} The control instance
	 * @since 1.79
	 * @private
	 */
	DataStateIndicator.prototype.setMessageLinkText = function(sLinkText) {
		this.setProperty("messageLinkText", sLinkText, true);
		// update the link aggregation of the message strip
		this._updateMessageLinkControl();
		return this;
	};

	/**
	 * Returns the message link text.
	 * @returns {string} message link text
	 * @since 1.79
	 * @private
	 */
	DataStateIndicator.prototype.getMessageLinkText = function() {
		return this.getProperty("messageLinkText");
	};

	/**
	 * Defines the visibility of the link control in the message strip.
	 * @param {boolean} [bVisible] Visibility of the link control
	 * @return {sap.m.plugins.DataStateIndicator} The control instance
	 * @since 1.79
	 * @private
	 */
	DataStateIndicator.prototype.setMessageLinkVisible = function(bVisible) {
		this.setProperty("messageLinkVisible", bVisible, true);

		if (this._oLink) {
			this._oLink.setVisible(bVisible);
		}

		return this;
	};

	/**
	 * Returns the property value of messageLinkVisible.
	 * @returns {boolean} The messageLinkVisible property value
	 * @since 1.79
	 * @private
	 */
	DataStateIndicator.prototype.getMessageLinkVisible = function() {
		return this.getProperty("messageLinkVisible");
	};

	DataStateIndicator.prototype.isApplicable = function(oControl) {
		if (!oControl.addAriaLabelledBy ||
			!PluginBase.prototype.isApplicable.apply(this, arguments) ||
			!oControl.getMetadata().getAllPrivateAggregations()["_messageStrip"] ||
			!this._getBindingName()) {
			return false;
		}

		return true;
	};

	DataStateIndicator.prototype.onActivate = function(oControl) {
		var sBindingName = this._getBindingName();
		var oBinding = oControl.getBinding(sBindingName);

		if (oBinding) {
			oBinding.attachAggregatedDataStateChange(this._onAggregatedDataStateChange, this);
			this._processDataState(oBinding.getDataState());
		}

		this._oObserver = new ManagedObjectObserver(this._observeChanges.bind(this));
		this._oObserver.observe(oControl, { bindings: [sBindingName] });
	};

	DataStateIndicator.prototype.onDeactivate = function(oControl) {
		var sBindingName = this._getBindingName();
		var oBinding = oControl.getBinding(sBindingName);

		if (oBinding) {
			oBinding.detachAggregatedDataStateChange(this._onAggregatedDataStateChange, this);
			oBinding.getDataState().getMessages().forEach(function(oMessage) {
				oMessage.removeControlId(oControl.getId());
			});
		}

		if (this._oMessageStrip) {
			this._oMessageStrip.destroy();
			this._oMessageStrip = null;
		}

		if (this._oLink) {
			this._oLink.destroy();
			this._oLink = null;
		}

		this._oObserver.unobserve(oControl, { bindings: [sBindingName] });
		this._oObserver.destroy();
		this._oObserver = null;
	};

	/**
	 * Shows a message.
	 *
	 * @param {string} [sText] The message text, if empty, the message is hidden
	 * @param {sap.ui.core.ValueState} [sType] The message type
	 * @public
	 */
	DataStateIndicator.prototype.showMessage = function(sText, sType) {
		if (!this.getEnabled() || !this.getControl() || (!sText && !this._oMessageStrip)) {
			return;
		}

		if (this._oMessageStrip) {
			this._oMessageStrip.setText(sText).setType(sType).setVisible(!!sText);
			return;
		}

		sap.ui.require(["sap/m/MessageStrip"], function(MessageStrip) {
			var oControl = this.getControl();
			this._oMessageStrip = new MessageStrip({
				showCloseButton: true,
				showIcon: true
			}).addStyleClass("sapUiTinyMargin");

			// update the link aggregation of the message strip
			this._updateMessageLinkControl();

			oControl.setAggregation("_messageStrip", this._oMessageStrip);
			oControl.addAriaLabelledBy(this._oMessageStrip);
			this.showMessage(sText, sType);
		}.bind(this));
	};

	/**
	 * Creates or updates the link control of the message strip.
	 * @since 1.79
	 * @private
	 */
	DataStateIndicator.prototype._updateMessageLinkControl = function() {
		if (!this._oMessageStrip) {
			return;
		}

		var sMessageLinkText = this.getMessageLinkText();
		if (!sMessageLinkText) {
			this._oMessageStrip.setLink(null);
			return;
		} else if (this._oLink) {
			this._oLink.setText(sMessageLinkText);
			this._oMessageStrip.setLink(this._oLink);
		}

		if (!this._oLink) {
			sap.ui.require(["sap/m/Link"], function(Link) {
				this._oLink = new Link({
					text: sMessageLinkText,
					visible: this.getMessageLinkVisible(),
					press: [function() {
						// private event fired when the link is pressed
						this.fireEvent("messageLinkPressed");
					}, this]
				});
				this._oMessageStrip.setLink(this._oLink);
			}.bind(this));
		}
	};

	/**
	 * Refreshes the messages displayed for the current data state.
	 *
	 * The current data state is evaluated again, and the filters are applied.
	 *
	 * @public
	 */
	DataStateIndicator.prototype.refresh = function() {
		if (this.isActive()) {
			var sBindingName = this._getBindingName();
			var oBinding = this.getControl().getBinding(sBindingName);
			if (oBinding) {
				this._processDataState(oBinding.getDataState());
			}
		}
	};

	DataStateIndicator.prototype._getBindingName = function() {
		return this.getControlPluginConfig("defaultBindingName");
	};

	DataStateIndicator.prototype._translate = function(sBundleKey) {
		var sBundleText = "DATASTATE_" + sBundleKey;
		var oMetadata = this.getControl().getMetadata();
		var sLibraryName = oMetadata.getLibraryName();
		var sControlName = oMetadata.getName().split(".").pop().toUpperCase();
		var oResourceBundle = Core.getLibraryResourceBundle(sLibraryName);
		var sControlBundleText = sControlName + "_" + sBundleText;

		if (oResourceBundle.hasText(sControlBundleText)){
			return oResourceBundle.getText(sControlBundleText);
		}

		if (sLibraryName == "sap.m") {
			return oResourceBundle.getText(sBundleText);
		}

		return Core.getLibraryResourceBundle("sap.m").getText(sBundleText);
	};

	DataStateIndicator.prototype._getCombinedType = function(aMessages) {
		if (aMessages && aMessages.length) {
			var mTypes = {None: 0, Information: 1, Success: 2, Warning: 4, Error: 8};
			var iSeverity = 0;

			aMessages.forEach(function(oMessage) {
				iSeverity |= mTypes[oMessage.getType()];
			});

			if (iSeverity & mTypes.Error && iSeverity & mTypes.Warning) {
				return "Issue";
			} else if (iSeverity & mTypes.Error) {
				return "Error";
			} else if (iSeverity & mTypes.Warning) {
				return "Warning";
			} else if (iSeverity & mTypes.Success || iSeverity & mTypes.Information) {
				return "Notification";
			}
		}

		return "";
	};

	DataStateIndicator.prototype._processDataState = function(oDataState) {
		if (!oDataState || !oDataState.getChanges().messages) {
			return;
		}

		var aMessages = oDataState.getMessages();
		var oControl = this.getControl();
		var fnFilter = this.getFilter();
		if (fnFilter) {
			aMessages = aMessages.filter(function(oMessage) {
				return fnFilter(oMessage, oControl);
			});
		}

		if (!this.fireDataStateChange({ dataState: oDataState, filteredMessages: aMessages})) {
			return;
		}

		if (aMessages.length) {
			var oFirstMessage = aMessages[0];
			var sBindingName = this._getBindingName();
			var sBindingPath = oControl.getBinding(sBindingName).getPath();
			var bUpdateMessageModel = false;
			var sBundleKey = "";
			var sMessage = "";

			aMessages.forEach(function(oMessage) {
				if (oMessage.getControlIds().indexOf(oControl.getId()) == -1) {
					oMessage.addControlId(oControl.getId());
					bUpdateMessageModel = true;
				}
			});

			if (aMessages.length == 1 && oFirstMessage.getTarget() && oFirstMessage.getTarget().endsWith(sBindingPath)) {
				sMessage = oFirstMessage.getMessage();
			} else {
				sBundleKey = this._getCombinedType(aMessages);

				if (sBundleKey) {
					sMessage = this._translate(sBundleKey.toUpperCase());
				}
			}

			this.showMessage(sMessage, oFirstMessage.getType());

			if (bUpdateMessageModel) {
				Core.getMessageManager().getMessageModel().checkUpdate(false, true);
			}
		} else {
			this.showMessage("");
		}
	};

	DataStateIndicator.prototype._onAggregatedDataStateChange = function(oEvent) {
		this._processDataState(oEvent.getParameter("dataState"));
	};

	DataStateIndicator.prototype._observeChanges = function(mChange) {
		var oBinding = mChange.bindingInfo.binding;
		if (oBinding) {
			var sOperation = (mChange.mutation == "ready") ? "attach" : "detach";
			oBinding[sOperation + "AggregatedDataStateChange"](this._onAggregatedDataStateChange, this);
		}
	};

	/**
	 * Plugin-specific control configurations
	 */
	PluginBase.setConfig({
		"sap.m.ListBase": {
			defaultBindingName: "items"
		},
		"sap.ui.table.Table": {
			defaultBindingName: "rows"
		}
	}, DataStateIndicator);

	return DataStateIndicator;

});
<|endoftext|>


<commit_before>/*!
 * ${copyright}
 */
sap.ui.define([
	"./PropertyHelper",
    "sap/m/Button",
    "sap/m/Bar",
    "sap/m/Title",
    "sap/base/util/merge",
    "sap/m/MessageBox",
    "sap/ui/Device",
    "sap/ui/fl/write/api/FieldExtensibility"
], function(P13nPropertyHelper, Button, Bar, Title, merge, MessageBox, Device, FieldExtensibility) {
    "use strict";

    var oRB = sap.ui.getCore().getLibraryResourceBundle("sap.ui.mdc");

	/**
	 *  Internal Utility class to create personalization UI's
	 *
	 * @author SAP SE
	 * @private
	 * @since 1.81.0
	 * @alias sap.ui.mdc.p13n.P13nBuilder
	 */
	var P13nBuilder = {

        /**
         *
         * @param {object} oP13nUI Control displayed in the content area
         * @param {object} mDialogSettings Settings to overwrite popover default properties, such as: contentHeight
         * @param {object} [mDialogSettings.reset] Reset settings for the custom header creation
         * @param {function} [mDialogSettings.reset.onExecute] Callback executed upon triggering a reset
         * @param {string} [mDialogSettings.reset.warningText] Warning which is displyed prior to executing the reset
         *
         * @returns {Promise} promise resolving in the Popover instance
         */
        createP13nPopover: function(oP13nUI, mDialogSettings) {

            return new Promise(function(resolve, reject){

                sap.ui.require(["sap/m/ResponsivePopover"], function(ResponsivePopover){
                    P13nBuilder["_checkSettings"](oP13nUI, mDialogSettings, reject);

                    var oPopover = new ResponsivePopover({
                        title: mDialogSettings.title,
                        horizontalScrolling: mDialogSettings.hasOwnProperty("horizontalScrolling") ? mDialogSettings.horizontalScrolling : false,
                        verticalScrolling: mDialogSettings.hasOwnProperty("verticalScrolling") ? mDialogSettings.verticalScrolling : false,
                        contentWidth: mDialogSettings.contentWidth ? mDialogSettings.contentWidth : "24rem",
                        resizable: mDialogSettings.hasOwnProperty("resizable") ? mDialogSettings.resizable : true,
                        contentHeight: mDialogSettings.contentHeight ? mDialogSettings.contentHeight : "35rem",
                        placement: mDialogSettings.placement ? mDialogSettings.placement : "Bottom",
                        content: oP13nUI,
                        afterClose: mDialogSettings.afterClose ? mDialogSettings.afterClose : function(){}
                    });

                    if (mDialogSettings.reset) {
                        var oCustomHeader = P13nBuilder._createResetHeader({
                            title: mDialogSettings.title,
                            reset: mDialogSettings.reset.onExecute,
                            idResetButton: mDialogSettings.reset.idButton,
                            warningText: mDialogSettings.reset.warningText
                        });
                        oPopover.setCustomHeader(oCustomHeader);
                    }

                    resolve(oPopover);
                },reject);
            });

        },

        /**
         *
         * @param {object} oP13nUI Control displayed in the content area
         * @param {object} mDialogSettings Settings to overwrite dialog default properties, such as: contentHeight
         * @param {object} [mDialogSettings.reset] Reset settings for the custom header creation
         * @param {function} [mDialogSettings.reset.onExecute] Callback executed upon triggering a reset
         * @param {string} [mDialogSettings.reset.warningText] Warning which is displyed prior to executing the reset
         *
         * @returns {Promise} Promise resolving in the Dialog instance
         */
        createP13nDialog: function(oP13nUI, mDialogSettings) {

            return new Promise(function(resolve, reject){

                P13nBuilder["_checkSettings"](oP13nUI, mDialogSettings, reject);

                var sId = mDialogSettings.id;

                sap.ui.require(["sap/m/Dialog", "sap/m/Button"], function(Dialog, Button){
                    var oResourceBundle = sap.ui.getCore().getLibraryResourceBundle("sap.ui.mdc");
                    var oContainer = new Dialog(sId, {
                        title: mDialogSettings.title,
                        horizontalScrolling: mDialogSettings.hasOwnProperty("horizontalScrolling") ? mDialogSettings.horizontalScrolling : false,
                        verticalScrolling: mDialogSettings.hasOwnProperty("verticalScrolling") ? mDialogSettings.verticalScrolling : true,
                        contentWidth: mDialogSettings.contentWidth ? mDialogSettings.contentWidth : "40rem",
                        contentHeight: mDialogSettings.contentHeight ? mDialogSettings.contentHeight : "55rem",
                        draggable: true,
                        resizable: true,
                        stretch: Device.system.phone,
                        content: oP13nUI,
                        afterClose: mDialogSettings.afterClose ? mDialogSettings.afterClose : function(){},
                        buttons: [
                            new Button(sId ? sId + "-confirmBtn" : undefined, {
                                text:  mDialogSettings.confirm && mDialogSettings.confirm.text ?  mDialogSettings.confirm.text : oResourceBundle.getText("p13nDialog.OK"),
                                type: "Emphasized",
                                press: function() {
                                    if (mDialogSettings.confirm && mDialogSettings.confirm.handler) {
                                        mDialogSettings.confirm.handler.apply(oContainer, arguments);
                                    }
                                }

                            }), new Button(sId ? sId + "-cancelBtn" : undefined, {
                                text: oResourceBundle.getText("p13nDialog.CANCEL"),
                                press: function () {
                                    mDialogSettings.cancel.apply(oContainer, arguments);
                                }
                            })
                        ]
                    });

                    if (mDialogSettings.reset) {
                        var oCustomHeader = P13nBuilder._createResetHeader({
                            title: mDialogSettings.title,
                            idResetButton: mDialogSettings.reset.idButton,
                            reset: mDialogSettings.reset.onExecute,
                            warningText: mDialogSettings.reset.warningText
                        });
                        oContainer.setCustomHeader(oCustomHeader);
                    }

                    var aAdditionalButtons = mDialogSettings.additionalButtons;
                    if (aAdditionalButtons instanceof Array) {
                        aAdditionalButtons.forEach(function(oButton){
                            if (!oButton.isA("sap.m.Button")) {
                                reject("Please only provide sap.m.Button instances as 'additionalButtons'");
                            }
                            oContainer.addButton(oButton);
                        });
                    }
                    resolve(oContainer);
                }, reject);
            });

        },

        /**
         *
         * @param {object} mSettings Settings object to create a customHeader including a reset Button
         * @param {string} mSettings.title Title for the custom reset header
         * @param {function} mSettings.reset Control specific reset handling
         * @param {string} [mSettings.warningText] Text which is displayed prior to executing to reset execution
         *
         * @returns {sap.m.Bar} The created custom header Bar
         */
        _createResetHeader: function(mSettings) {

            var oBar = new Bar({
                contentLeft: [
                    new Title({
                        text: mSettings.title
                    })
                ]
            });

            if (mSettings.reset) {
                var sId = mSettings.idResetButton;
                oBar.addContentRight(new Button( sId, {
                    text: sap.ui.getCore().getLibraryResourceBundle("sap.ui.mdc").getText("p13nDialog.RESET"),
                    press: function(oEvt) {

                        var oDialog =  oEvt.getSource().getParent().getParent();
                        var oControl = oDialog.getParent();

                        var sResetText = mSettings.warningText ? mSettings.warningText : sap.ui.getCore().getLibraryResourceBundle("sap.ui.mdc").getText("filterbar.ADAPT_RESET_WARNING");
                        MessageBox.warning(sResetText, {
                            actions: [MessageBox.Action.OK, MessageBox.Action.CANCEL],
                            emphasizedAction: MessageBox.Action.OK,
                            onClose: function (sAction) {
                                if (sAction === MessageBox.Action.OK) {
                                    // --> focus "OK" button after 'reset' has been triggered
                                    oDialog.getButtons()[0].focus();
                                    mSettings.reset(oControl);
                                }
                            }
                        });
                    }
                }));
            }

            return oBar;
        },

        prepareAdaptationData: function(vProperties, fnEnhace, bGroupData) {

			var oPropertyHelper =
                vProperties && vProperties.getProperties instanceof Function ?
				vProperties : new P13nPropertyHelper(vProperties);

            var aItems = [];
            var mItemsGrouped = bGroupData ? {} : null;

            var bEnhance = fnEnhace instanceof Function;

			oPropertyHelper.getProperties().forEach(function(oProperty) {

                var mItem = {};
                mItem.name = oProperty.name;

                if (bEnhance) {
                    var bIsValid = fnEnhace(mItem, oProperty);
                    if (!bIsValid) {
                        return;
                    }
                }

                mItem.label = oProperty.label || oProperty.name;
                mItem.tooltip = oProperty.tooltip;

                if (mItemsGrouped) {
                    mItem.group = oProperty.group ? oProperty.group : "BASIC";
                    mItem.groupLabel = oProperty.groupLabel;
                    mItemsGrouped[mItem.group] = mItemsGrouped[mItem.group] ? mItemsGrouped[mItem.group] : [];
                    mItemsGrouped[mItem.group].push(mItem);
                }

                aItems.push(mItem);

            });

            var oAdaptationData = {
                items: aItems
            };

            if (mItemsGrouped) {
                oAdaptationData.itemsGrouped = this._buildGroupStructure(mItemsGrouped);
            }

            return oAdaptationData;

        },

        //TODO: generify
        sortP13nData: function (oSorting, aItems) {

            var mP13nTypeSorting = oSorting;

            var sPositionAttribute = mP13nTypeSorting.position;
            var sSelectedAttribute = mP13nTypeSorting.visible;

            var sLocale = sap.ui.getCore().getConfiguration().getLocale().toString();

            var oCollator = window.Intl.Collator(sLocale, {});

            // group selected / unselected --> sort alphabetically in each group
            aItems.sort(function (mField1, mField2) {
                if (mField1[sSelectedAttribute] && mField2[sSelectedAttribute]) {
                    return (mField1[sPositionAttribute] || 0) - (mField2[sPositionAttribute] || 0);
                } else if (mField1[sSelectedAttribute]) {
                    return -1;
                } else if (mField2[sSelectedAttribute]) {
                    return 1;
                } else if (!mField1[sSelectedAttribute] && !mField2[sSelectedAttribute]) {
                    return oCollator.compare(mField1.label, mField2.label);
                }
            });

        },

        _buildGroupStructure: function(mItemsGrouped) {
            var aGroupedItems = [];
            Object.keys(mItemsGrouped).forEach(function(sGroupKey){
                this.sortP13nData("generic", mItemsGrouped[sGroupKey]);
                aGroupedItems.push({
                    group: sGroupKey,
                    groupLabel: mItemsGrouped[sGroupKey][0].groupLabel || oRB.getText("p13nDialog.FILTER_DEFAULT_GROUP"),//Grouplabel might not be necessarily be propagated to every item
                    groupVisible: true,
                    items: mItemsGrouped[sGroupKey]
                });
            }.bind(this));
            return aGroupedItems;

        },

        _isExcludeProperty: function(oProperty, aIgnoreAttributes){

            return aIgnoreAttributes.some(function(oKeyValuePair){
                var sIgnoreKey = oKeyValuePair.ignoreKey;
                var vIgnoreValue = oKeyValuePair.ignoreValue;
                return oProperty[sIgnoreKey] === vIgnoreValue;
            });

        },

        _checkSettings: function(oP13nUI, mDialogSettings, fnOnError) {
            if (!mDialogSettings) {
                fnOnError("Please provide a settings object for p13n creation");
            }

            if (!mDialogSettings.title && !mDialogSettings.customHeader) {
                fnOnError("Please provide a title or customHeader in the settings object for p13n creation");
            }
        },

        arrayToMap: function(aArray) {
            return aArray.reduce(function(mMap, oProp, iIndex){
                mMap[oProp.name] = oProp;
                mMap[oProp.name].position = iIndex;
                return mMap;
            }, {});
        },

        /**
         *
         * @param {object} oDialog AdaptFiltersDialog
         *
         * @returns {Promise} Promise resolving in the Dialog instance
         */
        addRTACustomFieldButton: function (oDialog) {

            var bExtensibilityEnabled = false,
                oDialogParent = oDialog.getParent();

            return sap.ui.getCore().loadLibrary('sap.ui.rta', {
                async: true
            }).then(function() {
                return new Promise(function(resolve) {
                    sap.ui.require([
                        "sap/ui/rta/Utils"
                    ], function(rtaUtils) {
                        var oHandleExtensibility = Promise.all([
                            rtaUtils.isServiceUpToDate(oDialogParent),
                            FieldExtensibility.isExtensibilityEnabled(oDialogParent)
                        ]);

                        return oHandleExtensibility.then(function (aResult) {
                            bExtensibilityEnabled = !!aResult[1];
                        })
                            .then(function() {
                                var oCustomHeader = oDialog.getCustomHeader(),
                                    sId = oDialogParent && oDialogParent.getId ? oDialogParent.getId() : undefined,
                                    oResourceBundle = sap.ui.getCore().getLibraryResourceBundle("sap.ui.mdc");

                                if (!oCustomHeader) {
                                    var oBar = new Bar({
                                        contentLeft: [
                                            new Title({
                                                text: oDialog.getTitle()
                                            })
                                        ]
                                    });
                                    oDialog.setCustomHeader(oBar);
                                    oCustomHeader = oDialog.getCustomHeader();
                                }

                                if (bExtensibilityEnabled) {
                                    oCustomHeader.addContentRight(new Button( sId + "-addCustomField", {
                                        icon: "sap-icon://add",
                                        enabled: bExtensibilityEnabled,
                                        tooltip: oResourceBundle.getText("p13nDialog.rtaAddTooltip"),
                                        press: function (oEvt) {
                                            var sRtaStyleClassName = rtaUtils.getRtaStyleClassName(),
                                                oAdaptDialog =  oEvt.getSource().getParent().getParent(),
                                                oControl = oAdaptDialog.getParent();

                                            FieldExtensibility.onControlSelected(oControl).then(function (oRetVal) {
                                                FieldExtensibility.getExtensionData().then(function (oExtensibilityInfo) {
                                                    FieldExtensibility.onTriggerCreateExtensionData(oExtensibilityInfo, sRtaStyleClassName);
                                                    oAdaptDialog.close(); // close as if there is newly created custom field, next time user tries to open it - it checks for service outdated and shows correct information
                                                });
                                            });

                                        }
                                    }));

                                    oDialog.setCustomHeader(oCustomHeader);
                                    resolve(oDialog);
                                }

                            });

                    });
                });
            });
        }

    };

	return P13nBuilder;
});
<commit_msg>[FEATURE] SmartTable - add custom-field button during UI adaptation at run time is now available<commit_after>/*!
 * ${copyright}
 */
sap.ui.define([
	"./PropertyHelper",
    "sap/m/Button",
    "sap/m/Bar",
    "sap/m/Title",
    "sap/base/util/merge",
    "sap/m/MessageBox",
    "sap/ui/Device",
    "sap/ui/fl/write/api/FieldExtensibility"
], function(P13nPropertyHelper, Button, Bar, Title, merge, MessageBox, Device, FieldExtensibility) {
    "use strict";

    var oRB = sap.ui.getCore().getLibraryResourceBundle("sap.ui.mdc");

	/**
	 *  Internal Utility class to create personalization UI's
	 *
	 * @author SAP SE
	 * @private
	 * @since 1.81.0
	 * @alias sap.ui.mdc.p13n.P13nBuilder
	 */
	var P13nBuilder = {

        /**
         *
         * @param {object} oP13nUI Control displayed in the content area
         * @param {object} mDialogSettings Settings to overwrite popover default properties, such as: contentHeight
         * @param {object} [mDialogSettings.reset] Reset settings for the custom header creation
         * @param {function} [mDialogSettings.reset.onExecute] Callback executed upon triggering a reset
         * @param {string} [mDialogSettings.reset.warningText] Warning which is displyed prior to executing the reset
         *
         * @returns {Promise} promise resolving in the Popover instance
         */
        createP13nPopover: function(oP13nUI, mDialogSettings) {

            return new Promise(function(resolve, reject){

                sap.ui.require(["sap/m/ResponsivePopover"], function(ResponsivePopover){
                    P13nBuilder["_checkSettings"](oP13nUI, mDialogSettings, reject);

                    var oPopover = new ResponsivePopover({
                        title: mDialogSettings.title,
                        horizontalScrolling: mDialogSettings.hasOwnProperty("horizontalScrolling") ? mDialogSettings.horizontalScrolling : false,
                        verticalScrolling: mDialogSettings.hasOwnProperty("verticalScrolling") ? mDialogSettings.verticalScrolling : false,
                        contentWidth: mDialogSettings.contentWidth ? mDialogSettings.contentWidth : "24rem",
                        resizable: mDialogSettings.hasOwnProperty("resizable") ? mDialogSettings.resizable : true,
                        contentHeight: mDialogSettings.contentHeight ? mDialogSettings.contentHeight : "35rem",
                        placement: mDialogSettings.placement ? mDialogSettings.placement : "Bottom",
                        content: oP13nUI,
                        afterClose: mDialogSettings.afterClose ? mDialogSettings.afterClose : function(){}
                    });

                    if (mDialogSettings.reset) {
                        var oCustomHeader = P13nBuilder._createResetHeader({
                            title: mDialogSettings.title,
                            reset: mDialogSettings.reset.onExecute,
                            idResetButton: mDialogSettings.reset.idButton,
                            warningText: mDialogSettings.reset.warningText
                        });
                        oPopover.setCustomHeader(oCustomHeader);
                    }

                    resolve(oPopover);
                },reject);
            });

        },

        /**
         *
         * @param {object} oP13nUI Control displayed in the content area
         * @param {object} mDialogSettings Settings to overwrite dialog default properties, such as: contentHeight
         * @param {object} [mDialogSettings.reset] Reset settings for the custom header creation
         * @param {function} [mDialogSettings.reset.onExecute] Callback executed upon triggering a reset
         * @param {string} [mDialogSettings.reset.warningText] Warning which is displyed prior to executing the reset
         *
         * @returns {Promise} Promise resolving in the Dialog instance
         */
        createP13nDialog: function(oP13nUI, mDialogSettings) {

            return new Promise(function(resolve, reject){

                P13nBuilder["_checkSettings"](oP13nUI, mDialogSettings, reject);

                var sId = mDialogSettings.id;

                sap.ui.require(["sap/m/Dialog", "sap/m/Button"], function(Dialog, Button){
                    var oResourceBundle = sap.ui.getCore().getLibraryResourceBundle("sap.ui.mdc");
                    var oContainer = new Dialog(sId, {
                        title: mDialogSettings.title,
                        horizontalScrolling: mDialogSettings.hasOwnProperty("horizontalScrolling") ? mDialogSettings.horizontalScrolling : false,
                        verticalScrolling: mDialogSettings.hasOwnProperty("verticalScrolling") ? mDialogSettings.verticalScrolling : true,
                        contentWidth: mDialogSettings.contentWidth ? mDialogSettings.contentWidth : "40rem",
                        contentHeight: mDialogSettings.contentHeight ? mDialogSettings.contentHeight : "55rem",
                        draggable: true,
                        resizable: true,
                        stretch: Device.system.phone,
                        content: oP13nUI,
                        afterClose: mDialogSettings.afterClose ? mDialogSettings.afterClose : function(){},
                        buttons: [
                            new Button(sId ? sId + "-confirmBtn" : undefined, {
                                text:  mDialogSettings.confirm && mDialogSettings.confirm.text ?  mDialogSettings.confirm.text : oResourceBundle.getText("p13nDialog.OK"),
                                type: "Emphasized",
                                press: function() {
                                    if (mDialogSettings.confirm && mDialogSettings.confirm.handler) {
                                        mDialogSettings.confirm.handler.apply(oContainer, arguments);
                                    }
                                }

                            }), new Button(sId ? sId + "-cancelBtn" : undefined, {
                                text: oResourceBundle.getText("p13nDialog.CANCEL"),
                                press: function () {
                                    mDialogSettings.cancel.apply(oContainer, arguments);
                                }
                            })
                        ]
                    });

                    if (mDialogSettings.reset) {
                        var oCustomHeader = P13nBuilder._createResetHeader({
                            title: mDialogSettings.title,
                            idResetButton: mDialogSettings.reset.idButton,
                            reset: mDialogSettings.reset.onExecute,
                            warningText: mDialogSettings.reset.warningText
                        });
                        oContainer.setCustomHeader(oCustomHeader);
                    }

                    var aAdditionalButtons = mDialogSettings.additionalButtons;
                    if (aAdditionalButtons instanceof Array) {
                        aAdditionalButtons.forEach(function(oButton){
                            if (!oButton.isA("sap.m.Button")) {
                                reject("Please only provide sap.m.Button instances as 'additionalButtons'");
                            }
                            oContainer.addButton(oButton);
                        });
                    }
                    resolve(oContainer);
                }, reject);
            });

        },

        /**
         *
         * @param {object} mSettings Settings object to create a customHeader including a reset Button
         * @param {string} mSettings.title Title for the custom reset header
         * @param {function} mSettings.reset Control specific reset handling
         * @param {string} [mSettings.warningText] Text which is displayed prior to executing to reset execution
         *
         * @returns {sap.m.Bar} The created custom header Bar
         */
        _createResetHeader: function(mSettings) {

            var oBar = new Bar({
                contentLeft: [
                    new Title({
                        text: mSettings.title
                    })
                ]
            });

            if (mSettings.reset) {
                var sId = mSettings.idResetButton;
                oBar.addContentRight(new Button( sId, {
                    text: sap.ui.getCore().getLibraryResourceBundle("sap.ui.mdc").getText("p13nDialog.RESET"),
                    press: function(oEvt) {

                        var oDialog =  oEvt.getSource().getParent().getParent();
                        var oControl = oDialog.getParent();

                        var sResetText = mSettings.warningText ? mSettings.warningText : sap.ui.getCore().getLibraryResourceBundle("sap.ui.mdc").getText("filterbar.ADAPT_RESET_WARNING");
                        MessageBox.warning(sResetText, {
                            actions: [MessageBox.Action.OK, MessageBox.Action.CANCEL],
                            emphasizedAction: MessageBox.Action.OK,
                            onClose: function (sAction) {
                                if (sAction === MessageBox.Action.OK) {
                                    // --> focus "OK" button after 'reset' has been triggered
                                    oDialog.getButtons()[0].focus();
                                    mSettings.reset(oControl);
                                }
                            }
                        });
                    }
                }));
            }

            return oBar;
        },

        prepareAdaptationData: function(vProperties, fnEnhace, bGroupData) {

			var oPropertyHelper =
                vProperties && vProperties.getProperties instanceof Function ?
				vProperties : new P13nPropertyHelper(vProperties);

            var aItems = [];
            var mItemsGrouped = bGroupData ? {} : null;

            var bEnhance = fnEnhace instanceof Function;

			oPropertyHelper.getProperties().forEach(function(oProperty) {

                var mItem = {};
                mItem.name = oProperty.name;

                if (bEnhance) {
                    var bIsValid = fnEnhace(mItem, oProperty);
                    if (!bIsValid) {
                        return;
                    }
                }

                mItem.label = oProperty.label || oProperty.name;
                mItem.tooltip = oProperty.tooltip;

                if (mItemsGrouped) {
                    mItem.group = oProperty.group ? oProperty.group : "BASIC";
                    mItem.groupLabel = oProperty.groupLabel;
                    mItemsGrouped[mItem.group] = mItemsGrouped[mItem.group] ? mItemsGrouped[mItem.group] : [];
                    mItemsGrouped[mItem.group].push(mItem);
                }

                aItems.push(mItem);

            });

            var oAdaptationData = {
                items: aItems
            };

            if (mItemsGrouped) {
                oAdaptationData.itemsGrouped = this._buildGroupStructure(mItemsGrouped);
            }

            return oAdaptationData;

        },

        //TODO: generify
        sortP13nData: function (oSorting, aItems) {

            var mP13nTypeSorting = oSorting;

            var sPositionAttribute = mP13nTypeSorting.position;
            var sSelectedAttribute = mP13nTypeSorting.visible;

            var sLocale = sap.ui.getCore().getConfiguration().getLocale().toString();

            var oCollator = window.Intl.Collator(sLocale, {});

            // group selected / unselected --> sort alphabetically in each group
            aItems.sort(function (mField1, mField2) {
                if (mField1[sSelectedAttribute] && mField2[sSelectedAttribute]) {
                    return (mField1[sPositionAttribute] || 0) - (mField2[sPositionAttribute] || 0);
                } else if (mField1[sSelectedAttribute]) {
                    return -1;
                } else if (mField2[sSelectedAttribute]) {
                    return 1;
                } else if (!mField1[sSelectedAttribute] && !mField2[sSelectedAttribute]) {
                    return oCollator.compare(mField1.label, mField2.label);
                }
            });

        },

        _buildGroupStructure: function(mItemsGrouped) {
            var aGroupedItems = [];
            Object.keys(mItemsGrouped).forEach(function(sGroupKey){
                this.sortP13nData("generic", mItemsGrouped[sGroupKey]);
                aGroupedItems.push({
                    group: sGroupKey,
                    groupLabel: mItemsGrouped[sGroupKey][0].groupLabel || oRB.getText("p13nDialog.FILTER_DEFAULT_GROUP"),//Grouplabel might not be necessarily be propagated to every item
                    groupVisible: true,
                    items: mItemsGrouped[sGroupKey]
                });
            }.bind(this));
            return aGroupedItems;

        },

        _isExcludeProperty: function(oProperty, aIgnoreAttributes){

            return aIgnoreAttributes.some(function(oKeyValuePair){
                var sIgnoreKey = oKeyValuePair.ignoreKey;
                var vIgnoreValue = oKeyValuePair.ignoreValue;
                return oProperty[sIgnoreKey] === vIgnoreValue;
            });

        },

        _checkSettings: function(oP13nUI, mDialogSettings, fnOnError) {
            if (!mDialogSettings) {
                fnOnError("Please provide a settings object for p13n creation");
            }

            if (!mDialogSettings.title && !mDialogSettings.customHeader) {
                fnOnError("Please provide a title or customHeader in the settings object for p13n creation");
            }
        },

        arrayToMap: function(aArray) {
            return aArray.reduce(function(mMap, oProp, iIndex){
                mMap[oProp.name] = oProp;
                mMap[oProp.name].position = iIndex;
                return mMap;
            }, {});
        },

        /**
         *
         * @param {object} oDialog AdaptFiltersDialog
         * @param {object} [oParent] An optional parent object to chain if necessary
         *
         * @returns {Promise} Promise resolving in the Dialog instance
         */
        addRTACustomFieldButton: function (oDialog, oParent) {

            var bExtensibilityEnabled = false,
                oDialogParent = oDialog.getParent();

            // cover SmartTable scenario
            if (oParent && oParent.isA('sap.ui.comp.smarttable.SmartTable')) {
                oDialogParent = oParent;
            }

            return sap.ui.getCore().loadLibrary('sap.ui.rta', {
                async: true
            }).then(function() {
                return new Promise(function(resolve) {
                    sap.ui.require([
                        "sap/ui/rta/Utils"
                    ], function(rtaUtils) {
                        var oHandleExtensibility = Promise.all([
                            rtaUtils.isServiceUpToDate(oDialogParent),
                            FieldExtensibility.isExtensibilityEnabled(oDialogParent)
                        ]);

                        return oHandleExtensibility.then(function (aResult) {
                            bExtensibilityEnabled = !!aResult[1];
                        })
                            .then(function() {
                                var oCustomHeader = oDialog.getCustomHeader(),
                                    sId = oDialogParent && oDialogParent.getId ? oDialogParent.getId() : undefined,
                                    oResourceBundle = sap.ui.getCore().getLibraryResourceBundle("sap.ui.mdc");

                                if (!oCustomHeader) {
                                    var oBar = new Bar({
                                        contentLeft: [
                                            new Title({
                                                text: oDialog.getTitle()
                                            })
                                        ]
                                    });
                                    oDialog.setCustomHeader(oBar);
                                    oCustomHeader = oDialog.getCustomHeader();
                                }

                                if (bExtensibilityEnabled) {
                                    oCustomHeader.addContentRight(new Button( sId + "-addCustomField", {
                                        icon: "sap-icon://add",
                                        enabled: bExtensibilityEnabled,
                                        tooltip: oResourceBundle.getText("p13nDialog.rtaAddTooltip"),
                                        press: function (oEvt) {
                                            var sRtaStyleClassName = rtaUtils.getRtaStyleClassName(),
                                                oAdaptDialog =  oEvt.getSource().getParent().getParent(),
                                                oControl = oAdaptDialog.getParent();

                                            // cover SmartTable scenario
                                            if (oParent && oParent.isA('sap.ui.comp.smarttable.SmartTable')) {
                                                oControl = oParent;
                                            }

                                            FieldExtensibility.onControlSelected(oControl).then(function (oRetVal) {
                                                FieldExtensibility.getExtensionData().then(function (oExtensibilityInfo) {
                                                    FieldExtensibility.onTriggerCreateExtensionData(oExtensibilityInfo, sRtaStyleClassName);
                                                    oAdaptDialog.close(); // close as if there is newly created custom field, next time user tries to open it - it checks for service outdated and shows correct information
                                                });
                                            });

                                        }
                                    }));

                                    oDialog.setCustomHeader(oCustomHeader);
                                    resolve(oDialog);
                                }

                            });

                    });
                });
            });
        }

    };

	return P13nBuilder;
});
<|endoftext|>


<commit_before>/*
Documentation for g:convert validator:
sample url: http://localhost:3000/api/validatorGconvert?genes=ATM ATP ATM
output: {"unrecogized":["ATP"],"duplicate":["ATM"],"geneInfo":[{"HGNC_symbol":"ATM","HGNC_id":"HGNC:795"}]}
*/

const request = require('request');
const _ = require('lodash');

const defaultSetting = {
  'output': 'mini',
  'organism': 'hsapiens',
  'target': 'HGNC'
};
const gConvertURL = 'http://biit.cs.ut.ee/gprofiler/gconvert.cgi';

const validatorGconvert = (query) => {
  const promise = new Promise((resolve, reject) => {
    const formData = _.assign({}, defaultSetting, { query: query });
    request.post({ url: gConvertURL, formData: formData }, (err, httpResponse, body) => {
      if (err) {
        reject(err);
      }
      const geneInfoList = _.map(body.split('\n'), ele => { return ele.split('\t'); });
      geneInfoList.splice(-1, 1); // remove last element ''

      const unrecogized = [];
      const duplicate = [];
      const geneInfo = [];
      const initialAliasIndex = 1;
      const convertedAliasIndex = 3;
      _.forEach(geneInfoList, info => {
        if (info[convertedAliasIndex] === 'N/A') {
          if (_.filter(unrecogized, ele => ele === info[initialAliasIndex]).length === 0) {
            unrecogized.push(info[initialAliasIndex]);
          }
        } else {
          if (_.filter(geneInfoList, ele => ele[convertedAliasIndex] === info[convertedAliasIndex]).length > 1 && _.filter(duplicate, ele => ele === info[initialAliasIndex]).length === 0) {
            duplicate.push(info[initialAliasIndex]);
          }
          if (_.filter(geneInfo, ele => ele.initialAlias === info[initialAliasIndex]).length === 0) {
            geneInfo.push({ initialAlias: info[initialAliasIndex], convertedAlias: info[convertedAliasIndex] });
          }
        }
      });

      const ret = { unrecogized: unrecogized, duplicate: duplicate, geneInfo: geneInfo };
      resolve(ret);
    });
  });
  return promise;
};

module.exports = { validatorGconvert };

// // simple testing
// validatorGconvert("ATM ATM AFF4 ATM ATP").then(function (results) {
//   console.log(results);
// });<commit_msg>renamed settings to options<commit_after>/*
Documentation for g:convert validator:
sample url: http://localhost:3000/api/validatorGconvert?genes=ATM ATP ATM
output: {"unrecogized":["ATP"],"duplicate":["ATM"],"geneInfo":[{"HGNC_symbol":"ATM","HGNC_id":"HGNC:795"}]}
*/

const request = require('request');
const _ = require('lodash');

const defaultOptions = {
  'output': 'mini',
  'organism': 'hsapiens',
  'target': 'HGNC'
};
const gConvertURL = 'http://biit.cs.ut.ee/gprofiler/gconvert.cgi';

const validatorGconvert = (query) => {
  const promise = new Promise((resolve, reject) => {
    const formData = _.assign({}, defaultOptions, { query: query });
    request.post({ url: gConvertURL, formData: formData }, (err, httpResponse, body) => {
      if (err) {
        reject(err);
      }
      const geneInfoList = _.map(body.split('\n'), ele => { return ele.split('\t'); });
      geneInfoList.splice(-1, 1); // remove last element ''

      const unrecogized = [];
      const duplicate = [];
      const geneInfo = [];
      const initialAliasIndex = 1;
      const convertedAliasIndex = 3;
      _.forEach(geneInfoList, info => {
        if (info[convertedAliasIndex] === 'N/A') {
          if (_.filter(unrecogized, ele => ele === info[initialAliasIndex]).length === 0) {
            unrecogized.push(info[initialAliasIndex]);
          }
        } else {
          if (_.filter(geneInfoList, ele => ele[convertedAliasIndex] === info[convertedAliasIndex]).length > 1 && _.filter(duplicate, ele => ele === info[initialAliasIndex]).length === 0) {
            duplicate.push(info[initialAliasIndex]);
          }
          if (_.filter(geneInfo, ele => ele.initialAlias === info[initialAliasIndex]).length === 0) {
            geneInfo.push({ initialAlias: info[initialAliasIndex], convertedAlias: info[convertedAliasIndex] });
          }
        }
      });

      const ret = { unrecogized: unrecogized, duplicate: duplicate, geneInfo: geneInfo };
      resolve(ret);
    });
  });
  return promise;
};

module.exports = { validatorGconvert };

// // simple testing
// validatorGconvert("ATM ATM AFF4 ATM ATP").then(function (results) {
//   console.log(results);
// });<|endoftext|>