Channel configuration validation + tags input

This commit is contained in:
Mehdi Benadel 2024-05-26 05:06:28 +02:00
parent 7c9e869e96
commit 35d9663559
11 changed files with 656 additions and 92 deletions

View File

@ -247,3 +247,89 @@ livechat-dynamic-table-form {
background-color: var(--bs-orange);
}
}
livechat-tags-input {
--tag-padding-vertical: 3px;
--tag-padding-horizontal: 6px;
display: flex;
align-items: flex-start;
flex-wrap: wrap;
input {
flex: 1;
border: none;
padding: var(--tag-padding-vertical) 0 0;
color: inherit;
background-color: inherit;
&:focus {
outline: transparent;
}
}
#tags {
display: flex;
flex-wrap: wrap;
padding: 0;
margin: var(--tag-padding-vertical) 0 0;
}
.tag {
width: auto;
height: 24px;
display: flex;
align-items: center;
justify-content: center;
color: #fff;
padding: 0 var(--tag-padding-horizontal);
font-size: 14px;
list-style: none;
border-radius: 3px;
margin: 0 3px 3px 0;
background: var(--bs-orange);
&,
&:active,
&:focus {
color: #fff;
background-color: var(--mainColor);
}
&:hover {
color: #fff;
background-color: var(--mainHoverColor);
}
&[disabled],
&.disabled {
cursor: default;
color: #fff;
background-color: var(--inputBorderColor);
}
.tag-name {
margin-top: 3px;
}
.tag-close {
display: block;
width: 12px;
height: 12px;
line-height: 10px;
text-align: center;
font-size: 14px;
margin-left: var(--tag-padding-horizontal);
color: var(--bs-orange);
border-radius: 50%;
background: #fff;
cursor: pointer;
}
}
@media screen and (max-width: 567px) {
.tags-input {
width: calc(100vw - 32px);
}
}
}

View File

@ -82,6 +82,9 @@ declare const LOC_LIVECHAT_CONFIGURATION_CHANNEL_BOT_NICKNAME: string
declare const LOC_LIVECHAT_CONFIGURATION_CHANNEL_FOR_MORE_INFO: string
declare const LOC_INVALID_VALUE: string
declare const LOC_INVALID_VALUE_WRONG_TYPE: string
declare const LOC_INVALID_VALUE_WRONG_FORMAT: string
declare const LOC_INVALID_VALUE_NOT_IN_RANGE: string
declare const LOC_CHATROOM_NOT_ACCESSIBLE: string
declare const LOC_PROMOTE: string

View File

@ -4,7 +4,7 @@
import type { RegisterClientOptions } from '@peertube/peertube-types/client'
import type { ChannelConfiguration } from 'shared/lib/types'
import { html } from 'lit'
import { TemplateResult, html, nothing } from 'lit'
import { customElement, property, state } from 'lit/decorators.js'
import { ptTr } from '../../lib/directives/translation'
import { Task } from '@lit/task'
@ -13,6 +13,8 @@ import { provide } from '@lit/context'
import { channelConfigurationContext, channelDetailsServiceContext } from '../contexts/channel'
import { registerClientOptionsContext } from '../../lib/contexts/peertube'
import { LivechatElement } from '../../lib/elements/livechat'
import { ValidationError, ValidationErrorType } from '../../lib/models/validation'
import { classMap } from 'lit/directives/class-map.js'
@customElement('livechat-channel-configuration')
export class ChannelConfigurationElement extends LivechatElement {
@ -31,7 +33,7 @@ export class ChannelConfigurationElement extends LivechatElement {
private _channelDetailsService?: ChannelDetailsService
@state()
public _formStatus: boolean | any = undefined
public _validationError?: ValidationError
private readonly _asyncTaskRender = new Task(this, {
task: async ([registerClientOptions]) => {
@ -49,21 +51,51 @@ export class ChannelConfigurationElement extends LivechatElement {
this._channelDetailsService.saveOptions(this._channelConfiguration.channel.id,
this._channelConfiguration.configuration)
.then(() => {
this._formStatus = { success: true }
this._validationError = undefined
this.registerClientOptions
?.peertubeHelpers.notifier.info('Livechat configuration has been properly updated.')
this.requestUpdate('_formStatus')
this.requestUpdate('_validationError')
})
.catch((error: Error) => {
console.error(`An error occurred. ${error.name}: ${error.message}`)
.catch((error: ValidationError) => {
this._validationError = error
console.warn(`A validation error occurred in saving configuration. ${error.name}: ${error.message}`)
this.registerClientOptions
?.peertubeHelpers.notifier.error(
`An error occurred. ${(error.name && error.message) ? `${error.name}: ${error.message}` : ''}`)
this.requestUpdate('_formStatus')
`An error occurred. ${(error.message) ? `${error.message}` : ''}`)
this.requestUpdate('_validationError')
})
}
}
private readonly _getInputValidationClass = (propertyName: string): { [key: string]: boolean } => {
const validationErrorTypes: ValidationErrorType[] | undefined =
this._validationError?.properties[`${propertyName}`]
return validationErrorTypes ? (validationErrorTypes.length ? { 'is-invalid': true } : { 'is-valid': true }) : {}
}
private readonly _renderFeedback = (feedbackId: string,
propertyName: string): TemplateResult | typeof nothing => {
const errorMessages: TemplateResult[] = []
const validationErrorTypes: ValidationErrorType[] | undefined =
this._validationError?.properties[`${propertyName}`] ?? undefined
if (validationErrorTypes && validationErrorTypes.length !== 0) {
if (validationErrorTypes.includes(ValidationErrorType.WrongType)) {
errorMessages.push(html`${ptTr(LOC_INVALID_VALUE_WRONG_TYPE)}`)
}
if (validationErrorTypes.includes(ValidationErrorType.WrongFormat)) {
errorMessages.push(html`${ptTr(LOC_INVALID_VALUE_WRONG_FORMAT)}`)
}
if (validationErrorTypes.includes(ValidationErrorType.NotInRange)) {
errorMessages.push(html`${ptTr(LOC_INVALID_VALUE_NOT_IN_RANGE)}`)
}
return html`<div id=${feedbackId} class="invalid-feedback">${errorMessages}</div>`
} else {
return nothing
}
}
protected override render = (): unknown => {
const tableHeaderList = {
forbiddenWords: {
@ -116,8 +148,8 @@ export class ChannelConfigurationElement extends LivechatElement {
const tableSchema = {
forbiddenWords: {
entries: {
inputType: 'textarea',
default: [''],
inputType: 'tags',
default: [],
separator: '\n'
},
regex: {
@ -144,9 +176,9 @@ export class ChannelConfigurationElement extends LivechatElement {
},
quotes: {
messages: {
inputType: 'textarea',
default: [''],
separator: '\n'
inputType: 'tags',
default: [],
separators: ['\n', '\t', ';']
},
delay: {
inputType: 'number',
@ -194,11 +226,12 @@ export class ChannelConfigurationElement extends LivechatElement {
<label>
<input
type="number"
name="slow_mode_duration"
class="form-control"
name="slowmode_duration"
class="form-control ${classMap(this._getInputValidationClass('slowMode.duration'))}"
min="0"
max="1000"
id="peertube-livechat-slow-mode-duration"
id="peertube-livechat-slowmode-duration"
aria-describedby="peertube-livechat-slowmode-duration-feedback"
@input=${(event: InputEvent) => {
if (event?.target && this._channelConfiguration) {
this._channelConfiguration.configuration.slowMode.duration =
@ -210,6 +243,7 @@ export class ChannelConfigurationElement extends LivechatElement {
value="${this._channelConfiguration?.configuration.slowMode.duration}"
/>
</label>
${this._renderFeedback('peertube-livechat-slowmode-duration-feedback', 'slowMode.duration')}
</div>
</div>
</div>
@ -244,14 +278,15 @@ export class ChannelConfigurationElement extends LivechatElement {
</div>
${this._channelConfiguration?.configuration.bot.enabled
? html`<div class="form-group">
<labelfor="peertube-livechat-bot-nickname">
<label for="peertube-livechat-bot-nickname">
${ptTr(LOC_LIVECHAT_CONFIGURATION_CHANNEL_BOT_NICKNAME)}
</label>
<input
type="text"
name="bot_nickname"
class="form-control"
class="form-control ${classMap(this._getInputValidationClass('bot.nickname'))}"
id="peertube-livechat-bot-nickname"
aria-describedby="peertube-livechat-bot-nickname-feedback"
@input=${(event: InputEvent) => {
if (event?.target && this._channelConfiguration) {
this._channelConfiguration.configuration.bot.nickname =
@ -262,6 +297,7 @@ export class ChannelConfigurationElement extends LivechatElement {
}
value="${this._channelConfiguration?.configuration.bot.nickname}"
/>
${this._renderFeedback('peertube-livechat-bot-nickname-feedback', 'bot.nickname')}
</div>`
: ''
}
@ -278,18 +314,20 @@ export class ChannelConfigurationElement extends LivechatElement {
</div>
<div class="col-12 col-lg-8 col-xl-9">
<livechat-dynamic-table-form
.header=${tableHeaderList.forbiddenWords}
.schema=${tableSchema.forbiddenWords}
.rows=${this._channelConfiguration?.configuration.bot.forbiddenWords}
@update=${(e: CustomEvent) => {
if (this._channelConfiguration) {
this._channelConfiguration.configuration.bot.forbiddenWords = e.detail
this.requestUpdate('_channelConfiguration')
}
.header=${tableHeaderList.forbiddenWords}
.schema=${tableSchema.forbiddenWords}
.validation=${this._validationError?.properties}
.validationPrefix=${'bot.forbiddenWords'}
.rows=${this._channelConfiguration?.configuration.bot.forbiddenWords}
@update=${(e: CustomEvent) => {
if (this._channelConfiguration) {
this._channelConfiguration.configuration.bot.forbiddenWords = e.detail
this.requestUpdate('_channelConfiguration')
}
}
.formName=${'forbidden-words'}>
</livechat-dynamic-table-form>
}
.formName=${'forbidden-words'}>
</livechat-dynamic-table-form>
</div>
</div>
<div class="row mt-5">
@ -304,6 +342,8 @@ export class ChannelConfigurationElement extends LivechatElement {
<livechat-dynamic-table-form
.header=${tableHeaderList.quotes}
.schema=${tableSchema.quotes}
.validation=${this._validationError?.properties}
.validationPrefix=${'bot.quotes'}
.rows=${this._channelConfiguration?.configuration.bot.quotes}
@update=${(e: CustomEvent) => {
if (this._channelConfiguration) {
@ -328,6 +368,8 @@ export class ChannelConfigurationElement extends LivechatElement {
<livechat-dynamic-table-form
.header=${tableHeaderList.commands}
.schema=${tableSchema.commands}
.validation=${this._validationError?.properties}
.validationPrefix=${'bot.commands'}
.rows=${this._channelConfiguration?.configuration.bot.commands}
@update=${(e: CustomEvent) => {
if (this._channelConfiguration) {

View File

@ -3,7 +3,9 @@
// SPDX-License-Identifier: AGPL-3.0-only
import type { RegisterClientOptions } from '@peertube/peertube-types/client'
import { ChannelLiveChatInfos, ChannelConfiguration, ChannelConfigurationOptions } from 'shared/lib/types'
import type { ValidationError } from '../../lib/models/validation'
import type { ChannelLiveChatInfos, ChannelConfiguration, ChannelConfigurationOptions } from 'shared/lib/types'
import { ValidationErrorType } from '../../lib/models/validation'
import { getBaseRoute } from '../../../utils/uri'
export class ChannelDetailsService {
@ -19,7 +21,73 @@ export class ChannelDetailsService {
}
validateOptions = (channelConfigurationOptions: ChannelConfigurationOptions): boolean => {
return !!channelConfigurationOptions
let hasErrors = false
const validationError: ValidationError = {
name: 'ChannelConfigurationOptionsValidationError',
message: 'There was an error during validation',
properties: {}
}
const botConf = channelConfigurationOptions.bot
const slowModeDuration = channelConfigurationOptions.slowMode.duration
validationError.properties['slowMode.duration'] = []
if (
(typeof slowModeDuration !== 'number') ||
isNaN(slowModeDuration)) {
validationError.properties['slowMode.duration'].push(ValidationErrorType.WrongType)
hasErrors = true
} else if (
slowModeDuration < 0 ||
slowModeDuration > 1000
) {
validationError.properties['slowMode.duration'].push(ValidationErrorType.NotInRange)
hasErrors = true
}
// If !bot.enabled, we don't have to validate these fields:
// The backend will ignore those values.
if (botConf.enabled) {
validationError.properties['bot.nickname'] = []
if (/[^\p{L}\p{N}\p{Z}_-]/u.test(botConf.nickname ?? '')) {
validationError.properties['bot.nickname'].push(ValidationErrorType.WrongFormat)
hasErrors = true
}
for (const [i, fw] of botConf.forbiddenWords.entries()) {
for (const v of fw.entries) {
validationError.properties[`bot.forbiddenWords.${i}.entries`] = []
if (fw.regexp) {
if (v.trim() !== '') {
try {
const test = new RegExp(v)
test.test(v)
} catch (_) {
validationError.properties[`bot.forbiddenWords.${i}.entries`]
.push(ValidationErrorType.WrongFormat)
hasErrors = true
}
}
}
}
}
for (const [i, cd] of botConf.commands.entries()) {
validationError.properties[`bot.commands.${i}.command`] = []
if (/\s+/.test(cd.command)) {
validationError.properties[`bot.commands.${i}.command`].push(ValidationErrorType.WrongFormat)
hasErrors = true
}
}
}
if (hasErrors) {
throw validationError
}
return true
}
saveOptions = async (channelId: number,

View File

@ -4,12 +4,16 @@
/* eslint no-fallthrough: "off" */
import type { TagsInputElement } from './tags-input'
import { ValidationErrorType } from '../models/validation'
import { html, nothing, TemplateResult } from 'lit'
import { repeat } from 'lit/directives/repeat.js'
import { customElement, property, state } from 'lit/decorators.js'
import { ifDefined } from 'lit/directives/if-defined.js'
import { unsafeHTML } from 'lit/directives/unsafe-html.js'
import { classMap } from 'lit/directives/class-map.js'
import { LivechatElement } from './livechat'
import { ptTr } from '../directives/translation'
// This content comes from the file assets/images/plus-square.svg, from the Feather icons set https://feathericons.com/
const AddSVG: string =
@ -50,6 +54,7 @@ type DynamicTableAcceptedInputTypes = 'textarea'
| 'time'
| 'url'
| 'week'
| 'tags'
interface CellDataSchema {
min?: number
@ -57,14 +62,20 @@ interface CellDataSchema {
minlength?: number
maxlength?: number
size?: number
label?: string
label?: TemplateResult | string
options?: { [key: string]: string }
datalist?: DynamicTableAcceptedTypes[]
separator?: string
separators?: string[]
inputType?: DynamicTableAcceptedInputTypes
default?: DynamicTableAcceptedTypes
}
interface DynamicTableRowData {
_id: number
_originalIndex: number
row: { [key: string]: DynamicTableAcceptedTypes }
}
@customElement('livechat-dynamic-table-form')
export class DynamicTableFormElement extends LivechatElement {
@property({ attribute: false })
@ -73,11 +84,17 @@ export class DynamicTableFormElement extends LivechatElement {
@property({ attribute: false })
public schema: { [key: string]: CellDataSchema } = {}
@property()
public validation?: {[key: string]: ValidationErrorType[] }
@property({ attribute: false })
public validationPrefix: string = ''
@property({ attribute: false })
public rows: Array<{ [key: string]: DynamicTableAcceptedTypes }> = []
@state()
public _rowsById: Array<{ _id: number, row: { [key: string]: DynamicTableAcceptedTypes } }> = []
public _rowsById: DynamicTableRowData[] = []
@property({ attribute: false })
public formName: string = ''
@ -102,7 +119,8 @@ export class DynamicTableFormElement extends LivechatElement {
private readonly _addRow = (): void => {
const newRow = this._getDefaultRow()
this._rowsById.push({ _id: this._lastRowId++, row: newRow })
// Create row and assign id and original index
this._rowsById.push({ _id: this._lastRowId++, _originalIndex: this.rows.length, row: newRow })
this.rows.push(newRow)
this.requestUpdate('rows')
this.requestUpdate('_rowsById')
@ -123,11 +141,17 @@ export class DynamicTableFormElement extends LivechatElement {
this._updateLastRowId()
// Filter removed rows
this._rowsById.filter(rowById => this.rows.includes(rowById.row))
for (const row of this.rows) {
if (this._rowsById.filter(rowById => rowById.row === row).length === 0) {
this._rowsById.push({ _id: this._lastRowId++, row })
for (let i = 0; i < this.rows.length; i++) {
if (this._rowsById.filter(rowById => rowById.row === this.rows[i]).length === 0) {
// Add row and assign id
this._rowsById.push({ _id: this._lastRowId++, _originalIndex: i, row: this.rows[i] })
} else {
// Update index in case it changed
this._rowsById.filter(rowById => rowById.row === this.rows[i])
.forEach((value) => { value._originalIndex = i })
}
}
@ -169,14 +193,16 @@ export class DynamicTableFormElement extends LivechatElement {
</th>`
}
private readonly _renderDataRow = (rowData: { _id: number
row: {[key: string]: DynamicTableAcceptedTypes} }): TemplateResult => {
private readonly _renderDataRow = (rowData: DynamicTableRowData): TemplateResult => {
const inputId = `peertube-livechat-${this.formName.replace(/_/g, '-')}-row-${rowData._id}`
return html`<tr id=${inputId}>
${Object.keys(this.header)
.sort((k1, k2) => this.columnOrder.indexOf(k1) - this.columnOrder.indexOf(k2))
.map(k => this.renderDataCell([k, rowData.row[k] ?? this.schema[k].default], rowData._id))}
.map(key => this.renderDataCell(key,
rowData.row[key] ?? this.schema[key].default,
rowData._id,
rowData._originalIndex))}
<td class="form-group">
<button type="button"
class="peertube-button-link orange-button dynamic-table-remove-row"
@ -202,8 +228,10 @@ export class DynamicTableFormElement extends LivechatElement {
</tfoot>`
}
renderDataCell = (property: [string, DynamicTableAcceptedTypes], rowId: number): TemplateResult => {
let [propertyName, propertyValue] = property
renderDataCell = (propertyName: string,
propertyValue: DynamicTableAcceptedTypes,
rowId: number,
originalIndex: number): TemplateResult => {
const propertySchema = this.schema[propertyName] ?? {}
let formElement
@ -212,6 +240,8 @@ export class DynamicTableFormElement extends LivechatElement {
const inputId =
`peertube-livechat-${this.formName.replace(/_/g, '-')}-${propertyName.toString().replace(/_/g, '-')}-${rowId}`
const feedback = this._renderFeedback(inputId, propertyName, originalIndex)
switch (propertySchema.default?.constructor) {
case String:
switch (propertySchema.inputType) {
@ -234,30 +264,39 @@ export class DynamicTableFormElement extends LivechatElement {
case 'time':
case 'url':
case 'week':
formElement = this._renderInput(rowId,
formElement = html`${this._renderInput(rowId,
inputId,
inputName,
propertyName,
propertySchema,
propertyValue as string)
propertyValue as string,
originalIndex)}
${feedback}
`
break
case 'textarea':
formElement = this._renderTextarea(rowId,
formElement = html`${this._renderTextarea(rowId,
inputId,
inputName,
propertyName,
propertySchema,
propertyValue as string)
propertyValue as string,
originalIndex)}
${feedback}
`
break
case 'select':
formElement = this._renderSelect(rowId,
formElement = html`${this._renderSelect(rowId,
inputId,
inputName,
propertyName,
propertySchema,
propertyValue as string)
propertyValue as string,
originalIndex)}
${feedback}
`
break
}
break
@ -271,12 +310,15 @@ export class DynamicTableFormElement extends LivechatElement {
case 'datetime':
case 'datetime-local':
case 'time':
formElement = this._renderInput(rowId,
formElement = html`${this._renderInput(rowId,
inputId,
inputName,
propertyName,
propertySchema,
(propertyValue as Date).toISOString())
(propertyValue as Date).toISOString(),
originalIndex)}
${feedback}
`
break
}
break
@ -288,12 +330,15 @@ export class DynamicTableFormElement extends LivechatElement {
case 'number':
case 'range':
formElement = this._renderInput(rowId,
formElement = html`${this._renderInput(rowId,
inputId,
inputName,
propertyName,
propertySchema,
propertyValue as string)
propertyValue as string,
originalIndex)}
${feedback}
`
break
}
break
@ -304,12 +349,15 @@ export class DynamicTableFormElement extends LivechatElement {
propertySchema.inputType = 'checkbox'
case 'checkbox':
formElement = this._renderCheckbox(rowId,
formElement = html`${this._renderCheckbox(rowId,
inputId,
inputName,
propertyName,
propertySchema,
propertyValue as boolean)
propertyValue as boolean,
originalIndex)}
${feedback}
`
break
}
break
@ -338,15 +386,45 @@ export class DynamicTableFormElement extends LivechatElement {
if (propertyValue.constructor !== Array) {
propertyValue = (propertyValue) ? [propertyValue as (number | string)] : []
}
formElement = this._renderInput(rowId, inputId, inputName, propertyName, propertySchema,
(propertyValue)?.join(propertySchema.separator ?? ',') ?? propertyValue ?? propertySchema.default ?? '')
formElement = html`${this._renderInput(rowId,
inputId,
inputName,
propertyName,
propertySchema,
(propertyValue)?.join(propertySchema.separators?.[0] ?? ',') ??
propertyValue ?? propertySchema.default ?? '',
originalIndex)}
${feedback}
`
break
case 'textarea':
if (propertyValue.constructor !== Array) {
propertyValue = (propertyValue) ? [propertyValue as (number | string)] : []
}
formElement = this._renderTextarea(rowId, inputId, inputName, propertyName, propertySchema,
(propertyValue)?.join(propertySchema.separator ?? ',') ?? propertyValue ?? propertySchema.default ?? '')
formElement = html`${this._renderTextarea(rowId,
inputId,
inputName,
propertyName,
propertySchema,
(propertyValue)?.join(propertySchema.separators?.[0] ?? ',') ??
propertyValue ?? propertySchema.default ?? '',
originalIndex)}
${feedback}
`
break
case 'tags':
if (propertyValue.constructor !== Array) {
propertyValue = (propertyValue) ? [propertyValue as (number | string)] : []
}
formElement = html`${this._renderTagsInput(rowId,
inputId,
inputName,
propertyName,
propertySchema,
propertyValue,
originalIndex)}
${feedback}
`
break
}
}
@ -364,12 +442,14 @@ export class DynamicTableFormElement extends LivechatElement {
inputName: string,
propertyName: string,
propertySchema: CellDataSchema,
propertyValue: string): TemplateResult => {
propertyValue: string,
originalIndex: number): TemplateResult => {
return html`<input
type=${propertySchema.inputType}
name=${inputName}
class="form-control"
class="form-control ${classMap(this._getInputValidationClass(propertyName, originalIndex))}"
id=${inputId}
aria-describedby="${inputId}-feedback"
list=${(propertySchema.datalist) ? inputId + '-datalist' : nothing}
min=${ifDefined(propertySchema.min)}
max=${ifDefined(propertySchema.max)}
@ -382,8 +462,31 @@ export class DynamicTableFormElement extends LivechatElement {
? html`<datalist id=${inputId + '-datalist'}>
${(propertySchema.datalist ?? []).map((value) => html`<option value=${value}>`)}
</datalist>`
: nothing}
`
: nothing}`
}
_renderTagsInput = (rowId: number,
inputId: string,
inputName: string,
propertyName: string,
propertySchema: CellDataSchema,
propertyValue: Array<string | number>,
originalIndex: number): TemplateResult => {
return html`<livechat-tags-input
.type=${'text'}
.name=${inputName}
class="form-control ${classMap(this._getInputValidationClass(propertyName, originalIndex))}"
id=${inputId}
.inputPlaceholder=${ifDefined(propertySchema.label)}
aria-describedby="${inputId}-feedback"
.min=${ifDefined(propertySchema.min)}
.max=${ifDefined(propertySchema.max)}
.minlength=${ifDefined(propertySchema.minlength)}
.maxlength=${ifDefined(propertySchema.maxlength)}
.datalist=${ifDefined(propertySchema.datalist)}
.separators=${ifDefined(propertySchema.separators)}
@change=${(event: Event) => this._updatePropertyFromValue(event, propertyName, propertySchema, rowId)}
.value=${propertyValue}></livechat-tags-input>`
}
_renderTextarea = (rowId: number,
@ -391,18 +494,19 @@ export class DynamicTableFormElement extends LivechatElement {
inputName: string,
propertyName: string,
propertySchema: CellDataSchema,
propertyValue: string): TemplateResult => {
propertyValue: string,
originalIndex: number): TemplateResult => {
return html`<textarea
name=${inputName}
class="form-control"
class="form-control ${classMap(this._getInputValidationClass(propertyName, originalIndex))}"
id=${inputId}
aria-describedby="${inputId}-feedback"
min=${ifDefined(propertySchema.min)}
max=${ifDefined(propertySchema.max)}
minlength=${ifDefined(propertySchema.minlength)}
maxlength=${ifDefined(propertySchema.maxlength)}
@change=${(event: Event) => this._updatePropertyFromValue(event, propertyName, propertySchema, rowId)}
.value=${propertyValue}
></textarea>`
.value=${propertyValue}></textarea>`
}
_renderCheckbox = (rowId: number,
@ -410,16 +514,17 @@ export class DynamicTableFormElement extends LivechatElement {
inputName: string,
propertyName: string,
propertySchema: CellDataSchema,
propertyValue: boolean): TemplateResult => {
propertyValue: boolean,
originalIndex: number): TemplateResult => {
return html`<input
type="checkbox"
name=${inputName}
class="form-check-input"
class="form-check-input ${classMap(this._getInputValidationClass(propertyName, originalIndex))}"
id=${inputId}
aria-describedby="${inputId}-feedback"
@change=${(event: Event) => this._updatePropertyFromValue(event, propertyName, propertySchema, rowId)}
.value=${propertyValue}
?checked=${propertyValue}
/>`
?checked=${propertyValue} />`
}
_renderSelect = (rowId: number,
@ -427,10 +532,13 @@ export class DynamicTableFormElement extends LivechatElement {
inputName: string,
propertyName: string,
propertySchema: CellDataSchema,
propertyValue: string): TemplateResult => {
propertyValue: string,
originalIndex: number): TemplateResult => {
return html`<select
class="form-select"
aria-label="Default select example"
class="form-select ${classMap(this._getInputValidationClass(propertyName, originalIndex))}"
id=${inputId}
aria-describedby="${inputId}-feedback"
aria-label=${inputName}
@change=${(event: Event) => this._updatePropertyFromValue(event, propertyName, propertySchema, rowId)}
>
<option ?selected=${!propertyValue}>${propertySchema.label ?? 'Choose your option'}</option>
@ -441,23 +549,64 @@ export class DynamicTableFormElement extends LivechatElement {
</select>`
}
_getInputValidationClass = (propertyName: string,
originalIndex: number): { [key: string]: boolean } => {
const validationErrorTypes: ValidationErrorType[] | undefined =
this.validation?.[`${this.validationPrefix}.${originalIndex}.${propertyName}`]
return validationErrorTypes !== undefined
? (validationErrorTypes.length ? { 'is-invalid': true } : { 'is-valid': true })
: {}
}
_renderFeedback = (inputId: string,
propertyName: string,
originalIndex: number): TemplateResult | typeof nothing => {
const errorMessages: TemplateResult[] = []
const validationErrorTypes: ValidationErrorType[] | undefined =
this.validation?.[`${this.validationPrefix}.${originalIndex}.${propertyName}`]
if (validationErrorTypes !== undefined && validationErrorTypes.length !== 0) {
if (validationErrorTypes.includes(ValidationErrorType.WrongType)) {
errorMessages.push(html`${ptTr(LOC_INVALID_VALUE_WRONG_TYPE)}`)
}
if (validationErrorTypes.includes(ValidationErrorType.WrongFormat)) {
errorMessages.push(html`${ptTr(LOC_INVALID_VALUE_WRONG_FORMAT)}`)
}
if (validationErrorTypes.includes(ValidationErrorType.NotInRange)) {
errorMessages.push(html`${ptTr(LOC_INVALID_VALUE_NOT_IN_RANGE)}`)
}
return html`<div id="${inputId}-feedback" class="invalid-feedback">${errorMessages}</div>`
} else {
return nothing
}
}
_updatePropertyFromValue = (event: Event,
propertyName: string,
propertySchema: CellDataSchema,
rowId: number): void => {
const target = event.target as (HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement)
const target = event.target as (TagsInputElement | HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement)
const value = (target)
? (target instanceof HTMLInputElement && target.type === 'checkbox')
? !!(target.checked)
: target.value
: undefined
console.log(`value: ${JSON.stringify(value)}`)
if (value !== undefined) {
for (const rowById of this._rowsById) {
if (rowById._id === rowId) {
switch (propertySchema.default?.constructor) {
case Array:
rowById.row[propertyName] = (value as string).split(propertySchema.separator ?? ',')
if (value.constructor === Array) {
rowById.row[propertyName] = value
} else {
rowById.row[propertyName] = (value as string)
.split(new RegExp(`/[${propertySchema.separators?.join('') ?? ''}]+/`))
}
break
default:
rowById.row[propertyName] = value

View File

@ -6,3 +6,4 @@
import './help-button'
import './dynamic-table-form'
import './configuration-row'
import './tags-input'

View File

@ -0,0 +1,193 @@
// SPDX-FileCopyrightText: 2024 Mehdi Benadel <https://mehdibenadel.com>
//
// SPDX-License-Identifier: AGPL-3.0-only
import { html } from 'lit'
import { customElement, property } from 'lit/decorators.js'
import { LivechatElement } from './livechat'
import { ifDefined } from 'lit/directives/if-defined.js'
@customElement('livechat-tags-input')
export class TagsInputElement extends LivechatElement {
@property({ attribute: false })
public type?: string = 'text'
@property({ attribute: false })
public name?: string
@property({ attribute: false })
public min?: string
@property({ attribute: false })
public max?: string
@property({ attribute: false })
public maxlength?: string
@property({ attribute: false })
public minlength?: string
public _inputValue?: string = ''
@property({ attribute: false })
public inputPlaceholder?: string = ''
@property({ attribute: false })
public datalist?: Array<string | number>
@property({ reflect: true })
public value: Array<string | number> = []
@property({ attribute: false })
public separators?: string[] = []
protected override render = (): unknown => {
return html`<ul id="tags">
${this.value.map((tag, index) => html`<li key=${index} class="tag">
<span class='tag-name'>${tag}</span>
<span class='tag-close'
@click=${() => this._removeTag(index)}>
x
</span>
</li>`
)}
</ul>
<input
type=${ifDefined(this.type)}
name=${ifDefined(this.name)}
id="${this.id ?? 'tags-input'}-input"
list="${this.id ?? 'tags-input'}-input-datalist"
min=${ifDefined(this.min)}
max=${ifDefined(this.max)}
minlength=${ifDefined(this.minlength)}
maxlength=${ifDefined(this.maxlength)}
@paste=${(e: ClipboardEvent) => this._handlePaste(e)}
@keydown=${(e: KeyboardEvent) => this._handleKeyboardEvent(e)}
@input=${(e: InputEvent) => this._handleInputEvent(e)}
@change=${(e: Event) => e.stopPropagation()}
.value=${this._inputValue} .placeholder=${this.inputPlaceholder} />
${(this.datalist)
? html`<datalist id="${this.id ?? 'tags-input'}-datalist">
${(this.datalist ?? []).map((value) => html`<option value=${value}>`)}
</datalist>`
: ''
}`
}
private readonly _handlePaste = (e: ClipboardEvent): boolean => {
const target = e?.target as HTMLInputElement
const pastedValue = `${target?.value ?? ''}${e.clipboardData?.getData('text/plain') ?? ''}`
if (target) {
e.preventDefault()
let values = pastedValue.split(new RegExp(`/[${this.separators?.join('') ?? ''}]+/`))
values = values.map(v => v.trim()).filter(v => v !== '')
if (values.length > 0) {
// Keep last value in input if paste doesn't finish with a separator
if (!this.separators?.some(separator => target?.value.match(/\s+$/m)?.[0]?.includes(separator))) {
target.value = values.pop() ?? ''
} else {
target.value = ''
}
// no duplicate
this.value = [...new Set([...this.value, ...values])]
console.log(`value: ${JSON.stringify(this.value)}`)
this.requestUpdate('value')
this.dispatchEvent(new CustomEvent('change', { detail: this.value }))
return false
}
}
return true
}
private readonly _handleKeyboardEvent = (e: KeyboardEvent): boolean => {
const target = e?.target as HTMLInputElement
if (target) {
switch (e.key) {
case 'Enter':
if (target.value === '') {
return true
} else {
e.preventDefault()
this._handleNewTag(e)
return false
}
case 'Backspace':
case 'Delete':
if (target.value === '') {
this._removeTag(this.value.length - 1)
}
break
default:
break
}
}
return true
}
private readonly _handleInputEvent = (e: InputEvent): boolean => {
const target = e?.target as HTMLInputElement
if (target) {
if (this.separators?.includes(target.value.slice(-1))) {
e.preventDefault()
target.value = target.value.slice(0, -1)
this._handleNewTag(e)
return false
}
}
return true
}
private readonly _handleNewTag = (e: Event): void => {
const target = e?.target as HTMLInputElement
if (target) {
this._addTag(target?.value)
target.value = ''
}
}
private readonly _addTag = (value: string | undefined): void => {
if (value === undefined) {
console.warn('Could not add tag : Target or value was undefined')
return
}
value = value.trim()
if (value) {
this.value.push(value)
// no duplicate
this.value = [...new Set(this.value)]
console.log(`value: ${JSON.stringify(this.value)}`)
this.requestUpdate('value')
this.dispatchEvent(new CustomEvent('change', { detail: this.value }))
}
}
private readonly _removeTag = (index: number): void => {
if (index < 0 || index >= this.value.length) {
console.warn('Could not remove tag : index out of range')
return
}
this.value.splice(index, 1)
console.log(`value: ${JSON.stringify(this.value)}`)
this.requestUpdate('value')
this.dispatchEvent(new CustomEvent('change', { detail: this.value }))
}
}

View File

@ -0,0 +1,13 @@
// SPDX-FileCopyrightText: 2024 Mehdi Benadel <https://mehdibenadel.com>
//
// SPDX-License-Identifier: AGPL-3.0-only
export enum ValidationErrorType {
WrongType,
WrongFormat,
NotInRange,
}
export class ValidationError extends Error {
properties: {[key: string]: ValidationErrorType[] } = {}
}

View File

@ -3,7 +3,7 @@
"experimentalDecorators": true,
"module": "es6",
"moduleResolution": "node",
"target": "es5",
"target": "es6",
"allowJs": true,
"sourceMap": true,
"forceConsistentCasingInFileNames": true,

View File

@ -435,6 +435,9 @@ livechat_configuration_channel_banned_jids_label: "Banned users and patterns"
livechat_configuration_channel_bot_nickname: "Bot nickname"
invalid_value: "Invalid value."
invalid_value_wrong_type: "Value is of the wrong type."
invalid_value_wrong_format: "Value is in the wrong format."
invalid_value_not_in_range: "Value is not in authorized range."
slow_mode_info: "Slow mode is enabled, users can send a message every %1$s seconds."

View File

@ -92,22 +92,9 @@ interface ChannelConfigurationOptions {
bot: {
enabled: boolean
nickname?: string
forbiddenWords: Array<{
entries: string[]
regexp?: boolean
applyToModerators?: boolean
label?: string
reason?: string
comments?: string
}>
quotes: Array<{
messages: string[]
delay: number
}>
commands: Array<{
command: string
message: string
}>
forbiddenWords: ChannelForbiddenWords[]
quotes: ChannelQuotes[]
commands: ChannelCommands[]
// TODO: bannedJIDs: string[]
}
slowMode: {
@ -115,6 +102,25 @@ interface ChannelConfigurationOptions {
}
}
interface ChannelForbiddenWords {
entries: string[]
regexp?: boolean
applyToModerators?: boolean
label?: string
reason?: string
comments?: string
}
interface ChannelQuotes {
messages: string[]
delay: number
}
interface ChannelCommands {
command: string
message: string
}
interface ChannelConfiguration {
channel: ChannelInfos
configuration: ChannelConfigurationOptions