WIP URL widget for email and phone (not yet styled)

This commit is contained in:
ralf 2022-03-08 20:19:33 +02:00
parent e9fbc81565
commit 1b74f1f1a7
6 changed files with 304 additions and 6 deletions

View File

@ -143,7 +143,6 @@ function send_template()
if (!empty($matches[3])) $tag = str_replace($matches[3], '', $tag);
if ($type !== 'float') $tag .= ' precision="0"';
return $tag.'></et2-number>';
}, $str);
// fix <buttononly.../> --> <button type="buttononly".../>
@ -156,16 +155,14 @@ function send_template()
(substr($matches[4], -1) === '/' ? substr($matches[4], 0, -1) . '></et2-' . $matches[3] : $matches[4]) . '>';
}, $str);
// handling of partially implemented select and date widget (only readonly or simple select without tags or search attribute or options)
// handling of date and partially implemented select widget (no search or tags attribute), incl. removing of type attribute
$str = preg_replace_callback('#<(select|date)(-[^ ]+)? ([^>]+)/>#', static function (array $matches)
{
preg_match_all('/(^| )([a-z0-9_-]+)="([^"]+)"/', $matches[3], $attrs, PREG_PATTERN_ORDER);
$attrs = array_combine($attrs[2], $attrs[3]);
// add et2-prefix for <select-* or <date-* readonly="true"
if (isset($attrs['readonly']) && !in_array($attrs['readonly'], ['false', '0']) ||
// also add it for <date* and <select* without search or tags attribute
$matches[1] === 'date' || $matches[1] === 'select' && !isset($attrs['search']) && !isset($attrs['tags']))
// add et2-prefix for <date-* and <select-* without search or tags attribute
if ($matches[1] === 'date' || $matches[1] === 'select' && !isset($attrs['search']) && !isset($attrs['tags']))
{
// type attribute need to go in widget type <select type="select-account" --> <et2-select-account
if (empty($matches[2]) && isset($attrs['type']))
@ -178,6 +175,14 @@ function send_template()
return $matches[0];
}, $str);
// add et2- prefix to url widget, as far as it is currently implemented
$str = preg_replace_callback('#<url-(email|phone) (.*?)/>#', static function($matches)
{
if (strpos($matches[2], 'readonly="true"')) return $matches[0]; // leave readonly alone for now
return str_replace('<url-'.$matches[1], '<et2-url-'.$matches[1], substr($matches[0], 0, -2)).
'></et2-url-'.$matches[1].'>';
}, $str);
$processing = microtime(true);
if(isset($cache) && (file_exists($cache_dir = dirname($cache)) || mkdir($cache_dir, 0755, true)))

View File

@ -0,0 +1,139 @@
/**
* EGroupware eTemplate2 - InvokerMixing
*
* @license http://opensource.org/licenses/gpl-license.php GPL - GNU General Public License
* @package api
* @link https://www.egroupware.org
* @author Ralf Becker
*/
/* eslint-disable import/no-extraneous-dependencies */
import {dedupeMixin, html, render} from '@lion/core';
import {Et2InputWidget} from "../Et2InputWidget/Et2InputWidget";
/**
* Invoker mixing adds an invoker button to a widget to trigger some action, e.g.:
* - searchbox to delete input
* - url to open url
* - url-email to open mail compose
*
* Inspired by Lion date-picker.
*/
export const Et2InvokerMixin = dedupeMixin((superclass) =>
{
class Et2Invoker extends Et2InputWidget(superclass)
{
/** @type {any} */
static get properties()
{
return {
_invokerLabel: {
type: String,
},
_invokerTitle: {
type: String,
},
_invokerAction: {
type: Function,
}
};
}
get slots()
{
return {
...super.slots,
suffix: () =>
{
const renderParent = document.createElement('div');
render(
this._invokerTemplate(),
renderParent
);
return /** @type {HTMLElement} */ (renderParent.firstElementChild);
},
};
}
/**
* @protected
*/
get _invokerNode()
{
return /** @type {HTMLElement} */ (this.querySelector(`#${this.__invokerId}`));
}
constructor()
{
super();
/** @private */
this.__invokerId = this.__createUniqueIdForA11y();
// default for properties
this._invokerLabel = '⎆';
this._invokerTitle = 'Click to open';
this._invokerAction = () => alert('Invoked :)');
}
/** @private */
__createUniqueIdForA11y()
{
return `${this.localName}-${Math.random().toString(36).substr(2, 10)}`;
}
/**
* @param {PropertyKey} name
* @param {?} oldValue
*/
requestUpdate(name, oldValue)
{
super.requestUpdate(name, oldValue);
if (name === 'disabled' || name === 'showsFeedbackFor' || name === 'modelValue')
{
this._toggleInvokerDisabled();
}
}
/**
* Method to check if invoker can be activated: not disabled, empty or invalid
*
* @protected
* */
_toggleInvokerDisabled()
{
if (this._invokerNode)
{
const invokerNode = /** @type {HTMLElement & {disabled: boolean}} */ (this._invokerNode);
invokerNode.disabled = this.disabled || this._isEmpty() || this.hasFeedbackFor.length > 0;
}
}
/** @param {import('@lion/core').PropertyValues } changedProperties */
firstUpdated(changedProperties)
{
super.firstUpdated(changedProperties);
this._toggleInvokerDisabled();
}
/**
* Subclassers can replace this with their custom extension invoker,
* like `<my-button><calendar-icon></calendar-icon></my-button>`
*/
// eslint-disable-next-line class-methods-use-this
_invokerTemplate()
{
return html`
<button
type="button"
@click="${this._invokerAction}"
id="${this.__invokerId}"
aria-label="${this.egw().lang(this._invokerTitle)}"
title="${this.egw().lang(this._invokerTitle)}"
>
${this._invokerLabel}
</button>
`;
}
}
return Et2Invoker;
})

View File

@ -0,0 +1,39 @@
/**
* EGroupware eTemplate2 - Email input widget
*
* @license http://opensource.org/licenses/gpl-license.php GPL - GNU General Public License
* @package api
* @link https://www.egroupware.org
* @author Ralf Becker
*/
/* eslint-disable import/no-extraneous-dependencies */
import {Et2InvokerMixin} from "./Et2InvokerMixin";
import {IsEmail} from "../Validators/IsEmail";
import {Et2Textbox} from "../Et2Textbox/Et2Textbox";
/**
* @customElement et2-url-email
*/
export class Et2UrlEmail extends Et2InvokerMixin(Et2Textbox)
{
constructor()
{
super();
this.defaultValidators.push(new IsEmail());
this._invokerLabel = '@';
this._invokerTitle = 'Compose mail to';
this._invokerAction = () => this.__invokerAction();
}
__invokerAction()
{
if (!this._isEmpty() && !this.hasFeedbackFor.length &&
this.egw().user('apps').mail && this.egw().preference('force_mailto','addressbook') != '1' )
{
egw.open_link('mailto:'+this.value);
}
}
}
// @ts-ignore TypeScript is not recognizing that this is a LitElement
customElements.define("et2-url-email", Et2UrlEmail);

View File

@ -0,0 +1,69 @@
/**
* EGroupware eTemplate2 - Phone input widget
*
* @license http://opensource.org/licenses/gpl-license.php GPL - GNU General Public License
* @package api
* @link https://www.egroupware.org
* @author Ralf Becker
*/
/* eslint-disable import/no-extraneous-dependencies */
import {Et2InvokerMixin} from "./Et2InvokerMixin";
import {Et2Textbox} from "../Et2Textbox/Et2Textbox";
/**
* @customElement et2-url-phone
*/
export class Et2UrlPhone extends Et2InvokerMixin(Et2Textbox)
{
constructor()
{
super();
//this.defaultValidators.push(...);
this._invokerLabel = '✆';
this._invokerTitle = 'Call';
this._invokerAction = () => this.__invokerAction();
}
__invokerAction()
{
let value = this.value;
// Clean number
value = value.replace('&#9829;','').replace('(0)','');
value = value.replace(/[abc]/gi,2).replace(/[def]/gi,3).replace(/[ghi]/gi,4).replace(/[jkl]/gi,5).replace(/[mno]/gi,6);
value = value.replace(/[pqrs]/gi,7).replace(/[tuv]/gi,8).replace(/[wxyz]/gi,9);
// remove everything but numbers and plus, as telephon software might not like it
value = value.replace(/[^0-9+]/g, '');
// mobile Webkit (iPhone, Android) have precedence over server configuration!
if (navigator.userAgent.indexOf('AppleWebKit') !== -1 &&
(navigator.userAgent.indexOf("iPhone") !== -1 || navigator.userAgent.indexOf("Android") !== -1))
{
window.open("tel:"+value);
}
else if (this.egw().config("call_link"))
{
var link = this.egw().config("call_link")
// tel: links use no URL encoding according to rfc3966 section-5.1.4
.replace("%1", this.egw().config("call_link").substr(0, 4) == 'tel:' ?
value : encodeURIComponent(value))
.replace("%u",this.egw().user('account_lid'))
.replace("%t",this.egw().user('account_phone'));
var popup = this.egw().config("call_popup");
if (popup && popup !== '_self' || !link.match(/^https?:/)) // execute non-http(s) links eg. tel: like before
{
egw.open_link(link, '_phonecall', popup);
}
else
{
// No popup, use AJAX. We don't care about the response.
window.fetch(link, {
headers: { 'Content-Type': 'application/json'},
method: "GET",
});
}
}
}
}
// @ts-ignore TypeScript is not recognizing that this is a LitElement
customElements.define("et2-url-phone", Et2UrlPhone);

View File

@ -0,0 +1,44 @@
import {Pattern} from "@lion/form-core";
export class IsEmail extends Pattern
{
/**
* Regexes for validating email addresses incl. email in angle-brackets eg.
* + "Ralf Becker <rb@egroupware.org>"
* + "Ralf Becker (EGroupware GmbH) <rb@egroupware.org>"
* + "<rb@egroupware.org>" or "rb@egroupware.org"
* + '"Becker, Ralf" <rb@egroupware.org>'
* + "'Becker, Ralf' <rb@egroupware.org>"
* but NOT:
* - "Becker, Ralf <rb@egroupware.org>" (contains comma outside " or ' enclosed block)
* - "Becker < Ralf <rb@egroupware.org>" (contains < ----------- " ---------------)
*
* About umlaut or IDN domains: we currently only allow German umlauts in domain part!
* We forbid all non-ascii chars in local part, as Horde does not yet support SMTPUTF8 extension (rfc6531)
* and we get a "SMTP server does not support internationalized header data" error otherwise.
*
* Using \042 instead of " to NOT stall minifyer!
*
* Similar, but not identical, preg is in Etemplate\Widget\Url PHP class!
* We can not use "(?<![.\s])", used to check that name-part does not end in
* a dot or white-space. The expression is valid in recent Chrome, but fails
* eg. in Safari 11.0 or node.js 4.8.3 and therefore grunt uglify!
* Server-side will fail in that case because it uses the full regexp.
*/
static EMAIL_PREG : RegExp = new RegExp(/^(([^\042',<][^,<]+|\042[^\042]+\042|\'[^\']+\'|"(?:[^"\\]|\\.)*")\s?<)?[^\x00-\x20()\xe2\x80\x8b<>@,;:\042\[\]\x80-\xff]+@([a-z0-9ÄÖÜäöüß](|[a-z0-9ÄÖÜäöüß_-]*[a-z0-9ÄÖÜäöüß])\.)+[a-z]{2,}>?$/i);
constructor()
{
super(IsEmail.EMAIL_PREG);
}
/**
* Give a message about this field being required. Could be customised according to MessageData.
* @param {MessageData | undefined} data
* @returns {Promise<string>}
*/
static async getMessage(data)
{
return data.formControl.egw().lang("Invalid email");
}
}

View File

@ -46,6 +46,8 @@ import './Et2Textbox/Et2Number';
import './Et2Textbox/Et2NumberReadonly';
import './Et2Colorpicker/Et2Colorpicker';
import './Et2Taglist/Et2Taglist';
import './Et2Url/Et2UrlEmail';
import './Et2Url/Et2UrlPhone';
/* 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