Channel configuration validation + tags input
This commit is contained in:
parent
7c9e869e96
commit
35d9663559
@ -247,3 +247,89 @@ livechat-dynamic-table-form {
|
|||||||
background-color: var(--bs-orange);
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
3
client/@types/global.d.ts
vendored
3
client/@types/global.d.ts
vendored
@ -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_LIVECHAT_CONFIGURATION_CHANNEL_FOR_MORE_INFO: string
|
||||||
|
|
||||||
declare const LOC_INVALID_VALUE: 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_CHATROOM_NOT_ACCESSIBLE: string
|
||||||
|
|
||||||
declare const LOC_PROMOTE: string
|
declare const LOC_PROMOTE: string
|
||||||
|
@ -4,7 +4,7 @@
|
|||||||
|
|
||||||
import type { RegisterClientOptions } from '@peertube/peertube-types/client'
|
import type { RegisterClientOptions } from '@peertube/peertube-types/client'
|
||||||
import type { ChannelConfiguration } from 'shared/lib/types'
|
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 { customElement, property, state } from 'lit/decorators.js'
|
||||||
import { ptTr } from '../../lib/directives/translation'
|
import { ptTr } from '../../lib/directives/translation'
|
||||||
import { Task } from '@lit/task'
|
import { Task } from '@lit/task'
|
||||||
@ -13,6 +13,8 @@ import { provide } from '@lit/context'
|
|||||||
import { channelConfigurationContext, channelDetailsServiceContext } from '../contexts/channel'
|
import { channelConfigurationContext, channelDetailsServiceContext } from '../contexts/channel'
|
||||||
import { registerClientOptionsContext } from '../../lib/contexts/peertube'
|
import { registerClientOptionsContext } from '../../lib/contexts/peertube'
|
||||||
import { LivechatElement } from '../../lib/elements/livechat'
|
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')
|
@customElement('livechat-channel-configuration')
|
||||||
export class ChannelConfigurationElement extends LivechatElement {
|
export class ChannelConfigurationElement extends LivechatElement {
|
||||||
@ -31,7 +33,7 @@ export class ChannelConfigurationElement extends LivechatElement {
|
|||||||
private _channelDetailsService?: ChannelDetailsService
|
private _channelDetailsService?: ChannelDetailsService
|
||||||
|
|
||||||
@state()
|
@state()
|
||||||
public _formStatus: boolean | any = undefined
|
public _validationError?: ValidationError
|
||||||
|
|
||||||
private readonly _asyncTaskRender = new Task(this, {
|
private readonly _asyncTaskRender = new Task(this, {
|
||||||
task: async ([registerClientOptions]) => {
|
task: async ([registerClientOptions]) => {
|
||||||
@ -49,21 +51,51 @@ export class ChannelConfigurationElement extends LivechatElement {
|
|||||||
this._channelDetailsService.saveOptions(this._channelConfiguration.channel.id,
|
this._channelDetailsService.saveOptions(this._channelConfiguration.channel.id,
|
||||||
this._channelConfiguration.configuration)
|
this._channelConfiguration.configuration)
|
||||||
.then(() => {
|
.then(() => {
|
||||||
this._formStatus = { success: true }
|
this._validationError = undefined
|
||||||
this.registerClientOptions
|
this.registerClientOptions
|
||||||
?.peertubeHelpers.notifier.info('Livechat configuration has been properly updated.')
|
?.peertubeHelpers.notifier.info('Livechat configuration has been properly updated.')
|
||||||
this.requestUpdate('_formStatus')
|
this.requestUpdate('_validationError')
|
||||||
})
|
})
|
||||||
.catch((error: Error) => {
|
.catch((error: ValidationError) => {
|
||||||
console.error(`An error occurred. ${error.name}: ${error.message}`)
|
this._validationError = error
|
||||||
|
console.warn(`A validation error occurred in saving configuration. ${error.name}: ${error.message}`)
|
||||||
this.registerClientOptions
|
this.registerClientOptions
|
||||||
?.peertubeHelpers.notifier.error(
|
?.peertubeHelpers.notifier.error(
|
||||||
`An error occurred. ${(error.name && error.message) ? `${error.name}: ${error.message}` : ''}`)
|
`An error occurred. ${(error.message) ? `${error.message}` : ''}`)
|
||||||
this.requestUpdate('_formStatus')
|
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 => {
|
protected override render = (): unknown => {
|
||||||
const tableHeaderList = {
|
const tableHeaderList = {
|
||||||
forbiddenWords: {
|
forbiddenWords: {
|
||||||
@ -116,8 +148,8 @@ export class ChannelConfigurationElement extends LivechatElement {
|
|||||||
const tableSchema = {
|
const tableSchema = {
|
||||||
forbiddenWords: {
|
forbiddenWords: {
|
||||||
entries: {
|
entries: {
|
||||||
inputType: 'textarea',
|
inputType: 'tags',
|
||||||
default: [''],
|
default: [],
|
||||||
separator: '\n'
|
separator: '\n'
|
||||||
},
|
},
|
||||||
regex: {
|
regex: {
|
||||||
@ -144,9 +176,9 @@ export class ChannelConfigurationElement extends LivechatElement {
|
|||||||
},
|
},
|
||||||
quotes: {
|
quotes: {
|
||||||
messages: {
|
messages: {
|
||||||
inputType: 'textarea',
|
inputType: 'tags',
|
||||||
default: [''],
|
default: [],
|
||||||
separator: '\n'
|
separators: ['\n', '\t', ';']
|
||||||
},
|
},
|
||||||
delay: {
|
delay: {
|
||||||
inputType: 'number',
|
inputType: 'number',
|
||||||
@ -194,11 +226,12 @@ export class ChannelConfigurationElement extends LivechatElement {
|
|||||||
<label>
|
<label>
|
||||||
<input
|
<input
|
||||||
type="number"
|
type="number"
|
||||||
name="slow_mode_duration"
|
name="slowmode_duration"
|
||||||
class="form-control"
|
class="form-control ${classMap(this._getInputValidationClass('slowMode.duration'))}"
|
||||||
min="0"
|
min="0"
|
||||||
max="1000"
|
max="1000"
|
||||||
id="peertube-livechat-slow-mode-duration"
|
id="peertube-livechat-slowmode-duration"
|
||||||
|
aria-describedby="peertube-livechat-slowmode-duration-feedback"
|
||||||
@input=${(event: InputEvent) => {
|
@input=${(event: InputEvent) => {
|
||||||
if (event?.target && this._channelConfiguration) {
|
if (event?.target && this._channelConfiguration) {
|
||||||
this._channelConfiguration.configuration.slowMode.duration =
|
this._channelConfiguration.configuration.slowMode.duration =
|
||||||
@ -210,6 +243,7 @@ export class ChannelConfigurationElement extends LivechatElement {
|
|||||||
value="${this._channelConfiguration?.configuration.slowMode.duration}"
|
value="${this._channelConfiguration?.configuration.slowMode.duration}"
|
||||||
/>
|
/>
|
||||||
</label>
|
</label>
|
||||||
|
${this._renderFeedback('peertube-livechat-slowmode-duration-feedback', 'slowMode.duration')}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@ -244,14 +278,15 @@ export class ChannelConfigurationElement extends LivechatElement {
|
|||||||
</div>
|
</div>
|
||||||
${this._channelConfiguration?.configuration.bot.enabled
|
${this._channelConfiguration?.configuration.bot.enabled
|
||||||
? html`<div class="form-group">
|
? html`<div class="form-group">
|
||||||
<labelfor="peertube-livechat-bot-nickname">
|
<label for="peertube-livechat-bot-nickname">
|
||||||
${ptTr(LOC_LIVECHAT_CONFIGURATION_CHANNEL_BOT_NICKNAME)}
|
${ptTr(LOC_LIVECHAT_CONFIGURATION_CHANNEL_BOT_NICKNAME)}
|
||||||
</label>
|
</label>
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
name="bot_nickname"
|
name="bot_nickname"
|
||||||
class="form-control"
|
class="form-control ${classMap(this._getInputValidationClass('bot.nickname'))}"
|
||||||
id="peertube-livechat-bot-nickname"
|
id="peertube-livechat-bot-nickname"
|
||||||
|
aria-describedby="peertube-livechat-bot-nickname-feedback"
|
||||||
@input=${(event: InputEvent) => {
|
@input=${(event: InputEvent) => {
|
||||||
if (event?.target && this._channelConfiguration) {
|
if (event?.target && this._channelConfiguration) {
|
||||||
this._channelConfiguration.configuration.bot.nickname =
|
this._channelConfiguration.configuration.bot.nickname =
|
||||||
@ -262,6 +297,7 @@ export class ChannelConfigurationElement extends LivechatElement {
|
|||||||
}
|
}
|
||||||
value="${this._channelConfiguration?.configuration.bot.nickname}"
|
value="${this._channelConfiguration?.configuration.bot.nickname}"
|
||||||
/>
|
/>
|
||||||
|
${this._renderFeedback('peertube-livechat-bot-nickname-feedback', 'bot.nickname')}
|
||||||
</div>`
|
</div>`
|
||||||
: ''
|
: ''
|
||||||
}
|
}
|
||||||
@ -278,18 +314,20 @@ export class ChannelConfigurationElement extends LivechatElement {
|
|||||||
</div>
|
</div>
|
||||||
<div class="col-12 col-lg-8 col-xl-9">
|
<div class="col-12 col-lg-8 col-xl-9">
|
||||||
<livechat-dynamic-table-form
|
<livechat-dynamic-table-form
|
||||||
.header=${tableHeaderList.forbiddenWords}
|
.header=${tableHeaderList.forbiddenWords}
|
||||||
.schema=${tableSchema.forbiddenWords}
|
.schema=${tableSchema.forbiddenWords}
|
||||||
.rows=${this._channelConfiguration?.configuration.bot.forbiddenWords}
|
.validation=${this._validationError?.properties}
|
||||||
@update=${(e: CustomEvent) => {
|
.validationPrefix=${'bot.forbiddenWords'}
|
||||||
if (this._channelConfiguration) {
|
.rows=${this._channelConfiguration?.configuration.bot.forbiddenWords}
|
||||||
this._channelConfiguration.configuration.bot.forbiddenWords = e.detail
|
@update=${(e: CustomEvent) => {
|
||||||
this.requestUpdate('_channelConfiguration')
|
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>
|
</div>
|
||||||
<div class="row mt-5">
|
<div class="row mt-5">
|
||||||
@ -304,6 +342,8 @@ export class ChannelConfigurationElement extends LivechatElement {
|
|||||||
<livechat-dynamic-table-form
|
<livechat-dynamic-table-form
|
||||||
.header=${tableHeaderList.quotes}
|
.header=${tableHeaderList.quotes}
|
||||||
.schema=${tableSchema.quotes}
|
.schema=${tableSchema.quotes}
|
||||||
|
.validation=${this._validationError?.properties}
|
||||||
|
.validationPrefix=${'bot.quotes'}
|
||||||
.rows=${this._channelConfiguration?.configuration.bot.quotes}
|
.rows=${this._channelConfiguration?.configuration.bot.quotes}
|
||||||
@update=${(e: CustomEvent) => {
|
@update=${(e: CustomEvent) => {
|
||||||
if (this._channelConfiguration) {
|
if (this._channelConfiguration) {
|
||||||
@ -328,6 +368,8 @@ export class ChannelConfigurationElement extends LivechatElement {
|
|||||||
<livechat-dynamic-table-form
|
<livechat-dynamic-table-form
|
||||||
.header=${tableHeaderList.commands}
|
.header=${tableHeaderList.commands}
|
||||||
.schema=${tableSchema.commands}
|
.schema=${tableSchema.commands}
|
||||||
|
.validation=${this._validationError?.properties}
|
||||||
|
.validationPrefix=${'bot.commands'}
|
||||||
.rows=${this._channelConfiguration?.configuration.bot.commands}
|
.rows=${this._channelConfiguration?.configuration.bot.commands}
|
||||||
@update=${(e: CustomEvent) => {
|
@update=${(e: CustomEvent) => {
|
||||||
if (this._channelConfiguration) {
|
if (this._channelConfiguration) {
|
||||||
|
@ -3,7 +3,9 @@
|
|||||||
// SPDX-License-Identifier: AGPL-3.0-only
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
import type { RegisterClientOptions } from '@peertube/peertube-types/client'
|
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'
|
import { getBaseRoute } from '../../../utils/uri'
|
||||||
|
|
||||||
export class ChannelDetailsService {
|
export class ChannelDetailsService {
|
||||||
@ -19,7 +21,73 @@ export class ChannelDetailsService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
validateOptions = (channelConfigurationOptions: ChannelConfigurationOptions): boolean => {
|
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,
|
saveOptions = async (channelId: number,
|
||||||
|
@ -4,12 +4,16 @@
|
|||||||
|
|
||||||
/* eslint no-fallthrough: "off" */
|
/* eslint no-fallthrough: "off" */
|
||||||
|
|
||||||
|
import type { TagsInputElement } from './tags-input'
|
||||||
|
import { ValidationErrorType } from '../models/validation'
|
||||||
import { html, nothing, TemplateResult } from 'lit'
|
import { html, nothing, TemplateResult } from 'lit'
|
||||||
import { repeat } from 'lit/directives/repeat.js'
|
import { repeat } from 'lit/directives/repeat.js'
|
||||||
import { customElement, property, state } from 'lit/decorators.js'
|
import { customElement, property, state } from 'lit/decorators.js'
|
||||||
import { ifDefined } from 'lit/directives/if-defined.js'
|
import { ifDefined } from 'lit/directives/if-defined.js'
|
||||||
import { unsafeHTML } from 'lit/directives/unsafe-html.js'
|
import { unsafeHTML } from 'lit/directives/unsafe-html.js'
|
||||||
|
import { classMap } from 'lit/directives/class-map.js'
|
||||||
import { LivechatElement } from './livechat'
|
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/
|
// This content comes from the file assets/images/plus-square.svg, from the Feather icons set https://feathericons.com/
|
||||||
const AddSVG: string =
|
const AddSVG: string =
|
||||||
@ -50,6 +54,7 @@ type DynamicTableAcceptedInputTypes = 'textarea'
|
|||||||
| 'time'
|
| 'time'
|
||||||
| 'url'
|
| 'url'
|
||||||
| 'week'
|
| 'week'
|
||||||
|
| 'tags'
|
||||||
|
|
||||||
interface CellDataSchema {
|
interface CellDataSchema {
|
||||||
min?: number
|
min?: number
|
||||||
@ -57,14 +62,20 @@ interface CellDataSchema {
|
|||||||
minlength?: number
|
minlength?: number
|
||||||
maxlength?: number
|
maxlength?: number
|
||||||
size?: number
|
size?: number
|
||||||
label?: string
|
label?: TemplateResult | string
|
||||||
options?: { [key: string]: string }
|
options?: { [key: string]: string }
|
||||||
datalist?: DynamicTableAcceptedTypes[]
|
datalist?: DynamicTableAcceptedTypes[]
|
||||||
separator?: string
|
separators?: string[]
|
||||||
inputType?: DynamicTableAcceptedInputTypes
|
inputType?: DynamicTableAcceptedInputTypes
|
||||||
default?: DynamicTableAcceptedTypes
|
default?: DynamicTableAcceptedTypes
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface DynamicTableRowData {
|
||||||
|
_id: number
|
||||||
|
_originalIndex: number
|
||||||
|
row: { [key: string]: DynamicTableAcceptedTypes }
|
||||||
|
}
|
||||||
|
|
||||||
@customElement('livechat-dynamic-table-form')
|
@customElement('livechat-dynamic-table-form')
|
||||||
export class DynamicTableFormElement extends LivechatElement {
|
export class DynamicTableFormElement extends LivechatElement {
|
||||||
@property({ attribute: false })
|
@property({ attribute: false })
|
||||||
@ -73,11 +84,17 @@ export class DynamicTableFormElement extends LivechatElement {
|
|||||||
@property({ attribute: false })
|
@property({ attribute: false })
|
||||||
public schema: { [key: string]: CellDataSchema } = {}
|
public schema: { [key: string]: CellDataSchema } = {}
|
||||||
|
|
||||||
|
@property()
|
||||||
|
public validation?: {[key: string]: ValidationErrorType[] }
|
||||||
|
|
||||||
|
@property({ attribute: false })
|
||||||
|
public validationPrefix: string = ''
|
||||||
|
|
||||||
@property({ attribute: false })
|
@property({ attribute: false })
|
||||||
public rows: Array<{ [key: string]: DynamicTableAcceptedTypes }> = []
|
public rows: Array<{ [key: string]: DynamicTableAcceptedTypes }> = []
|
||||||
|
|
||||||
@state()
|
@state()
|
||||||
public _rowsById: Array<{ _id: number, row: { [key: string]: DynamicTableAcceptedTypes } }> = []
|
public _rowsById: DynamicTableRowData[] = []
|
||||||
|
|
||||||
@property({ attribute: false })
|
@property({ attribute: false })
|
||||||
public formName: string = ''
|
public formName: string = ''
|
||||||
@ -102,7 +119,8 @@ export class DynamicTableFormElement extends LivechatElement {
|
|||||||
|
|
||||||
private readonly _addRow = (): void => {
|
private readonly _addRow = (): void => {
|
||||||
const newRow = this._getDefaultRow()
|
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.rows.push(newRow)
|
||||||
this.requestUpdate('rows')
|
this.requestUpdate('rows')
|
||||||
this.requestUpdate('_rowsById')
|
this.requestUpdate('_rowsById')
|
||||||
@ -123,11 +141,17 @@ export class DynamicTableFormElement extends LivechatElement {
|
|||||||
|
|
||||||
this._updateLastRowId()
|
this._updateLastRowId()
|
||||||
|
|
||||||
|
// Filter removed rows
|
||||||
this._rowsById.filter(rowById => this.rows.includes(rowById.row))
|
this._rowsById.filter(rowById => this.rows.includes(rowById.row))
|
||||||
|
|
||||||
for (const row of this.rows) {
|
for (let i = 0; i < this.rows.length; i++) {
|
||||||
if (this._rowsById.filter(rowById => rowById.row === row).length === 0) {
|
if (this._rowsById.filter(rowById => rowById.row === this.rows[i]).length === 0) {
|
||||||
this._rowsById.push({ _id: this._lastRowId++, row })
|
// 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>`
|
</th>`
|
||||||
}
|
}
|
||||||
|
|
||||||
private readonly _renderDataRow = (rowData: { _id: number
|
private readonly _renderDataRow = (rowData: DynamicTableRowData): TemplateResult => {
|
||||||
row: {[key: string]: DynamicTableAcceptedTypes} }): TemplateResult => {
|
|
||||||
const inputId = `peertube-livechat-${this.formName.replace(/_/g, '-')}-row-${rowData._id}`
|
const inputId = `peertube-livechat-${this.formName.replace(/_/g, '-')}-row-${rowData._id}`
|
||||||
|
|
||||||
return html`<tr id=${inputId}>
|
return html`<tr id=${inputId}>
|
||||||
${Object.keys(this.header)
|
${Object.keys(this.header)
|
||||||
.sort((k1, k2) => this.columnOrder.indexOf(k1) - this.columnOrder.indexOf(k2))
|
.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">
|
<td class="form-group">
|
||||||
<button type="button"
|
<button type="button"
|
||||||
class="peertube-button-link orange-button dynamic-table-remove-row"
|
class="peertube-button-link orange-button dynamic-table-remove-row"
|
||||||
@ -202,8 +228,10 @@ export class DynamicTableFormElement extends LivechatElement {
|
|||||||
</tfoot>`
|
</tfoot>`
|
||||||
}
|
}
|
||||||
|
|
||||||
renderDataCell = (property: [string, DynamicTableAcceptedTypes], rowId: number): TemplateResult => {
|
renderDataCell = (propertyName: string,
|
||||||
let [propertyName, propertyValue] = property
|
propertyValue: DynamicTableAcceptedTypes,
|
||||||
|
rowId: number,
|
||||||
|
originalIndex: number): TemplateResult => {
|
||||||
const propertySchema = this.schema[propertyName] ?? {}
|
const propertySchema = this.schema[propertyName] ?? {}
|
||||||
|
|
||||||
let formElement
|
let formElement
|
||||||
@ -212,6 +240,8 @@ export class DynamicTableFormElement extends LivechatElement {
|
|||||||
const inputId =
|
const inputId =
|
||||||
`peertube-livechat-${this.formName.replace(/_/g, '-')}-${propertyName.toString().replace(/_/g, '-')}-${rowId}`
|
`peertube-livechat-${this.formName.replace(/_/g, '-')}-${propertyName.toString().replace(/_/g, '-')}-${rowId}`
|
||||||
|
|
||||||
|
const feedback = this._renderFeedback(inputId, propertyName, originalIndex)
|
||||||
|
|
||||||
switch (propertySchema.default?.constructor) {
|
switch (propertySchema.default?.constructor) {
|
||||||
case String:
|
case String:
|
||||||
switch (propertySchema.inputType) {
|
switch (propertySchema.inputType) {
|
||||||
@ -234,30 +264,39 @@ export class DynamicTableFormElement extends LivechatElement {
|
|||||||
case 'time':
|
case 'time':
|
||||||
case 'url':
|
case 'url':
|
||||||
case 'week':
|
case 'week':
|
||||||
formElement = this._renderInput(rowId,
|
formElement = html`${this._renderInput(rowId,
|
||||||
inputId,
|
inputId,
|
||||||
inputName,
|
inputName,
|
||||||
propertyName,
|
propertyName,
|
||||||
propertySchema,
|
propertySchema,
|
||||||
propertyValue as string)
|
propertyValue as string,
|
||||||
|
originalIndex)}
|
||||||
|
${feedback}
|
||||||
|
`
|
||||||
break
|
break
|
||||||
|
|
||||||
case 'textarea':
|
case 'textarea':
|
||||||
formElement = this._renderTextarea(rowId,
|
formElement = html`${this._renderTextarea(rowId,
|
||||||
inputId,
|
inputId,
|
||||||
inputName,
|
inputName,
|
||||||
propertyName,
|
propertyName,
|
||||||
propertySchema,
|
propertySchema,
|
||||||
propertyValue as string)
|
propertyValue as string,
|
||||||
|
originalIndex)}
|
||||||
|
${feedback}
|
||||||
|
`
|
||||||
break
|
break
|
||||||
|
|
||||||
case 'select':
|
case 'select':
|
||||||
formElement = this._renderSelect(rowId,
|
formElement = html`${this._renderSelect(rowId,
|
||||||
inputId,
|
inputId,
|
||||||
inputName,
|
inputName,
|
||||||
propertyName,
|
propertyName,
|
||||||
propertySchema,
|
propertySchema,
|
||||||
propertyValue as string)
|
propertyValue as string,
|
||||||
|
originalIndex)}
|
||||||
|
${feedback}
|
||||||
|
`
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
break
|
break
|
||||||
@ -271,12 +310,15 @@ export class DynamicTableFormElement extends LivechatElement {
|
|||||||
case 'datetime':
|
case 'datetime':
|
||||||
case 'datetime-local':
|
case 'datetime-local':
|
||||||
case 'time':
|
case 'time':
|
||||||
formElement = this._renderInput(rowId,
|
formElement = html`${this._renderInput(rowId,
|
||||||
inputId,
|
inputId,
|
||||||
inputName,
|
inputName,
|
||||||
propertyName,
|
propertyName,
|
||||||
propertySchema,
|
propertySchema,
|
||||||
(propertyValue as Date).toISOString())
|
(propertyValue as Date).toISOString(),
|
||||||
|
originalIndex)}
|
||||||
|
${feedback}
|
||||||
|
`
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
break
|
break
|
||||||
@ -288,12 +330,15 @@ export class DynamicTableFormElement extends LivechatElement {
|
|||||||
|
|
||||||
case 'number':
|
case 'number':
|
||||||
case 'range':
|
case 'range':
|
||||||
formElement = this._renderInput(rowId,
|
formElement = html`${this._renderInput(rowId,
|
||||||
inputId,
|
inputId,
|
||||||
inputName,
|
inputName,
|
||||||
propertyName,
|
propertyName,
|
||||||
propertySchema,
|
propertySchema,
|
||||||
propertyValue as string)
|
propertyValue as string,
|
||||||
|
originalIndex)}
|
||||||
|
${feedback}
|
||||||
|
`
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
break
|
break
|
||||||
@ -304,12 +349,15 @@ export class DynamicTableFormElement extends LivechatElement {
|
|||||||
propertySchema.inputType = 'checkbox'
|
propertySchema.inputType = 'checkbox'
|
||||||
|
|
||||||
case 'checkbox':
|
case 'checkbox':
|
||||||
formElement = this._renderCheckbox(rowId,
|
formElement = html`${this._renderCheckbox(rowId,
|
||||||
inputId,
|
inputId,
|
||||||
inputName,
|
inputName,
|
||||||
propertyName,
|
propertyName,
|
||||||
propertySchema,
|
propertySchema,
|
||||||
propertyValue as boolean)
|
propertyValue as boolean,
|
||||||
|
originalIndex)}
|
||||||
|
${feedback}
|
||||||
|
`
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
break
|
break
|
||||||
@ -338,15 +386,45 @@ export class DynamicTableFormElement extends LivechatElement {
|
|||||||
if (propertyValue.constructor !== Array) {
|
if (propertyValue.constructor !== Array) {
|
||||||
propertyValue = (propertyValue) ? [propertyValue as (number | string)] : []
|
propertyValue = (propertyValue) ? [propertyValue as (number | string)] : []
|
||||||
}
|
}
|
||||||
formElement = this._renderInput(rowId, inputId, inputName, propertyName, propertySchema,
|
formElement = html`${this._renderInput(rowId,
|
||||||
(propertyValue)?.join(propertySchema.separator ?? ',') ?? propertyValue ?? propertySchema.default ?? '')
|
inputId,
|
||||||
|
inputName,
|
||||||
|
propertyName,
|
||||||
|
propertySchema,
|
||||||
|
(propertyValue)?.join(propertySchema.separators?.[0] ?? ',') ??
|
||||||
|
propertyValue ?? propertySchema.default ?? '',
|
||||||
|
originalIndex)}
|
||||||
|
${feedback}
|
||||||
|
`
|
||||||
break
|
break
|
||||||
case 'textarea':
|
case 'textarea':
|
||||||
if (propertyValue.constructor !== Array) {
|
if (propertyValue.constructor !== Array) {
|
||||||
propertyValue = (propertyValue) ? [propertyValue as (number | string)] : []
|
propertyValue = (propertyValue) ? [propertyValue as (number | string)] : []
|
||||||
}
|
}
|
||||||
formElement = this._renderTextarea(rowId, inputId, inputName, propertyName, propertySchema,
|
formElement = html`${this._renderTextarea(rowId,
|
||||||
(propertyValue)?.join(propertySchema.separator ?? ',') ?? propertyValue ?? propertySchema.default ?? '')
|
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
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -364,12 +442,14 @@ export class DynamicTableFormElement extends LivechatElement {
|
|||||||
inputName: string,
|
inputName: string,
|
||||||
propertyName: string,
|
propertyName: string,
|
||||||
propertySchema: CellDataSchema,
|
propertySchema: CellDataSchema,
|
||||||
propertyValue: string): TemplateResult => {
|
propertyValue: string,
|
||||||
|
originalIndex: number): TemplateResult => {
|
||||||
return html`<input
|
return html`<input
|
||||||
type=${propertySchema.inputType}
|
type=${propertySchema.inputType}
|
||||||
name=${inputName}
|
name=${inputName}
|
||||||
class="form-control"
|
class="form-control ${classMap(this._getInputValidationClass(propertyName, originalIndex))}"
|
||||||
id=${inputId}
|
id=${inputId}
|
||||||
|
aria-describedby="${inputId}-feedback"
|
||||||
list=${(propertySchema.datalist) ? inputId + '-datalist' : nothing}
|
list=${(propertySchema.datalist) ? inputId + '-datalist' : nothing}
|
||||||
min=${ifDefined(propertySchema.min)}
|
min=${ifDefined(propertySchema.min)}
|
||||||
max=${ifDefined(propertySchema.max)}
|
max=${ifDefined(propertySchema.max)}
|
||||||
@ -382,8 +462,31 @@ export class DynamicTableFormElement extends LivechatElement {
|
|||||||
? html`<datalist id=${inputId + '-datalist'}>
|
? html`<datalist id=${inputId + '-datalist'}>
|
||||||
${(propertySchema.datalist ?? []).map((value) => html`<option value=${value}>`)}
|
${(propertySchema.datalist ?? []).map((value) => html`<option value=${value}>`)}
|
||||||
</datalist>`
|
</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,
|
_renderTextarea = (rowId: number,
|
||||||
@ -391,18 +494,19 @@ export class DynamicTableFormElement extends LivechatElement {
|
|||||||
inputName: string,
|
inputName: string,
|
||||||
propertyName: string,
|
propertyName: string,
|
||||||
propertySchema: CellDataSchema,
|
propertySchema: CellDataSchema,
|
||||||
propertyValue: string): TemplateResult => {
|
propertyValue: string,
|
||||||
|
originalIndex: number): TemplateResult => {
|
||||||
return html`<textarea
|
return html`<textarea
|
||||||
name=${inputName}
|
name=${inputName}
|
||||||
class="form-control"
|
class="form-control ${classMap(this._getInputValidationClass(propertyName, originalIndex))}"
|
||||||
id=${inputId}
|
id=${inputId}
|
||||||
|
aria-describedby="${inputId}-feedback"
|
||||||
min=${ifDefined(propertySchema.min)}
|
min=${ifDefined(propertySchema.min)}
|
||||||
max=${ifDefined(propertySchema.max)}
|
max=${ifDefined(propertySchema.max)}
|
||||||
minlength=${ifDefined(propertySchema.minlength)}
|
minlength=${ifDefined(propertySchema.minlength)}
|
||||||
maxlength=${ifDefined(propertySchema.maxlength)}
|
maxlength=${ifDefined(propertySchema.maxlength)}
|
||||||
@change=${(event: Event) => this._updatePropertyFromValue(event, propertyName, propertySchema, rowId)}
|
@change=${(event: Event) => this._updatePropertyFromValue(event, propertyName, propertySchema, rowId)}
|
||||||
.value=${propertyValue}
|
.value=${propertyValue}></textarea>`
|
||||||
></textarea>`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
_renderCheckbox = (rowId: number,
|
_renderCheckbox = (rowId: number,
|
||||||
@ -410,16 +514,17 @@ export class DynamicTableFormElement extends LivechatElement {
|
|||||||
inputName: string,
|
inputName: string,
|
||||||
propertyName: string,
|
propertyName: string,
|
||||||
propertySchema: CellDataSchema,
|
propertySchema: CellDataSchema,
|
||||||
propertyValue: boolean): TemplateResult => {
|
propertyValue: boolean,
|
||||||
|
originalIndex: number): TemplateResult => {
|
||||||
return html`<input
|
return html`<input
|
||||||
type="checkbox"
|
type="checkbox"
|
||||||
name=${inputName}
|
name=${inputName}
|
||||||
class="form-check-input"
|
class="form-check-input ${classMap(this._getInputValidationClass(propertyName, originalIndex))}"
|
||||||
id=${inputId}
|
id=${inputId}
|
||||||
|
aria-describedby="${inputId}-feedback"
|
||||||
@change=${(event: Event) => this._updatePropertyFromValue(event, propertyName, propertySchema, rowId)}
|
@change=${(event: Event) => this._updatePropertyFromValue(event, propertyName, propertySchema, rowId)}
|
||||||
.value=${propertyValue}
|
.value=${propertyValue}
|
||||||
?checked=${propertyValue}
|
?checked=${propertyValue} />`
|
||||||
/>`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
_renderSelect = (rowId: number,
|
_renderSelect = (rowId: number,
|
||||||
@ -427,10 +532,13 @@ export class DynamicTableFormElement extends LivechatElement {
|
|||||||
inputName: string,
|
inputName: string,
|
||||||
propertyName: string,
|
propertyName: string,
|
||||||
propertySchema: CellDataSchema,
|
propertySchema: CellDataSchema,
|
||||||
propertyValue: string): TemplateResult => {
|
propertyValue: string,
|
||||||
|
originalIndex: number): TemplateResult => {
|
||||||
return html`<select
|
return html`<select
|
||||||
class="form-select"
|
class="form-select ${classMap(this._getInputValidationClass(propertyName, originalIndex))}"
|
||||||
aria-label="Default select example"
|
id=${inputId}
|
||||||
|
aria-describedby="${inputId}-feedback"
|
||||||
|
aria-label=${inputName}
|
||||||
@change=${(event: Event) => this._updatePropertyFromValue(event, propertyName, propertySchema, rowId)}
|
@change=${(event: Event) => this._updatePropertyFromValue(event, propertyName, propertySchema, rowId)}
|
||||||
>
|
>
|
||||||
<option ?selected=${!propertyValue}>${propertySchema.label ?? 'Choose your option'}</option>
|
<option ?selected=${!propertyValue}>${propertySchema.label ?? 'Choose your option'}</option>
|
||||||
@ -441,23 +549,64 @@ export class DynamicTableFormElement extends LivechatElement {
|
|||||||
</select>`
|
</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,
|
_updatePropertyFromValue = (event: Event,
|
||||||
propertyName: string,
|
propertyName: string,
|
||||||
propertySchema: CellDataSchema,
|
propertySchema: CellDataSchema,
|
||||||
rowId: number): void => {
|
rowId: number): void => {
|
||||||
const target = event.target as (HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement)
|
const target = event.target as (TagsInputElement | HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement)
|
||||||
const value = (target)
|
const value = (target)
|
||||||
? (target instanceof HTMLInputElement && target.type === 'checkbox')
|
? (target instanceof HTMLInputElement && target.type === 'checkbox')
|
||||||
? !!(target.checked)
|
? !!(target.checked)
|
||||||
: target.value
|
: target.value
|
||||||
: undefined
|
: undefined
|
||||||
|
|
||||||
|
console.log(`value: ${JSON.stringify(value)}`)
|
||||||
|
|
||||||
if (value !== undefined) {
|
if (value !== undefined) {
|
||||||
for (const rowById of this._rowsById) {
|
for (const rowById of this._rowsById) {
|
||||||
if (rowById._id === rowId) {
|
if (rowById._id === rowId) {
|
||||||
switch (propertySchema.default?.constructor) {
|
switch (propertySchema.default?.constructor) {
|
||||||
case Array:
|
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
|
break
|
||||||
default:
|
default:
|
||||||
rowById.row[propertyName] = value
|
rowById.row[propertyName] = value
|
||||||
|
@ -6,3 +6,4 @@
|
|||||||
import './help-button'
|
import './help-button'
|
||||||
import './dynamic-table-form'
|
import './dynamic-table-form'
|
||||||
import './configuration-row'
|
import './configuration-row'
|
||||||
|
import './tags-input'
|
||||||
|
193
client/common/lib/elements/tags-input.ts
Normal file
193
client/common/lib/elements/tags-input.ts
Normal 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 }))
|
||||||
|
}
|
||||||
|
}
|
13
client/common/lib/models/validation.ts
Normal file
13
client/common/lib/models/validation.ts
Normal 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[] } = {}
|
||||||
|
}
|
@ -3,7 +3,7 @@
|
|||||||
"experimentalDecorators": true,
|
"experimentalDecorators": true,
|
||||||
"module": "es6",
|
"module": "es6",
|
||||||
"moduleResolution": "node",
|
"moduleResolution": "node",
|
||||||
"target": "es5",
|
"target": "es6",
|
||||||
"allowJs": true,
|
"allowJs": true,
|
||||||
"sourceMap": true,
|
"sourceMap": true,
|
||||||
"forceConsistentCasingInFileNames": true,
|
"forceConsistentCasingInFileNames": true,
|
||||||
|
@ -435,6 +435,9 @@ livechat_configuration_channel_banned_jids_label: "Banned users and patterns"
|
|||||||
livechat_configuration_channel_bot_nickname: "Bot nickname"
|
livechat_configuration_channel_bot_nickname: "Bot nickname"
|
||||||
|
|
||||||
invalid_value: "Invalid value."
|
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."
|
slow_mode_info: "Slow mode is enabled, users can send a message every %1$s seconds."
|
||||||
|
|
||||||
|
@ -92,22 +92,9 @@ interface ChannelConfigurationOptions {
|
|||||||
bot: {
|
bot: {
|
||||||
enabled: boolean
|
enabled: boolean
|
||||||
nickname?: string
|
nickname?: string
|
||||||
forbiddenWords: Array<{
|
forbiddenWords: ChannelForbiddenWords[]
|
||||||
entries: string[]
|
quotes: ChannelQuotes[]
|
||||||
regexp?: boolean
|
commands: ChannelCommands[]
|
||||||
applyToModerators?: boolean
|
|
||||||
label?: string
|
|
||||||
reason?: string
|
|
||||||
comments?: string
|
|
||||||
}>
|
|
||||||
quotes: Array<{
|
|
||||||
messages: string[]
|
|
||||||
delay: number
|
|
||||||
}>
|
|
||||||
commands: Array<{
|
|
||||||
command: string
|
|
||||||
message: string
|
|
||||||
}>
|
|
||||||
// TODO: bannedJIDs: string[]
|
// TODO: bannedJIDs: string[]
|
||||||
}
|
}
|
||||||
slowMode: {
|
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 {
|
interface ChannelConfiguration {
|
||||||
channel: ChannelInfos
|
channel: ChannelInfos
|
||||||
configuration: ChannelConfigurationOptions
|
configuration: ChannelConfigurationOptions
|
||||||
|
Loading…
x
Reference in New Issue
Block a user