WIP on Date widget

Something's not right with the parser/formatter, they're not getting called.

Times not handled yet
This commit is contained in:
nathan 2021-08-13 15:26:18 -06:00
parent 35e5d57b2a
commit 4f225054f8
11 changed files with 3578 additions and 3381 deletions

View File

@ -9,7 +9,7 @@
*/ */
import {css, html, LitElement} from "@lion/core"; import {css, html, LitElement} from "../../../node_modules/@lion/core/index.js";
import {Et2Widget} from "./Et2Widget"; import {Et2Widget} from "./Et2Widget";
export class Et2Box extends Et2Widget(LitElement) export class Et2Box extends Et2Widget(LitElement)

View File

@ -9,8 +9,8 @@
*/ */
import {css, html} from "@lion/core/index.js"; import {css, html} from "../../../node_modules/@lion/core/index.js";
import {LionButton} from "@lion/button/index.js"; import {LionButton} from "../../../node_modules/@lion/button/index.js";
import {Et2InputWidget} from "./et2_core_inputWidget"; import {Et2InputWidget} from "./et2_core_inputWidget";
import {Et2Widget} from "./Et2Widget"; import {Et2Widget} from "./Et2Widget";
@ -42,6 +42,7 @@ export class Et2Button extends Et2InputWidget(Et2Widget(LionButton))
static get properties() static get properties()
{ {
return { return {
...super.properties,
image: {type: String}, image: {type: String},
onclick: {type: Function} onclick: {type: Function}
} }

163
api/js/etemplate/Et2Date.ts Normal file
View File

@ -0,0 +1,163 @@
/**
* EGroupware eTemplate2 - Date widget (WebComponent)
*
* @license http://opensource.org/licenses/gpl-license.php GPL - GNU General Public License
* @package etemplate
* @subpackage api
* @link https://www.egroupware.org
* @author Nathan Gray
*/
import {css, html} from "../../../node_modules/@lion/core/index.js"
import {LionInputDatepicker} from "../../../node_modules/@lion/input-datepicker/index.js"
import {Et2InputWidget} from "./et2_core_inputWidget";
import {Et2Widget} from "./Et2Widget";
/**
* To parse a date into the right format
*
* @param {string} dateString
* @returns {Date | undefined}
*/
export function parseDate(dateString)
{
debugger;
let formatString = <string>(egw.preference("dateformat") || 'Y-m-d');
formatString = formatString.replaceAll(/-\/\./ig, '-');
let parsedString = "";
switch (formatString)
{
case 'd-m-Y':
parsedString = `${dateString.slice(6, 10)}/${dateString.slice(
3,
5,
)}/${dateString.slice(0, 2)}`;
break;
case 'm-d-Y':
parsedString = `${dateString.slice(6, 10)}/${dateString.slice(
0,
2,
)}/${dateString.slice(3, 5)}`;
break;
case 'Y-m-d':
parsedString = `${dateString.slice(0, 4)}/${dateString.slice(
5,
7,
)}/${dateString.slice(8, 10)}`;
break;
case 'd-M-Y':
parsedString = `${dateString.slice(6, 10)}/${dateString.slice(
3,
5,
)}/${dateString.slice(0, 2)}`;
default:
parsedString = '0000/00/00';
}
const [year, month, day] = parsedString.split('/').map(Number);
const parsedDate = new Date(Date.UTC(year, month - 1, day));
// Check if parsedDate is not `Invalid Date` or that the date has changed (e.g. the not existing 31.02.2020)
if (
year > 0 &&
month > 0 &&
day > 0 &&
parsedDate.getDate() === day &&
parsedDate.getMonth() === month - 1
)
{
return parsedDate;
}
return undefined;
}
/**
* Format dates according to user preference
*
* @param {Date} date
* @param {import('@lion/localize/types/LocalizeMixinTypes').FormatDateOptions} [options] Intl options are available
* set 'dateFormat': "Y-m-d" to specify a particular format
* @returns {string}
*/
export function formatDate(date: Date, options): string
{
debugger;
if (!date || !(date instanceof Date))
{
return "";
}
let _value = '';
// Add timezone offset back in, or formatDate will lose those hours
let formatDate = new Date(date.valueOf() + date.getTimezoneOffset() * 60 * 1000);
let dateformat = options.dateFormat || <string>egw.preference("dateformat") || 'Y-m-d';
var replace_map = {
d: "" + date.getUTCDate(),
m: "" + date.getUTCMonth() + 1,
Y: "" + date.getUTCFullYear()
}
var re = new RegExp(Object.keys(replace_map).join("|"), "gi");
_value = dateformat.replace(re, function (matched)
{
return replace_map[matched];
});
return _value;
}
export class Et2Date extends Et2InputWidget(Et2Widget(LionInputDatepicker))
{
static get styles()
{
return [
...super.styles,
css`
/* Custom CSS */
`,
];
}
static get properties()
{
return {
...super.properties,
value: {
attribute: true,
converter: {
toAttribute(value)
{
return value ? value.toJSON().replace(/\.\d{3}Z$/, 'Z') : "";
},
fromAttribute(value)
{
return new Date(value);
}
}
},
}
}
constructor()
{
super();
this.parser = parseDate;
this.formatter = formatDate;
}
connectedCallback()
{
super.connectedCallback();
}
getValue()
{
debugger;
return this.modelValue ? this.modelValue.toJSON().replace(/\.\d{3}Z$/, 'Z') : "";
}
}
customElements.define("et2-date", Et2Date);

View File

@ -1,5 +1,5 @@
/** /**
* EGroupware eTemplate2 - Button widget * EGroupware eTemplate2 - Textbox widget (WebComponent)
* *
* @license http://opensource.org/licenses/gpl-license.php GPL - GNU General Public License * @license http://opensource.org/licenses/gpl-license.php GPL - GNU General Public License
* @package etemplate * @package etemplate
@ -9,8 +9,8 @@
*/ */
import {css, html} from "@lion/core"; import {css, html} from "../../../node_modules/@lion/core/index.js"
import {LionInput} from "@lion/input"; import {LionInput} from "../../../node_modules/@lion/input/index.js"
import {Et2InputWidget} from "./et2_core_inputWidget"; import {Et2InputWidget} from "./et2_core_inputWidget";
import {Et2Widget} from "./Et2Widget"; import {Et2Widget} from "./Et2Widget";

View File

@ -341,14 +341,9 @@ export const Et2Widget = <T extends Constructor<LitElement>>(superClass: T) =>
let val = mgr.getEntry(widget.id, false, true); let val = mgr.getEntry(widget.id, false, true);
if (val !== null) if (val !== null)
{ {
widget.setAttribute("value", val); widget.set_value(val);
} }
} }
// Check for already inside namespace
if (this._createNamespace() && this.getArrayMgr("content").perspectiveData.owner == this)
{
widget.setAttribute("value", this.getArrayMgr("content").data);
}
} }
// Children need to be loaded // Children need to be loaded

View File

@ -23,9 +23,11 @@ import {et2_compileLegacyJS} from "./et2_core_legacyJSFunctions";
// fixing circular dependencies by only importing the type (not in compiled .js) // fixing circular dependencies by only importing the type (not in compiled .js)
import type {et2_tabbox} from "./et2_widget_tabs"; import type {et2_tabbox} from "./et2_widget_tabs";
export interface et2_input { export interface et2_input
{
getInputNode(): HTMLInputElement | HTMLElement; getInputNode(): HTMLInputElement | HTMLElement;
} }
/** /**
* et2_inputWidget derrives from et2_simpleWidget and implements the IInput * et2_inputWidget derrives from et2_simpleWidget and implements the IInput
* interface. When derriving from this class, call setDOMNode with an input * interface. When derriving from this class, call setDOMNode with an input
@ -141,10 +143,12 @@ export class et2_inputWidget extends et2_valueWidget implements et2_IInput, et2_
{ {
jQuery(node) jQuery(node)
.off('.et2_inputWidget') .off('.et2_inputWidget')
.bind("change.et2_inputWidget", this, function(e) { .bind("change.et2_inputWidget", this, function (e)
{
e.data.change.call(e.data, this); e.data.change.call(e.data, this);
}) })
.bind("focus.et2_inputWidget", this, function(e) { .bind("focus.et2_inputWidget", this, function (e)
{
e.data.focus.call(e.data, this); e.data.focus.call(e.data, this);
}); });
} }
@ -180,7 +184,9 @@ export class et2_inputWidget extends et2_valueWidget implements et2_IInput, et2_
if (args.indexOf(this) == -1) args.push(this); if (args.indexOf(this) == -1) args.push(this);
return this.onchange.apply(this, args); return this.onchange.apply(this, args);
} else { }
else
{
return (et2_compileLegacyJS(this.options.onchange, this, _node))(); return (et2_compileLegacyJS(this.options.onchange, this, _node))();
} }
} }
@ -249,9 +255,12 @@ export class et2_inputWidget extends et2_valueWidget implements et2_IInput, et2_
var node = this.getInputNode(); var node = this.getInputNode();
if (node) if (node)
{ {
if(_value && !this.options.readonly) { if (_value && !this.options.readonly)
{
jQuery(node).attr("required", "required"); jQuery(node).attr("required", "required");
} else { }
else
{
node.removeAttribute("required"); node.removeAttribute("required");
} }
} }
@ -392,33 +401,38 @@ export class et2_inputWidget extends et2_valueWidget implements et2_IInput, et2_
*/ */
type Constructor<T = {}> = new (...args: any[]) => T; type Constructor<T = {}> = new (...args: any[]) => T;
export const Et2InputWidget = <T extends Constructor>(superClass: T) => { export const Et2InputWidget = <T extends Constructor>(superClass: T) =>
class Et2InputWidgetClass extends superClass implements et2_IInput, et2_IInputNode { {
class Et2InputWidgetClass extends superClass implements et2_IInput, et2_IInputNode
{
label: string = ''; label: string = '';
protected value: string | number | Object; protected value: string | number | Object;
protected _oldValue: string | number | Object; protected _oldValue: string | number | Object;
/** WebComponent **/ /** WebComponent **/
static get properties() { static get properties()
{
return { return {
...super.properties, ...super.properties,
value: {attribute: false} value: {attribute: false}
}; };
} }
constructor() { constructor()
{
super(); super();
} }
set_value(new_value) set_value(new_value)
{ {
this.modelValue=new_value; this.value = new_value;
} }
getValue() getValue()
{ {
return this._inputNode.value; return this.getInputNode().value;
} }
isDirty() isDirty()

View File

@ -862,11 +862,6 @@ export class et2_widget extends ClassWithAttributes
widget.setAttribute("value", val); widget.setAttribute("value", val);
} }
} }
// Check for already inside namespace
if (this._createNamespace() && this.getArrayMgr("content").perspectiveData.owner == this)
{
widget.setAttribute("value", this.getArrayMgr("content").data);
}
} }
// Children need to be loaded // Children need to be loaded

View File

@ -25,6 +25,7 @@ import '../jsapi/egw_json.js';
import {egwIsMobile} from "../egw_action/egw_action_common.js"; import {egwIsMobile} from "../egw_action/egw_action_common.js";
import './Et2Box'; import './Et2Box';
import './Et2Button'; import './Et2Button';
import './Et2Date';
import './Et2Textbox'; import './Et2Textbox';
/* Include all widget classes here, we only care about them registering, not importing anything*/ /* Include all widget classes here, we only care about them registering, not importing anything*/
import './et2_widget_vfs'; // Vfs must be first (before et2_widget_file) due to import cycle import './et2_widget_vfs'; // Vfs must be first (before et2_widget_file) due to import cycle

View File

@ -87,14 +87,20 @@ class Date extends Transformer
* @param array $expand * @param array $expand
* @param array $data Row data * @param array $data Row data
*/ */
public function set_row_value($cname, Array $expand, Array &$data) public function set_row_value($cname, array $expand, array &$data)
{ {
if($this->type == 'date-duration') return; if($this->type == 'date-duration')
{
return;
}
$form_name = self::form_name($cname, $this->id, $expand); $form_name = self::form_name($cname, $this->id, $expand);
$value =& $this->get_array($data, $form_name, true); $value =& $this->get_array($data, $form_name, true);
if (true) $value = $this->format_date($value); if(true)
{
$value = $this->format_date($value);
}
} }
/** /**
@ -104,7 +110,10 @@ class Date extends Transformer
*/ */
public function format_date($value) public function format_date($value)
{ {
if (!$value) return $value; // otherwise we will get current date or 1970-01-01 instead of an empty value if(!$value)
{
return $value;
} // otherwise we will get current date or 1970-01-01 instead of an empty value
// for DateTime objects (regular PHP and Api\DateTime ones), set user timezone // for DateTime objects (regular PHP and Api\DateTime ones), set user timezone
if($value instanceof \DateTime) if($value instanceof \DateTime)
@ -158,7 +167,10 @@ class Date extends Transformer
{ {
try try
{ {
if (substr($value, -1) === 'Z') $value = substr($value, 0, -1); if(substr($value, -1) === 'Z')
{
$value = substr($value, 0, -1);
}
$date = new Api\DateTime($value); $date = new Api\DateTime($value);
} }
catch (\Exception $e) catch (\Exception $e)
@ -193,7 +205,11 @@ class Date extends Transformer
elseif(preg_match('/[+-][[:digit:]]+[ymwd]/', $this->attrs['min'])) elseif(preg_match('/[+-][[:digit:]]+[ymwd]/', $this->attrs['min']))
{ {
// Relative date with periods // Relative date with periods
$min = new Api\DateTime(strtotime(str_replace(array('y','m','w','d'), array('years','months','weeks','days'), $this->attrs['min']))); $min = new Api\DateTime(strtotime(str_replace(array('y', 'm', 'w', 'd'), array('years', 'months',
'weeks',
'days'), $this->attrs['min'])
)
);
} }
else else
{ {
@ -204,7 +220,8 @@ class Date extends Transformer
self::set_validation_error($form_name, lang( self::set_validation_error($form_name, lang(
"Value has to be at least '%1' !!!", "Value has to be at least '%1' !!!",
$min->format($this->type != 'date') $min->format($this->type != 'date')
),''); ), ''
);
$value = $min; $value = $min;
} }
} }
@ -217,7 +234,11 @@ class Date extends Transformer
elseif(preg_match('/[+-][[:digit:]]+[ymwd]/', $this->attrs['max'])) elseif(preg_match('/[+-][[:digit:]]+[ymwd]/', $this->attrs['max']))
{ {
// Relative date with periods // Relative date with periods
$max = new Api\DateTime(strtotime(str_replace(array('y','m','w','d'), array('years','months','weeks','days'), $this->attrs['max']))); $max = new Api\DateTime(strtotime(str_replace(array('y', 'm', 'w', 'd'), array('years', 'months',
'weeks',
'days'), $this->attrs['max'])
)
);
} }
else else
{ {
@ -228,7 +249,8 @@ class Date extends Transformer
self::set_validation_error($form_name, lang( self::set_validation_error($form_name, lang(
"Value has to be at maximum '%1' !!!", "Value has to be at maximum '%1' !!!",
$max->format($this->type != 'date') $max->format($this->type != 'date')
),''); ), ''
);
$value = $max; $value = $max;
} }
} }
@ -259,4 +281,5 @@ class Date extends Transformer
} }
} }
} }
\EGroupware\Api\Etemplate\Widget::registerWidget(__NAMESPACE__.'\\Date', array('time_or_date'));
\EGroupware\Api\Etemplate\Widget::registerWidget(__NAMESPACE__ . '\\Date', array('et2-date', 'time_or_date'));

View File

@ -165,7 +165,7 @@
</menulist> </menulist>
<description/> <description/>
<description value="Startdate" for="info_startdate"/> <description value="Startdate" for="info_startdate"/>
<date-time statustext="when should the ToDo or Phonecall be started, it shows up from that date in the filter open or own open (startpage)" id="info_startdate" class="et2_fullWidth"/> <et2-date statustext="when should the ToDo or Phonecall be started, it shows up from that date in the filter open or own open (startpage)" id="info_startdate" class="et2_fullWidth"></et2-date>
</row> </row>
<row class="dialogHeader3"> <row class="dialogHeader3">
<description value="Contact"/> <description value="Contact"/>

View File

@ -46,6 +46,11 @@
}, },
"dependencies": { "dependencies": {
"@andxor/jquery-ui-touch-punch-fix": "^1.0.2", "@andxor/jquery-ui-touch-punch-fix": "^1.0.2",
"@lion/button": "^0.14.2",
"@lion/core": "^0.18.2",
"@lion/input": "^0.15.4",
"@lion/input-date": "^0.12.6",
"@lion/input-datepicker": "^0.23.6",
"jquery-ui-dist": "^1.12.1", "jquery-ui-dist": "^1.12.1",
"jquery-ui-themes": "^1.12.0", "jquery-ui-themes": "^1.12.0",
"jquery-ui-timepicker-addon": "^1.6.3", "jquery-ui-timepicker-addon": "^1.6.3",