/** * Copyright Sourcepole AG * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import {connect} from 'react-redux'; import {XMLParser} from 'fast-xml-parser'; import isEmpty from 'lodash.isempty'; import PropTypes from 'prop-types'; import {v4 as uuidv4} from 'uuid'; import ConfigUtils from '../utils/ConfigUtils'; import {parseExpression} from '../utils/EditingUtils'; import LocaleUtils from '../utils/LocaleUtils'; import MapUtils from '../utils/MapUtils'; import MiscUtils from '../utils/MiscUtils'; import Request from '../utils/Request'; import EditComboField from './EditComboField'; import EditUploadField from './EditUploadField'; import Icon from './Icon'; import Button from './widgets/Button'; import ButtonBar from './widgets/ButtonBar'; import DateTimeInput from './widgets/DateTimeInput'; import ListInput from './widgets/ListInput'; import NumberInput from './widgets/NumberInput'; import Spinner from './widgets/Spinner'; import TextInput from './widgets/TextInput'; import './style/QtDesignerForm.css'; const FormPreprocessors = {}; /* editDataset: . preprocessor: function(formData, feature, callback) formData: { fields: { dict of fields }, buttons: { dict of buttons }, externalFields: { dict of external fields} } feature: The feature for which the form is being displayed callback: function(formData), return the updated formData */ export function registerFormPreprocessor(editDataset, preprocessor) { FormPreprocessors[editDataset] = preprocessor; } export function removeFormPreprocessor(editDataset) { delete FormPreprocessors[editDataset]; } const hFitWidgets = ["QLabel", "QCheckBox", "QRadioButton", "Line", "QDateTimeEdit", "QDateEdit", "QTimeEdit"]; const vFitWidgets = ["QLabel", "QCheckBox", "QRadioButton", "Line", "QDateTimeEdit", "QDateEdit", "QTimeEdit", "QPushButton", "QComboBox", "QLineEdit", "QSpinBox", "QDoubleSpinBox", "QSlider"]; class QtDesignerForm extends React.Component { static propTypes = { addRelationRecord: PropTypes.func, editConfig: PropTypes.object, editConfigs: PropTypes.object, editLayerId: PropTypes.string, editRelationRecord: PropTypes.func, feature: PropTypes.object, iface: PropTypes.object, locale: PropTypes.string, mapCrs: PropTypes.string, mapPrefix: PropTypes.string, readOnly: PropTypes.bool, removeRelationRecord: PropTypes.func, reorderRelationRecord: PropTypes.func, report: PropTypes.bool, setFormBusy: PropTypes.func, setRelationTables: PropTypes.func, switchEditContext: PropTypes.func, translations: PropTypes.object, updateField: PropTypes.func, updateRelationField: PropTypes.func }; static defaultState = { loadedform: null, activetabs: {}, formdata: null, loading: false, loadingReqId: null, relationAddPressed: null }; state = { reevaluate: 0 }; constructor(props) { super(props); this.state = QtDesignerForm.defaultState; this.form = null; this.highlightId = null; this.highlight = null; } componentDidMount() { this.componentDidUpdate({}); } componentWillUnmount() { MapUtils.removeUnmanagedLayer(this.highlight); } componentDidUpdate(prevProps) { // Query form if (this.props.editConfig.form !== prevProps.editConfig?.form || this.props.feature.__version__ !== prevProps.feature?.__version__) { this.setState((state) => ({ ...QtDesignerForm.defaultState, activetabs: this.props.editConfig.form === prevProps.editConfig?.form ? state.activetabs : {} })); let url = MiscUtils.resolveAssetsPath(this.props.editConfig.form); url += (url.includes('?') ? '&' : '?') + "lang=" + this.props.locale; const loadingReqId = uuidv4(); this.setState({formData: null, loadedform: null, loading: true, loadingReqId: loadingReqId}); Request.get(url).then(response => { this.parseForm(this.props.editConfig.form, response.data, loadingReqId); }).catch(e => { // eslint-disable-next-line console.log(e); if (this.state.loadingReqId === loadingReqId) { this.setState({loading: false, loadingReqId: null}); } }); } // As soon as relation value is added, scroll to bottom of list if (this.form && this.props.feature?.relationValues && prevProps.feature?.relationValues && this.props.feature.relationValues !== prevProps.feature.relationValues) { Object.entries(this.props.feature.relationValues).forEach(([dataset, entry]) => { const prevFeatures = prevProps.feature.relationValues[dataset]?.features ?? []; if (entry.features.length > prevFeatures.length && prevFeatures.length > 0) { const widget = this.form.querySelector(`[data-reldataset="${dataset}"]`); widget?.scrollTo(0, widget?.scrollHeight); } }); } } render() { if (this.state.loading) { return (
{LocaleUtils.tr("qtdesignerform.loading")}
); } else if (this.state.formData && this.state.loadedform === this.props.editConfig.form) { const root = this.state.formData.ui.widget; return (
{this.form = el;}}> {this.renderLayout(root.layout, this.props.feature, this.props.editConfig, this.props.updateField)}
); } else { return null; } } isVertical = (orientation) => { return orientation === "Qt::Vertical" || orientation === "Qt::Orientation::Vertical"; }; isHorizontal = (orientation) => { return orientation === "Qt::Horizontal" || orientation === "Qt::Orientation::Horizontal"; }; renderLayout = (layout, feature, editConfig, updateField, nametransform = (name) => name, visible = true) => { let containerClass = ""; let itemStyle = () => ({}); let sortKey = (item, idx) => idx; let containerStyle = {}; if (!layout) { return null; } else if (layout.class === "QGridLayout" || layout.class === "QFormLayout") { containerClass = "qt-designer-layout-grid"; containerStyle = { gridTemplateColumns: this.computeLayoutColumns(layout.item).join(" "), gridTemplateRows: this.computeLayoutRows(layout.item).join(" ") }; itemStyle = item => ({ gridArea: (1 + parseInt(item.row, 10)) + "/" + (1 + parseInt(item.column, 10)) + "/ span " + parseInt(item.rowspan || 1, 10) + "/ span " + parseInt(item.colspan || 1, 10) }); sortKey = (item) => item.row; } else if (layout.class === "QVBoxLayout") { containerClass = "qt-designer-layout-grid"; containerStyle = { gridTemplateRows: this.computeLayoutRows(layout.item, true).join(" ") }; itemStyle = (item, idx) => ({ gridArea: (1 + idx) + "/1/ span 1/ span 1" }); sortKey = (item, idx) => idx; } else if (layout.class === "QHBoxLayout") { containerClass = "qt-designer-layout-grid"; containerStyle = { gridTemplateColumns: this.computeLayoutColumns(layout.item, true).join(" ") }; itemStyle = (item, idx) => ({ gridArea: "1/" + (1 + idx) + "/ span 1/ span 1" }); sortKey = (item, idx) => idx; } else { return null; } if (!visible) { containerStyle.display = 'none'; } if (layout.item.find(item => item.spacer && this.isVertical(item.spacer.property?.orientation))) { containerStyle.height = '100%'; } const fields = (this.props.editConfig.fields ?? []).reduce((res, field) => ({...res, [field.id]: field}), {}); return (
{layout.item.sort((a, b) => (sortKey(a) - sortKey(b))).map((item, idx) => { let child = null; if (item.widget) { child = this.renderWidget(item.widget, feature, editConfig, fields, updateField, nametransform, false); } else if (item.layout) { child = this.renderLayout(item.layout, feature, editConfig, updateField, nametransform); } else if (item.spacer) { child = (
); } else { return null; } return (
{child}
); })}
); }; computeLayoutColumns = (items, useIndex = false) => { const columns = []; let hasAuto = false; items.forEach((item, index) => { const col = useIndex ? index : (parseInt(item.column, 10) || 0); const colSpan = useIndex ? 1 : (parseInt(item.colspan, 10) || 1); if (this.isHorizontal(item.spacer?.property?.orientation)) { columns[col] = '1fr'; hasAuto = true; } else if (!hFitWidgets.includes(item.widget?.class) && colSpan === 1) { columns[col] = 'auto'; hasAuto = true; } else { columns[col] = columns[col] ?? null; // Placeholder replaced by fit-content below } }); const fit = 'fit-content(' + Math.round(1 / columns.length * 100) + '%)'; for (let col = 0; col < columns.length; ++col) { columns[col] = hasAuto ? (columns[col] || fit) : 'auto'; } return columns; }; computeLayoutRows = (items, useIndex = false) => { const rows = []; items.forEach((item, index) => { const row = useIndex ? index : (parseInt(item.row, 10) || 0); const rowSpan = useIndex ? 1 : (parseInt(item.rowspan, 10) || 1); if (this.isVertical(item.spacer?.property?.orientation)) { rows[row] = '1fr'; } else if (item.widget?.layout ?? item.layout) { rows[row] = item.widget?.layout?.verticalFill || item.layout?.verticalFill ? 'auto' : null; // Placeholder replaced by fit-content below } else if (item.widget?.name?.startsWith?.("nrel_")) { rows[row] = 'auto'; } else if (!vFitWidgets.includes(item.widget?.class) && rowSpan === 1) { rows[row] = 'auto'; } else { rows[row] = rows[row] ?? null; // Placeholder replaced by fit-content below } }); const fit = 'fit-content(' + Math.round(1 / rows.length * 100) + '%)'; for (let row = 0; row < rows.length; ++row) { rows[row] = rows[row] || fit; } return rows; }; renderWidget = (widget, feature, editConfig, fields, updateField, nametransform = (name) => name, isRelWidget, disabled = false) => { let value = feature.properties?.[widget.name] ?? ""; const prop = widget.property || {}; if (String(prop.visible) === "false") { return null; } const attr = widget.attribute || {}; const fieldname = widget.name.replace(/kvrel__/, '').split("__")[isRelWidget ? 1 : 0]; const field = fields[fieldname]; const constraints = {...field?.constraints}; constraints.readOnly = this.props.readOnly || constraints.readOnly === true || String(prop.readOnly) === "true" || String(prop.enabled) === "false" || disabled; constraints.required = !constraints.readOnly && (constraints.required || String(prop.required) === "true"); constraints.placeholder = prop.placeholderText || constraints.placeholder || ""; const fontProps = prop.font || {}; const fontStyle = { fontWeight: String(fontProps.bold) === "true" ? "bold" : "normal", fontStyle: String(fontProps.italic) === "true" ? "italic" : "normal", textDecoration: [ String(fontProps.underline) === "true" ? "underline" : "", String(fontProps.strikeout) === "true" ? "line-through" : "" ].join(" "), fontSize: Math.round((fontProps.pointsize || 9) / 9 * 100) + "%", textAlign: 'left' }; if (prop.alignment) { if (prop.alignment.includes("Qt::AlignRight")) { fontStyle.textAlign = 'right'; } else if (prop.alignment.includes("Qt::AlignCenter")) { fontStyle.textAlign = 'center'; } } let frameShapeClass = ''; if (prop.frameShape) { const frameStyleClassMap = { "QFrame::Shape::Box": "qt-designer-form-frame-box", "QFrame::Shape::StyledPanel": "qt-designer-form-frame-box", "QFrame::Shape::Panel": "qt-designer-form-frame-box", "QFrame::Shape::HLine": "qt-designer-form-frame-hline", "QFrame::Shape::VLine": "qt-designer-form-frame-vline" }; frameShapeClass = frameStyleClassMap[prop.frameShape] ?? ''; } else if (!prop.flat) { frameShapeClass = "qt-designer-form-frame-box"; } let elname = undefined; if (widget.name.startsWith("ext__")) { updateField = null; value = this.state.formData.externalFields[widget.name.slice(5)]; constraints.readOnly = true; } else { elname = nametransform(widget.name); } if (widget.component) { return ( updateField(fieldName ?? widget.name, val)} readOnly={this.props.readOnly} removeRelationRecord={this.props.removeRelationRecord} reorderRelationRecord={this.props.reorderRelationRecord} updateRelationField={this.props.updateRelationField} widget={widget} {...widget.props} /> ); } else if (widget.class === "QLabel") { if (widget.name.startsWith("img__")) { value = feature.properties?.[widget.name.split("__")[1]] ?? widget.property.text; return (
); } else if (widget.name.startsWith("ext__")) { return (
{value}
); } else { const text = widget.property.fieldLabel ? this.translateFieldName(widget.property.text, editConfig.layerName) : widget.property.text; return (
{text}
); } } else if (widget.class === "Line") { const linetype = this.isVertical(widget.property?.orientation) ? "vline" : "hline"; return (
); } else if (widget.class === "QFrame") { if (widget.property.visibilityExpression) { const exprResult = parseExpression(widget.property.visibilityExpression, feature, editConfig, this.props.iface, this.props.mapPrefix, this.props.mapCrs, () => this.setState({reevaluate: +new Date})); if (exprResult === false || exprResult === 0) { return null; } } return (
{widget.name.startsWith("nrel__") ? this.renderNRelation(widget) : this.renderLayout(widget.layout, feature, editConfig, updateField, nametransform)}
); } else if (widget.class === "QGroupBox") { if (widget.property.visibilityExpression) { const exprResult = parseExpression(widget.property.visibilityExpression, feature, editConfig, this.props.iface, this.props.mapPrefix, this.props.mapCrs, () => this.setState({reevaluate: +new Date})); if (exprResult === false || exprResult === 0) { return null; } } return (
{this.translateFormString(prop.title, editConfig.layerName)}
{widget.name.startsWith("nrel__") ? this.renderNRelation(widget) : this.renderLayout(widget.layout, feature, editConfig, updateField, nametransform)}
); } else if (widget.class === "QTabWidget") { const tabwidgets = (widget.widget || []).filter(child => { if (!child.property.visibilityExpression) { return true; } const exprResult = parseExpression(child.property.visibilityExpression, feature, editConfig, this.props.iface, this.props.mapPrefix, this.props.mapCrs, () => this.setState({reevaluate: +new Date})); return exprResult !== false && exprResult !== 0; }); if (isEmpty(tabwidgets)) { return null; } const activetab = this.state.activetabs[widget.name] || tabwidgets[0].name; const tabs = tabwidgets.map(tab => ({ key: tab.name, label: this.translateFormString(tab.attribute.title, editConfig.layerName) })); return (
this.setState((state) => ({activetabs: {...state.activetabs, [widget.name]: key}}))} />
{tabwidgets.filter(child => child.layout).map(child => ( this.renderLayout(child.layout, feature, editConfig, updateField, nametransform, child.name === activetab) ))}
); } else if (widget.class === "QTextEdit" || widget.class === "QTextBrowser" || widget.class === "QPlainTextEdit") { if (value === "" && (feature.properties?.[widget.name] ?? null) === null) { value = ConfigUtils.getConfigProp("editTextNullValue") ?? ""; } if (this.props.report) { return (
{value}
); } else { const addLinkAnchors = ConfigUtils.getConfigProp("editingAddLinkAnchors") !== false; return ( updateField(widget.name, val)} placeholder={constraints.placeholder} readOnly={constraints.readOnly} required={constraints.required} style={fontStyle} value={String(value)} />); } } else if (widget.class === "QLineEdit") { if (widget.name.endsWith("__upload")) { const fieldId = widget.name.replace(/__upload/, ''); const uploadValue = (feature.properties?.[fieldId] || ""); const uploadElName = elname.replace(/__upload/, ''); const widgetConstraints = { accept: prop.text || "", required: constraints.required }; return (); } else { if (constraints.prec !== undefined && typeof value === 'number') { value = value.toFixed(constraints.prec); } else if (value === "" && (feature.properties?.[widget.name] ?? null) === null) { value = ConfigUtils.getConfigProp("editTextNullValue") ?? ""; } if (this.props.report) { return (
{value || constraints.placeholder}
); } else { const addLinkAnchors = ConfigUtils.getConfigProp("editingAddLinkAnchors") !== false; const editTextNullValue = ConfigUtils.getConfigProp("editTextNullValue"); return ( updateField(widget.name, val)} placeholder={constraints.placeholder} readOnly={constraints.readOnly} required={constraints.required} style={fontStyle} value={String(value)} />); } } } else if (widget.class === "QCheckBox" || widget.class === "QRadioButton") { const type = widget.class === "QCheckBox" ? "checkbox" : "radio"; const inGroup = attr.buttonGroup; const checked = inGroup ? this.props.feature.properties?.[this.groupOrName(widget)] === widget.name : value; return ( ); } else if (widget.class === "QComboBox") { const parts = widget.name.split("__"); if ((parts.length === 5 || parts.length === 6) && parts[0] === "kvrel") { // kvrel__attrname__datatable__keyfield__valuefield // kvrel__reltablename__attrname__datatable__keyfield__valuefield const count = parts.length; const fieldId = parts.slice(1, count - 3).join("__"); value = feature.properties?.[fieldId] ?? ""; const keyvalrel = parts[count - 3] + ":" + parts[count - 2] + ":" + parts[count - 1]; let filterExpr = null; if (field?.filterExpression) { filterExpr = parseExpression(field.filterExpression, feature, editConfig, this.props.iface, this.props.mapPrefix, this.props.mapCrs, () => this.setState({reevaluate: +new Date}), true); } return ( ); } else { const values = widget.item ? MiscUtils.ensureArray(widget.item).map((item) => ({ label: item.property.text, value: item.property.value ?? item.property.text })) : constraints.values ?? []; return ( ); } } else if (widget.class === "QSpinBox" || widget.class === "QDoubleSpinBox" || widget.class === "QSlider") { const floatConstraint = (x) => { const f = parseFloat(x); return isNaN(f) ? undefined : f; }; const min = floatConstraint(prop.minimum ?? constraints.min); const max = floatConstraint(prop.maximum ?? constraints.max); const step = prop.singleStep ?? constraints.step ?? 1; const precision = prop.decimals ?? 0; if (widget.class === "QSlider") { return ( updateField(widget.name, ev.target.value)} placeholder={constraints.placeholder} readOnly={constraints.readOnly} required={constraints.required} size={5} step={step} style={fontStyle} type="range" value={value} />); } else { return ( updateField(widget.name, val)} placeholder={constraints.placeholder} readOnly={constraints.readOnly} required={constraints.required} step={step} style={fontStyle} value={feature.properties?.[widget.name]} />); } } else if (widget.class === "QDateEdit") { const min = prop.minimumDate ? this.dateConstraint(prop.minimumDate) : "1600-01-01"; const max = prop.maximumDate ? this.dateConstraint(prop.maximumDate) : "9999-12-31"; return ( updateField(widget.name, ev.target.value)} placeholder={constraints.placeholder} readOnly={constraints.readOnly} required={constraints.required} style={fontStyle} type="date" value={value.split("T")[0]} /> ); } else if (widget.class === "QTimeEdit") { return ( updateField(widget.name, ev.target.value)} placeholder={constraints.placeholder} readOnly={constraints.readOnly} required={constraints.required} style={fontStyle} type="time" value={value} /> ); } else if (widget.class === "QDateTimeEdit") { const min = prop.minimumDate ? this.dateConstraint(prop.minimumDate) : "1600-01-01"; const max = prop.maximumDate ? this.dateConstraint(prop.maximumDate) : "9999-12-31"; return ( updateField(widget.name, val)} readOnly={constraints.readOnly} required={constraints.required} style={fontStyle} value={value} valueHasTz={field.data_type === "timestamp with time zone"} /> ); } else if (widget.class === "QListWidget") { return ( updateField(widget.name, val)} readOnly={constraints.readOnly} required={constraints.required} type={field.type.slice(0, -2)} value={value} /> ); } else if (widget.class === "QWidget") { if (widget.name.startsWith("nrel__")) { return this.renderNRelation(widget); } else if (widget.name.startsWith("ext__")) { return value; } else { return this.renderLayout(widget.layout, feature, editConfig, updateField, nametransform); } } else if (widget.class === "QPushButton") { if (widget.name.startsWith("btn__") && widget.onClick) { return (); } else if (widget.name.startsWith("featurelink__")) { const parts = widget.name.split("__"); // featurelink__layer__attrname // featurelink__layer__reltable__attrname if (parts.length === 3 || parts.length === 4 ) { const layer = parts[1]; const rellayer = parts.length === 4 ? parts[2] : ""; const attrname = parts.slice(2).join("__"); value = feature.properties?.[attrname]; if (layer === rellayer) { const index = parseInt(nametransform("").split("__")[1], 10); // Ugh.. const dataset = this.props.mapPrefix + "." + rellayer; return (
); } else { if (value !== null) { return (
); } else { const featurebuttons = [ {key: 'Pick', icon: 'pick', label: LocaleUtils.tr("common.pick")}, {key: 'Create', icon: 'editdraw', label: LocaleUtils.tr("common.draw")} ]; return ( this.props.switchEditContext(action, layer, null, (f) => updateField(attrname, f.id))} />); } } } } } else if (widget.class === "QStackedWidget") { return this.renderLayout(widget.widget[parseInt(widget.property.currentIndex, 10)].layout, feature, editConfig, updateField, nametransform); } return null; }; renderNRelation = (widget) => { const parts = widget.name.split("__"); if (parts.length < 3 || !widget.layout) { return null; } const disabled = String(widget.property?.enabled) === "false"; const layername = parts[1]; const sortcol = parts[3] || null; const noreorder = parts[4] || false; const headerItems = widget.layout.item.filter(item => item.widget && item.widget.name.startsWith("header__")).sort((a, b) => a.column - b.column); const widgetItems = widget.layout.item.filter(item => !item.widget || !item.widget.name.startsWith("header__")).sort((a, b) => a.column - b.column); const tableFitWidgets = ["QLabel", "QCheckBox", "QRadioButton", "QDateTimeEdit", "QDateEdit", "QTimeEdit"]; const columnStyles = widgetItems.map(item => { return item.widget && tableFitWidgets.includes(item.widget.class) ? {width: '1px'} : {}; }); const editConfig = this.props.editConfigs[this.props.mapPrefix][layername]; if (!editConfig) { // Relation dataset not permitted / no edit config available return null; } const relDataset = editConfig.editDataset; const fields = (editConfig.fields ?? []).reduce((res, field) => ({...res, [field.id]: field}), {}); const editPermissions = editConfig.permissions || {}; const addData = { geomType: editConfig.geomType, dataset: relDataset }; const addButtons = this.state.relationAddPressed === relDataset ? [{ key: editConfig.pickMode ?? "Pick", icon: "pick", label: LocaleUtils.tr("common.pick"), data: addData }, { key: "Create", icon: "editdraw", label: LocaleUtils.tr("common.draw"), data: addData }, { key: "Cancel", icon: "remove", label: LocaleUtils.tr("common.cancel"), extraClasses: "button-reject" }] : [{ key: "Add", icon: "plus", label: LocaleUtils.tr("common.add"), disabled: !this.props.feature.relationValues?.[relDataset], data: addData }]; return (
{!this.props.feature.relationValues ? (
) : null} {!isEmpty(headerItems) ? ( ))} ) : null} {(this.props.feature.relationValues?.[relDataset]?.features || []).map((feature, idx) => { const updateField = (name, value) => { const fieldname = name.slice(layername.length + 2); // Strip __ prefix this.props.updateRelationField(relDataset, idx, fieldname, value); }; const nametransform = (name) => (name + "__" + idx); const status = feature.__status__ || ""; const relFeature = { ...feature, properties: Object.entries(feature.properties).reduce((res, [key, value]) => ( {...res, [layername + "__" + key]: value}), {}) }; let statusIcon = null; if (status === "new") { statusIcon = "new"; } else if (status) { statusIcon = "edited"; } let statusText = ""; if (feature.error) { statusIcon = "warning"; statusText = this.buildErrMsg(feature); } const extraClass = status.startsWith("deleted") ? "qt-designer-widget-relation-record-deleted" : ""; return ( {widgetItems.map((item, widx) => { if (item.widget) { return ( ); } else if (item.spacer) { return ( ) : null} {!this.props.readOnly && !disabled && editPermissions.deletable !== false ? ( ) : null} ); })}
{headerItems.map(item => ({item.widget.property.text}
{statusIcon ? () : null} {this.renderWidget(item.widget, relFeature, editConfig, fields, updateField, nametransform, true, disabled)} ); } else { return null; } })} {!this.props.readOnly && !disabled && sortcol && !noreorder ? ( this.props.reorderRelationRecord(relDataset, idx, -1)} />
this.props.reorderRelationRecord(relDataset, idx, 1)} />
this.props.removeRelationRecord(relDataset, idx)} />
{!this.props.readOnly && editPermissions.creatable !== false && editPermissions.geomreadonly !== true ? ( ) : null}
); }; addRelationRecordAction = (key, data) => { if (key === "Add") { if (data.geomType) { this.setState({relationAddPressed: data.dataset}); } else { this.props.addRelationRecord(data.dataset); } } else if (key === "Create") { this.props.addRelationRecord(data.dataset, null, "Create"); this.setState({relationAddPressed: null}); } else if (key === "Pick") { this.props.addRelationRecord(data.dataset, null, "Pick"); this.setState({relationAddPressed: null}); } else if (key === "PickGeometry") { this.props.addRelationRecord(data.dataset, null, "PickGeometry"); this.setState({relationAddPressed: null}); } else if (key === "Cancel") { this.setState({relationAddPressed: null}); } }; startRelationTableResize = (ev) => { const container = ev.target.parentElement; if (!container) { return; } // Drop max-height as soon as a manual height is set const startHeight = container.offsetHeight; container.style.height = container.offsetHeight + 'px'; container.style.maxHeight = 'initial'; const startMouseY = ev.clientY; const resizeInput = (event) => { container.style.height = Math.max(MiscUtils.convertEmToPx(2.5), (startHeight + (event.clientY - startMouseY))) + 'px'; }; const eventShield = ev.view.document.createElement("div"); eventShield.className = '__event_shield'; const shieldParent = MiscUtils.appContainer(ev.target); shieldParent.classList.add('nsresizing'); shieldParent.appendChild(eventShield); ev.view.addEventListener("pointermove", resizeInput); ev.view.addEventListener("pointerup", () => { eventShield.remove(); shieldParent.classList.remove('nsresizing'); ev.view.removeEventListener("pointermove", resizeInput); }, {once: true}); }; groupOrName = (widget) => { return widget.attribute && widget.attribute.buttonGroup ? widget.attribute.buttonGroup._ : widget.name; }; dateConstraint = (constr) => { return (constr.year + "-" + ("0" + constr.month).slice(-2) + "-" + ("0" + constr.day).slice(-2)); }; parseForm = (url, data, loadingReqId) => { const parserOpts = { isArray: () => false, ignoreAttributes: false, attributeNamePrefix: "" }; const json = (new XMLParser(parserOpts)).parse(data); const relationTables = {}; const externalFields = {}; const widgets = {}; const fields = {}; const buttons = {}; const nrels = {}; const counters = { widget: 0, layout: 0 }; this.reformatWidget(json.ui.widget, relationTables, fields, buttons, nrels, externalFields, widgets, counters); // console.log(json); json.externalFields = externalFields; json.widgets = widgets; json.fields = fields; json.buttons = buttons; json.nrels = nrels; json.relationTables = relationTables; if (FormPreprocessors[this.props.editConfig.editDataset]) { FormPreprocessors[this.props.editConfig.editDataset](json, this.props.feature, (formData) => { if (this.state.loadingReqId === loadingReqId) { this.setState({formData: formData, loadedform: url, loading: false, loadingReqId: null}); this.props.setRelationTables(formData.relationTables); } }); } else { if (this.state.loadingReqId === loadingReqId) { this.setState({formData: json, loadedform: url, loading: false, loadingReqId: null}); this.props.setRelationTables(json.relationTables); } } }; reformatWidget = (widget, relationTables, fields, buttons, nrels, externalFields, widgets, counters) => { if (widget.property) { widget.property = MiscUtils.ensureArray(widget.property).reduce((res, prop) => { return ({...res, [prop.name]: prop[Object.keys(prop).find(key => key !== "name")]}); }, {}); } else { widget.property = {}; } if (widget.attribute) { widget.attribute = MiscUtils.ensureArray(widget.attribute).reduce((res, prop) => { return ({...res, [prop.name]: prop[Object.keys(prop).find(key => key !== "name")]}); }, {}); } else { widget.attribute = {}; } let verticalFill = false; if (widget.item) { MiscUtils.ensureArray(widget.item).forEach(item => { verticalFill |= this.reformatWidget(item, relationTables, fields, buttons, nrels, externalFields, widgets, counters); }); } widget.name = widget.name || (":widget_" + counters.widget++); const fieldNames = this.props.editConfig.fields.map(field => field.id); if (fieldNames.includes(widget.name)) { fields[widget.name] = widget; } else if (widget.name.startsWith("kvrel__") || widget.name.startsWith("img__")) { const parts = widget.name.split("__"); if (fieldNames.includes(parts[1])) { fields[parts[1]] = widget; } } else if (widget.name.startsWith("btn__")) { buttons[widget.name.split("__")[1]] = widget; } else if (widget.name.startsWith("nrel__")) { nrels[widget.name.split("__")[1]] = widget; } if (widget.name.startsWith("ext__")) { externalFields[widget.name.slice(5)] = ""; } widgets[widget.name] = widget; if (widget.layout) { verticalFill |= this.reformatLayout(widget.layout, relationTables, fields, buttons, nrels, externalFields, widgets, counters); } if (widget.widget) { widget.widget = Array.isArray(widget.widget) ? widget.widget : [widget.widget]; widget.widget.forEach(child => { child.name = (":widget_" + counters.widget++); verticalFill |= this.reformatWidget(child, relationTables, fields, buttons, nrels, externalFields, widgets, counters); }); } if (widget.name.startsWith("nrel__") || (!widget.layout && !vFitWidgets.includes(widget.class))) { verticalFill = true; } const parts = widget.name.split("__"); if (parts.length >= 3 && parts[0] === "nrel") { relationTables[this.props.mapPrefix + "." + parts[1]] = { table: this.props.mapPrefix + "." + parts[1], fkField: parts[2], sortField: parts[3] || null, noreorder: parts[4] || false, pkField: this.props.editConfig.reltables.find(entry => entry.id === widget.name)?.referencedField ?? null }; } return verticalFill; }; reformatLayout = (layout, relationTables, fields, buttons, nrels, externalFields, widgets, counters) => { layout.item = MiscUtils.ensureArray(layout.item); layout.name = layout.name || (":layout_" + counters.layout++); let verticalFill = false; layout.item.forEach(item => { if (!item) { return; } else if (item.widget) { verticalFill |= this.reformatWidget(item.widget, relationTables, fields, buttons, nrels, externalFields, widgets, counters); } else if (item.spacer) { item.spacer.property = MiscUtils.ensureArray(item.spacer.property).reduce((res, prop) => { return ({...res, [prop.name]: prop[Object.keys(prop).find(key => key !== "name")]}); }, {}); if (this.isVertical(item.spacer.property.orientation)) { verticalFill = true; } } else if (item.layout) { verticalFill |= this.reformatLayout(item.layout, relationTables, fields, buttons, nrels, externalFields, widgets, counters); } }); layout.verticalFill = verticalFill; return verticalFill; }; buildErrMsg = (record) => { let message = record.error; const errorDetails = record.error_details || {}; if (!isEmpty(errorDetails.geometry_errors)) { message += ":\n"; message += errorDetails.geometry_errors.map(entry => " - " + entry.reason + " at " + entry.location); } if (!isEmpty(errorDetails.data_errors)) { message += ":\n - " + errorDetails.data_errors.join("\n - "); } if (!isEmpty(errorDetails.validation_errors)) { message += ":\n - " + errorDetails.validation_errors.join("\n - "); } return message; }; translateFormString = (label, layerName) => { return this.props.translations?.layers?.[layerName]?.form?.[label] ?? label; }; translateFieldName = (fieldName, layerName) => { return this.props.translations?.layers?.[layerName]?.fields?.[fieldName] ?? fieldName; }; setHighlight = (key, feature) => { this.highlightId = key; this.highlight = MapUtils.addUnmanagedLayer({features: [feature]}, this.highlight); }; clearHighlight = (key) => { if (this.highlightId === key) { this.highlightId = null; MapUtils.removeUnmanagedLayer(this.highlight); } }; } export default connect((state) => ({ locale: state.locale.current, editConfigs: state.layers.editConfigs }))(QtDesignerForm);