fix linting

This commit is contained in:
Mehdi Benadel 2024-05-23 22:52:39 +02:00
parent f549142ae4
commit fb7f44692c
10 changed files with 282 additions and 204 deletions

View File

@ -6,5 +6,7 @@ import type { ChannelConfiguration } from 'shared/lib/types'
import { createContext } from '@lit/context' import { createContext } from '@lit/context'
import { ChannelDetailsService } from '../services/channel-details' import { ChannelDetailsService } from '../services/channel-details'
export const channelConfigurationContext = createContext<ChannelConfiguration | undefined>(Symbol('channel-configuration')) export const channelConfigurationContext =
export const channelDetailsServiceContext = createContext<ChannelDetailsService | undefined>(Symbol('channel-configuration-service')) createContext<ChannelConfiguration | undefined>(Symbol('channel-configuration'))
export const channelDetailsServiceContext =
createContext<ChannelDetailsService | undefined>(Symbol('channel-configuration-service'))

View File

@ -16,7 +16,6 @@ import { LivechatElement } from '../../lib/elements/livechat'
@customElement('livechat-channel-configuration') @customElement('livechat-channel-configuration')
export class ChannelConfigurationElement extends LivechatElement { export class ChannelConfigurationElement extends LivechatElement {
@provide({ context: registerClientOptionsContext }) @provide({ context: registerClientOptionsContext })
@property({ attribute: false }) @property({ attribute: false })
public registerClientOptions: RegisterClientOptions | undefined public registerClientOptions: RegisterClientOptions | undefined
@ -34,38 +33,36 @@ export class ChannelConfigurationElement extends LivechatElement {
@state() @state()
public _formStatus: boolean | any = undefined public _formStatus: boolean | any = undefined
private _asyncTaskRender = new Task(this, { private readonly _asyncTaskRender = new Task(this, {
task: async ([registerClientOptions]) => {
task: async ([registerClientOptions], { signal }) => { if (registerClientOptions) {
if (this.registerClientOptions) { this._channelDetailsService = new ChannelDetailsService(registerClientOptions)
this._channelDetailsService = new ChannelDetailsService(this.registerClientOptions)
this._channelConfiguration = await this._channelDetailsService.fetchConfiguration(this.channelId ?? 0) this._channelConfiguration = await this._channelDetailsService.fetchConfiguration(this.channelId ?? 0)
} }
}, },
args: () => [this.registerClientOptions] args: () => [this.registerClientOptions]
})
}); private readonly _saveConfig = (ev?: Event): undefined => {
private _saveConfig = (ev?: Event) => {
ev?.preventDefault() ev?.preventDefault()
if (this._channelDetailsService && this._channelConfiguration) { if (this._channelDetailsService && this._channelConfiguration) {
this._channelDetailsService.saveOptions(this._channelConfiguration.channel.id, this._channelConfiguration.configuration) this._channelDetailsService.saveOptions(this._channelConfiguration.channel.id,
.then((value) => { this._channelConfiguration.configuration)
.then(() => {
this._formStatus = { success: true } this._formStatus = { success: true }
console.log(`Configuration has been updated`) console.log('Configuration has been updated')
this.requestUpdate('_formStatus') this.requestUpdate('_formStatus')
}) })
.catch((error) => { .catch((error) => {
this._formStatus = error this._formStatus = error
console.log(`An error occurred : ${JSON.stringify(this._formStatus)}`) console.log(`An error occurred : ${JSON.stringify(this._formStatus)}`)
this.requestUpdate('_formStatus') this.requestUpdate('_formStatus')
}); })
} }
} }
render = () => { protected override render = (): unknown => {
let tableHeaderList = { const tableHeaderList = {
forbiddenWords: { forbiddenWords: {
entries: { entries: {
colName: ptTr(LOC_LIVECHAT_CONFIGURATION_CHANNEL_FORBIDDEN_WORDS_LABEL), colName: ptTr(LOC_LIVECHAT_CONFIGURATION_CHANNEL_FORBIDDEN_WORDS_LABEL),
@ -113,16 +110,16 @@ export class ChannelConfigurationElement extends LivechatElement {
} }
} }
} }
let tableSchema = { const tableSchema = {
forbiddenWords: { forbiddenWords: {
entries: { entries: {
inputType: 'textarea', inputType: 'textarea',
default: [''], default: [''],
separator: '\n', separator: '\n'
}, },
regex: { regex: {
inputType: 'checkbox', inputType: 'checkbox',
default: false, default: false
}, },
applyToModerators: { applyToModerators: {
inputType: 'checkbox', inputType: 'checkbox',
@ -140,34 +137,35 @@ export class ChannelConfigurationElement extends LivechatElement {
comments: { comments: {
inputType: 'textarea', inputType: 'textarea',
default: '' default: ''
}, }
}, },
quotes: { quotes: {
messages: { messages: {
inputType: 'textarea', inputType: 'textarea',
default: [''], default: [''],
separator: '\n', separator: '\n'
}, },
delay: { delay: {
inputType: 'number', inputType: 'number',
default: 10, default: 10
} }
}, },
commands: { commands: {
command: { command: {
inputType: 'text', inputType: 'text',
default: '', default: ''
}, },
message: { message: {
inputType: 'text', inputType: 'text',
default: '', default: ''
} }
} }
} }
return this._asyncTaskRender.render({ return this._asyncTaskRender.render({
complete: () => html` complete: () => html`
<div class="margin-content peertube-plugin-livechat-configuration peertube-plugin-livechat-configuration-channel"> <div class="margin-content peertube-plugin-livechat-configuration
peertube-plugin-livechat-configuration-channel">
<h1> <h1>
${ptTr(LOC_LIVECHAT_CONFIGURATION_CHANNEL_TITLE)}: ${ptTr(LOC_LIVECHAT_CONFIGURATION_CHANNEL_TITLE)}:
<span class="peertube-plugin-livechat-configuration-channel-info"> <span class="peertube-plugin-livechat-configuration-channel-info">
@ -185,7 +183,7 @@ export class ChannelConfigurationElement extends LivechatElement {
<livechat-configuration-row <livechat-configuration-row
.title=${ptTr(LOC_LIVECHAT_CONFIGURATION_CHANNEL_SLOW_MODE_LABEL)} .title=${ptTr(LOC_LIVECHAT_CONFIGURATION_CHANNEL_SLOW_MODE_LABEL)}
.description=${ptTr(LOC_LIVECHAT_CONFIGURATION_CHANNEL_SLOW_MODE_DESC, true)} .description=${ptTr(LOC_LIVECHAT_CONFIGURATION_CHANNEL_SLOW_MODE_DESC, true)}
.helpPage=${"documentation/user/streamers/slow_mode"}> .helpPage=${'documentation/user/streamers/slow_mode'}>
</livechat-configuration-row> </livechat-configuration-row>
</div> </div>
<div class="col-12 col-lg-8 col-xl-9"> <div class="col-12 col-lg-8 col-xl-9">
@ -199,8 +197,10 @@ export class ChannelConfigurationElement extends LivechatElement {
max="1000" max="1000"
id="peertube-livechat-slow-mode-duration" id="peertube-livechat-slow-mode-duration"
@input=${(event: InputEvent) => { @input=${(event: InputEvent) => {
if (event?.target && this._channelConfiguration) if (event?.target && this._channelConfiguration) {
this._channelConfiguration.configuration.slowMode.duration = Number((event.target as HTMLInputElement).value) this._channelConfiguration.configuration.slowMode.duration =
Number((event.target as HTMLInputElement).value)
}
this.requestUpdate('_channelConfiguration') this.requestUpdate('_channelConfiguration')
} }
} }
@ -215,7 +215,7 @@ export class ChannelConfigurationElement extends LivechatElement {
<livechat-configuration-row <livechat-configuration-row
.title=${ptTr(LOC_LIVECHAT_CONFIGURATION_CHANNEL_BOT_OPTIONS_TITLE)} .title=${ptTr(LOC_LIVECHAT_CONFIGURATION_CHANNEL_BOT_OPTIONS_TITLE)}
.description=${''} .description=${''}
.helpPage=${"documentation/user/streamers/channel"}> .helpPage=${'documentation/user/streamers/channel'}>
</livechat-configuration-row> </livechat-configuration-row>
</div> </div>
<div class="col-12 col-lg-8 col-xl-9"> <div class="col-12 col-lg-8 col-xl-9">
@ -226,8 +226,10 @@ export class ChannelConfigurationElement extends LivechatElement {
name="bot" name="bot"
id="peertube-livechat-bot" id="peertube-livechat-bot"
@input=${(event: InputEvent) => { @input=${(event: InputEvent) => {
if (event?.target && this._channelConfiguration) if (event?.target && this._channelConfiguration) {
this._channelConfiguration.configuration.bot.enabled = (event.target as HTMLInputElement).checked this._channelConfiguration.configuration.bot.enabled =
(event.target as HTMLInputElement).checked
}
this.requestUpdate('_channelConfiguration') this.requestUpdate('_channelConfiguration')
} }
} }
@ -237,17 +239,21 @@ export class ChannelConfigurationElement extends LivechatElement {
${ptTr(LOC_LIVECHAT_CONFIGURATION_CHANNEL_ENABLE_BOT_LABEL)} ${ptTr(LOC_LIVECHAT_CONFIGURATION_CHANNEL_ENABLE_BOT_LABEL)}
</label> </label>
</div> </div>
${this._channelConfiguration?.configuration.bot.enabled ? ${this._channelConfiguration?.configuration.bot.enabled
html`<div class="form-group"> ? html`<div class="form-group">
<label for="peertube-livechat-bot-nickname">${ptTr(LOC_LIVECHAT_CONFIGURATION_CHANNEL_BOT_NICKNAME)}</label> <labelfor="peertube-livechat-bot-nickname">
${ptTr(LOC_LIVECHAT_CONFIGURATION_CHANNEL_BOT_NICKNAME)}
</label>
<input <input
type="text" type="text"
name="bot_nickname" name="bot_nickname"
class="form-control" class="form-control"
id="peertube-livechat-bot-nickname" id="peertube-livechat-bot-nickname"
@input=${(event: InputEvent) => { @input=${(event: InputEvent) => {
if (event?.target && this._channelConfiguration) if (event?.target && this._channelConfiguration) {
this._channelConfiguration.configuration.bot.nickname = (event.target as HTMLInputElement).value this._channelConfiguration.configuration.bot.nickname =
(event.target as HTMLInputElement).value
}
this.requestUpdate('_channelConfiguration') this.requestUpdate('_channelConfiguration')
} }
} }
@ -258,13 +264,13 @@ export class ChannelConfigurationElement extends LivechatElement {
} }
</div> </div>
</div> </div>
${this._channelConfiguration?.configuration.bot.enabled ? ${this._channelConfiguration?.configuration.bot.enabled
html`<div class="row mt-5"> ? html`<div class="row mt-5">
<div class="col-12 col-lg-4 col-xl-3"> <div class="col-12 col-lg-4 col-xl-3">
<livechat-configuration-row <livechat-configuration-row
.title=${ptTr(LOC_LIVECHAT_CONFIGURATION_CHANNEL_FORBIDDEN_WORDS_LABEL)} .title=${ptTr(LOC_LIVECHAT_CONFIGURATION_CHANNEL_FORBIDDEN_WORDS_LABEL)}
.description=${ptTr(LOC_LIVECHAT_CONFIGURATION_CHANNEL_FORBIDDEN_WORDS_DESC)} .description=${ptTr(LOC_LIVECHAT_CONFIGURATION_CHANNEL_FORBIDDEN_WORDS_DESC)}
.helpPage=${"documentation/user/streamers/bot/forbidden_words"}> .helpPage=${'documentation/user/streamers/bot/forbidden_words'}>
</livechat-configuration-row> </livechat-configuration-row>
</div> </div>
<div class="col-12 col-lg-8 col-xl-9"> <div class="col-12 col-lg-8 col-xl-9">
@ -288,7 +294,7 @@ export class ChannelConfigurationElement extends LivechatElement {
<livechat-configuration-row <livechat-configuration-row
.title=${ptTr(LOC_LIVECHAT_CONFIGURATION_CHANNEL_QUOTE_LABEL)} .title=${ptTr(LOC_LIVECHAT_CONFIGURATION_CHANNEL_QUOTE_LABEL)}
.description=${ptTr(LOC_LIVECHAT_CONFIGURATION_CHANNEL_QUOTE_DESC)} .description=${ptTr(LOC_LIVECHAT_CONFIGURATION_CHANNEL_QUOTE_DESC)}
.helpPage=${"documentation/user/streamers/bot/quotes"}> .helpPage=${'documentation/user/streamers/bot/quotes'}>
</livechat-configuration-row> </livechat-configuration-row>
</div> </div>
<div class="col-12 col-lg-8 col-xl-9"> <div class="col-12 col-lg-8 col-xl-9">
@ -312,7 +318,7 @@ export class ChannelConfigurationElement extends LivechatElement {
<livechat-configuration-row <livechat-configuration-row
.title=${ptTr(LOC_LIVECHAT_CONFIGURATION_CHANNEL_COMMAND_LABEL)} .title=${ptTr(LOC_LIVECHAT_CONFIGURATION_CHANNEL_COMMAND_LABEL)}
.description=${ptTr(LOC_LIVECHAT_CONFIGURATION_CHANNEL_COMMAND_DESC)} .description=${ptTr(LOC_LIVECHAT_CONFIGURATION_CHANNEL_COMMAND_DESC)}
.helpPage=${"documentation/user/streamers/bot/commands"}> .helpPage=${'documentation/user/streamers/bot/commands'}>
</livechat-configuration-row> </livechat-configuration-row>
</div> </div>
<div class="col-12 col-lg-8 col-xl-9"> <div class="col-12 col-lg-8 col-xl-9">
@ -336,14 +342,14 @@ export class ChannelConfigurationElement extends LivechatElement {
<div class="form-group mt-5"> <div class="form-group mt-5">
<input type="submit" class="peertube-button-link orange-button" value=${ptTr(LOC_SAVE)} /> <input type="submit" class="peertube-button-link orange-button" value=${ptTr(LOC_SAVE)} />
</div> </div>
${(this._formStatus && this._formStatus.success === undefined) ? ${(this._formStatus && this._formStatus.success === undefined)
html`<div class="alert alert-warning" role="alert"> ? html`<div class="alert alert-warning" role="alert">
An error occurred : ${JSON.stringify(this._formStatus)} An error occurred : ${JSON.stringify(this._formStatus)}
</div>` </div>`
: '' : ''
} }
${(this._formStatus && this._formStatus.success === true) ? ${(this._formStatus && this._formStatus.success === true)
html`<div class="alert alert-success" role="alert"> ? html`<div class="alert alert-success" role="alert">
Configuration has been updated Configuration has been updated
</div>` </div>`
: '' : ''

View File

@ -6,7 +6,7 @@ import type { RegisterClientOptions } from '@peertube/peertube-types/client'
import { html } from 'lit' import { html } 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'
import type { ChannelLiveChatInfos } from 'shared/lib/types' import type { ChannelLiveChatInfos } from 'shared/lib/types'
import { ChannelDetailsService } from '../services/channel-details' import { ChannelDetailsService } from '../services/channel-details'
import { provide } from '@lit/context' import { provide } from '@lit/context'
@ -16,7 +16,6 @@ import { LivechatElement } from '../../lib/elements/livechat'
@customElement('livechat-channel-home') @customElement('livechat-channel-home')
export class ChannelHomeElement extends LivechatElement { export class ChannelHomeElement extends LivechatElement {
@provide({ context: registerClientOptionsContext }) @provide({ context: registerClientOptionsContext })
@property({ attribute: false }) @property({ attribute: false })
public registerClientOptions: RegisterClientOptions | undefined public registerClientOptions: RegisterClientOptions | undefined
@ -30,26 +29,23 @@ export class ChannelHomeElement extends LivechatElement {
@state() @state()
public _formStatus: boolean | any = undefined public _formStatus: boolean | any = undefined
private _asyncTaskRender = new Task(this, { private readonly _asyncTaskRender = new Task(this, {
task: async ([registerClientOptions]) => {
task: async ([registerClientOptions], {signal}) => {
// Getting the current username in localStorage. Don't know any cleaner way to do. // Getting the current username in localStorage. Don't know any cleaner way to do.
const username = window.localStorage.getItem('username') const username = window.localStorage.getItem('username')
if (!username) { if (!username) {
throw new Error('Can\'t get the current username.') throw new Error('Can\'t get the current username.')
} }
if (this.registerClientOptions) { if (registerClientOptions) {
this._channelDetailsService = new ChannelDetailsService(this.registerClientOptions) this._channelDetailsService = new ChannelDetailsService(registerClientOptions)
this._channels = await this._channelDetailsService.fetchUserChannels(username) this._channels = await this._channelDetailsService.fetchUserChannels(username)
} }
}, },
args: () => [this.registerClientOptions] args: () => [this.registerClientOptions]
})
}); protected override render = (): unknown => {
render = () => {
return this._asyncTaskRender.render({ return this._asyncTaskRender.render({
complete: () => html` complete: () => html`
<div class="margin-content peertube-plugin-livechat-configuration peertube-plugin-livechat-configuration-home"> <div class="margin-content peertube-plugin-livechat-configuration peertube-plugin-livechat-configuration-home">
@ -64,10 +60,9 @@ export class ChannelHomeElement extends LivechatElement {
${this._channels?.map((channel) => html` ${this._channels?.map((channel) => html`
<li> <li>
<a href="${channel.livechatConfigurationUri}"> <a href="${channel.livechatConfigurationUri}">
${channel.avatar ? ${channel.avatar
html`<img class="avatar channel" src="${channel.avatar.path}">` ? html`<img class="avatar channel" src="${channel.avatar.path}">`
: : html`<div class="avatar channel initial gray"></div>`
html`<div class="avatar channel initial gray"></div>`
} }
</a> </a>
<div class="peertube-plugin-livechat-configuration-home-info"> <div class="peertube-plugin-livechat-configuration-home-info">

View File

@ -8,17 +8,16 @@ import { LivechatElement } from '../../lib/elements/livechat'
@customElement('livechat-configuration-row') @customElement('livechat-configuration-row')
export class ConfigurationRowElement extends LivechatElement { export class ConfigurationRowElement extends LivechatElement {
@property({ attribute: false })
public title: string = 'title'
@property({ attribute: false }) @property({ attribute: false })
public title: string = `title` public description: string = 'Here\'s a description'
@property({ attribute: false })
public description: string = `Here's a description`
@property({ attribute: false }) @property({ attribute: false })
public helpPage: string = 'documentation' public helpPage: string = 'documentation'
render() { protected override render = (): unknown => {
return html` return html`
<h2>${this.title}</h2> <h2>${this.title}</h2>
<p>${this.description}</p> <p>${this.description}</p>

View File

@ -4,32 +4,30 @@
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 { ChannelLiveChatInfos, ChannelConfiguration, ChannelConfigurationOptions } from 'shared/lib/types'
import { getBaseRoute } from "../../../utils/uri" import { getBaseRoute } from '../../../utils/uri'
export class ChannelDetailsService { export class ChannelDetailsService {
public _registerClientOptions: RegisterClientOptions public _registerClientOptions: RegisterClientOptions
private _headers : any = {} private readonly _headers: any = {}
constructor(registerClientOptions: RegisterClientOptions) { constructor (registerClientOptions: RegisterClientOptions) {
this._registerClientOptions = registerClientOptions this._registerClientOptions = registerClientOptions
this._headers = this._registerClientOptions.peertubeHelpers.getAuthHeader() ?? {} this._headers = this._registerClientOptions.peertubeHelpers.getAuthHeader() ?? {}
this._headers['content-type'] = 'application/json;charset=UTF-8' this._headers['content-type'] = 'application/json;charset=UTF-8'
} }
validateOptions = (channelConfigurationOptions: ChannelConfigurationOptions) => { validateOptions = (channelConfigurationOptions: ChannelConfigurationOptions): boolean => {
return true return !!channelConfigurationOptions
} }
saveOptions = async (channelId: number, channelConfigurationOptions: ChannelConfigurationOptions) => { saveOptions = async (channelId: number,
channelConfigurationOptions: ChannelConfigurationOptions): Promise<Response> => {
if (!await this.validateOptions(channelConfigurationOptions)) { if (!await this.validateOptions(channelConfigurationOptions)) {
throw new Error('Invalid form data') throw new Error('Invalid form data')
} }
const response = await fetch( const response = await fetch(
getBaseRoute(this._registerClientOptions) + '/api/configuration/channel/' + encodeURIComponent(channelId), getBaseRoute(this._registerClientOptions) + '/api/configuration/channel/' + encodeURIComponent(channelId),
{ {
@ -43,7 +41,7 @@ export class ChannelDetailsService {
throw new Error('Failed to save configuration options.') throw new Error('Failed to save configuration options.')
} }
return await response.json() return response.json()
} }
fetchUserChannels = async (username: string): Promise<ChannelLiveChatInfos[]> => { fetchUserChannels = async (username: string): Promise<ChannelLiveChatInfos[]> => {
@ -90,6 +88,6 @@ export class ChannelDetailsService {
throw new Error('Can\'t get channel configuration options.') throw new Error('Can\'t get channel configuration options.')
} }
return await response.json() return response.json()
} }
} }

View File

@ -5,4 +5,5 @@
import type { RegisterClientOptions } from '@peertube/peertube-types/client/types' import type { RegisterClientOptions } from '@peertube/peertube-types/client/types'
import { createContext } from '@lit/context' import { createContext } from '@lit/context'
export const registerClientOptionsContext = createContext<RegisterClientOptions | undefined>(Symbol('register-client-options')) export const registerClientOptionsContext =
createContext<RegisterClientOptions | undefined>(Symbol('register-client-options'))

View File

@ -2,59 +2,59 @@
// //
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-License-Identifier: AGPL-3.0-only
import { PartInfo, directive } from 'lit/directive.js' import { /* PartInfo, */ directive } from 'lit/directive.js'
import { AsyncDirective } from 'lit/async-directive.js' import { AsyncDirective } from 'lit/async-directive.js'
import { RegisterClientHelpers } from '@peertube/peertube-types/client'; import { RegisterClientHelpers } from '@peertube/peertube-types/client'
import { unsafeHTML } from 'lit/directives/unsafe-html.js'; import { unsafeHTML } from 'lit/directives/unsafe-html.js'
import { html } from 'lit'; import { html } from 'lit'
export class TranslationDirective extends AsyncDirective { export class TranslationDirective extends AsyncDirective {
private readonly _peertubeHelpers?: RegisterClientHelpers
private _peertubeHelpers?: RegisterClientHelpers private _translatedValue: string = ''
private _localizationId: string = ''
private _translatedValue : string = '' private _allowUnsafeHTML = false
private _localizationId : string = ''
private _allowUnsafeHTML = false // constructor (partInfo: PartInfo) {
// super(partInfo)
constructor(partInfo: PartInfo) { // _peertubeOptionsPromise.then((options) => this._peertubeHelpers = options.peertubeHelpers)
super(partInfo); // }
//_peertubeOptionsPromise.then((options) => this._peertubeHelpers = options.peertubeHelpers) // update = (part: ElementPart) => {
// if (part) console.log(`Element : ${part?.element?.getAttributeNames?.().join(' ')}`);
// return this.render(this._localizationId);
// }
public override render = (locId: string, allowHTML: boolean = false): unknown => {
this._localizationId = locId // TODO Check current component for context (to infer the prefix)
this._allowUnsafeHTML = allowHTML
if (this._translatedValue === '') {
this._translatedValue = locId
} }
// update = (part: ElementPart) => { this._asyncUpdateTranslation().then(() => {}, () => {})
// if (part) console.log(`Element : ${part?.element?.getAttributeNames?.().join(' ')}`);
// return this.render(this._localizationId);
// }
override render = (locId: string, allowHTML: boolean = false) => { return this._internalRender()
this._localizationId = locId // TODO Check current component for context (to infer the prefix) }
this._allowUnsafeHTML = allowHTML private readonly _internalRender = (): unknown => {
return this._allowUnsafeHTML ? html`${unsafeHTML(this._translatedValue)}` : this._translatedValue
}
if (this._translatedValue === '') { private readonly _asyncUpdateTranslation = async (): Promise<true> => {
this._translatedValue = locId const newValue = await this._peertubeHelpers?.translate(this._localizationId) ?? ''
}
this._asyncUpdateTranslation().then(() => {}, () => {}) if (newValue !== '' && newValue !== this._translatedValue) {
this._translatedValue = newValue
return this._internalRender() this.setValue(this._internalRender())
} }
_internalRender = () => { return true
return this._allowUnsafeHTML ? html`${unsafeHTML(this._translatedValue)}` : this._translatedValue }
}
_asyncUpdateTranslation = async () => {
let newValue = await this._peertubeHelpers?.translate(this._localizationId) ?? ''
if (newValue !== '' && newValue !== this._translatedValue) {
this._translatedValue = newValue
this.setValue(this._internalRender())
}
}
} }
export const ptTr = directive(TranslationDirective) export const ptTr = directive(TranslationDirective)

View File

@ -2,6 +2,8 @@
// //
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-License-Identifier: AGPL-3.0-only
/* eslint no-fallthrough: "off" */
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'
@ -9,43 +11,45 @@ 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 { LivechatElement } from './livechat' import { LivechatElement } from './livechat'
// 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 =
`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-plus-square"> `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"
fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"
stroke-linejoin="round" class="feather feather-plus-square">
<rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect> <rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
<line x1="12" y1="8" x2="12" y2="16"></line><line x1="8" y1="12" x2="16" y2="12"></line> <line x1="12" y1="8" x2="12" y2="16"></line><line x1="8" y1="12" x2="16" y2="12"></line>
</svg>` </svg>`
// This content comes from the file assets/images/x-square.svg, from the Feather icons set https://feathericons.com/ // This content comes from the file assets/images/x-square.svg, from the Feather icons set https://feathericons.com/
const RemoveSVG: string = const RemoveSVG: string =
`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-x-square"> `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"
fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"
stroke-linejoin="round" class="feather feather-x-square">
<rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect> <rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
<line x1="9" y1="9" x2="15" y2="15"></line><line x1="15" y1="9" x2="9" y2="15"></line> <line x1="9" y1="9" x2="15" y2="15"></line><line x1="15" y1="9" x2="9" y2="15"></line>
</svg>` </svg>`
type DynamicTableAcceptedTypes = number | string | boolean | Date | Array<number | string> type DynamicTableAcceptedTypes = number | string | boolean | Date | Array<number | string>
type DynamicTableAcceptedInputTypes = 'textarea' type DynamicTableAcceptedInputTypes = 'textarea'
| 'select' | 'select'
| 'checkbox' | 'checkbox'
| 'range' | 'range'
| 'color' | 'color'
| 'date' | 'date'
| 'datetime' | 'datetime'
| 'datetime-local' | 'datetime-local'
| 'email' | 'email'
| 'file' | 'file'
| 'image' | 'image'
| 'month' | 'month'
| 'number' | 'number'
| 'password' | 'password'
| 'tel' | 'tel'
| 'text' | 'text'
| 'time' | 'time'
| 'url' | 'url'
| 'week' | 'week'
interface CellDataSchema { interface CellDataSchema {
min?: number min?: number
@ -63,19 +67,17 @@ interface CellDataSchema {
@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 })
public header: { [key: string]: { colName: TemplateResult, description: TemplateResult } } = {} public header: { [key: string]: { colName: TemplateResult, description: TemplateResult } } = {}
@property({ attribute: false }) @property({ attribute: false })
public schema: { [key: string]: CellDataSchema } = {} public schema: { [key: string]: CellDataSchema } = {}
@property({ attribute: false }) @property({ attribute: false })
public rows: { [key: string]: DynamicTableAcceptedTypes }[] = [] public rows: Array<{ [key: string]: DynamicTableAcceptedTypes }> = []
@state() @state()
public _rowsById: { _id: number; row: { [key: string]: DynamicTableAcceptedTypes } }[] = [] public _rowsById: Array<{ _id: number, row: { [key: string]: DynamicTableAcceptedTypes } }> = []
@property({ attribute: false }) @property({ attribute: false })
public formName: string = '' public formName: string = ''
@ -87,29 +89,28 @@ export class DynamicTableFormElement extends LivechatElement {
private columnOrder: string[] = [] private columnOrder: string[] = []
// fixes situations when list has been reinitialized or changed outside of CustomElement // fixes situations when list has been reinitialized or changed outside of CustomElement
private _updateLastRowId = () => { private readonly _updateLastRowId = (): void => {
for (let rowById of this._rowsById) { for (const rowById of this._rowsById) {
this._lastRowId = Math.max(this._lastRowId, rowById._id + 1); this._lastRowId = Math.max(this._lastRowId, rowById._id + 1)
} }
} }
private _getDefaultRow = () : { [key: string]: DynamicTableAcceptedTypes } => { private readonly _getDefaultRow = (): { [key: string]: DynamicTableAcceptedTypes } => {
this._updateLastRowId() this._updateLastRowId()
return Object.fromEntries([...Object.entries(this.schema).map((entry) => [entry[0], entry[1].default ?? ''])]) return Object.fromEntries([...Object.entries(this.schema).map((entry) => [entry[0], entry[1].default ?? ''])])
} }
private _addRow = () => { private readonly _addRow = (): void => {
let newRow = this._getDefaultRow() const newRow = this._getDefaultRow()
this._rowsById.push({_id:this._lastRowId++, row: newRow}) this._rowsById.push({ _id: this._lastRowId++, row: newRow })
this.rows.push(newRow) this.rows.push(newRow)
this.requestUpdate('rows') this.requestUpdate('rows')
this.requestUpdate('_rowsById') this.requestUpdate('_rowsById')
this.dispatchEvent(new CustomEvent('update', { detail: this.rows })) this.dispatchEvent(new CustomEvent('update', { detail: this.rows }))
} }
private readonly _removeRow = (rowId: number): void => {
private _removeRow = (rowId: number) => { const rowToRemove = this._rowsById.filter(rowById => rowById._id === rowId).map(rowById => rowById.row)[0]
let rowToRemove = this._rowsById.filter(rowById => rowById._id == rowId).map(rowById => rowById.row)[0]
this._rowsById = this._rowsById.filter(rowById => rowById._id !== rowId) this._rowsById = this._rowsById.filter(rowById => rowById._id !== rowId)
this.rows = this.rows.filter((row) => row !== rowToRemove) this.rows = this.rows.filter((row) => row !== rowToRemove)
this.requestUpdate('rows') this.requestUpdate('rows')
@ -117,16 +118,16 @@ export class DynamicTableFormElement extends LivechatElement {
this.dispatchEvent(new CustomEvent('update', { detail: this.rows })) this.dispatchEvent(new CustomEvent('update', { detail: this.rows }))
} }
render = () => { protected override render = (): unknown => {
const inputId = `peertube-livechat-${this.formName.replace(/_/g, '-')}-table` const inputId = `peertube-livechat-${this.formName.replace(/_/g, '-')}-table`
this._updateLastRowId() this._updateLastRowId()
this._rowsById.filter(rowById => this.rows.includes(rowById.row)) this._rowsById.filter(rowById => this.rows.includes(rowById.row))
for (let row of this.rows) { for (const row of this.rows) {
if (this._rowsById.filter(rowById => rowById.row === row).length == 0) { if (this._rowsById.filter(rowById => rowById.row === row).length === 0) {
this._rowsById.push({_id: this._lastRowId++, row }) this._rowsById.push({ _id: this._lastRowId++, row })
} }
} }
@ -148,50 +149,68 @@ export class DynamicTableFormElement extends LivechatElement {
` `
} }
private _renderHeader = () => { private readonly _renderHeader = (): TemplateResult => {
return html`<thead> return html`<thead>
<tr> <tr>
${Object.entries(this.header).sort(([k1,_1], [k2,_2]) => this.columnOrder.indexOf(k1) - this.columnOrder.indexOf(k2)) ${Object.entries(this.header)
.map(([k,v]) => this._renderHeaderCell(v))} .sort(([k1, _1], [k2, _2]) => this.columnOrder.indexOf(k1) - this.columnOrder.indexOf(k2))
.map(([_, v]) => this._renderHeaderCell(v))}
<th scope="col"></th> <th scope="col"></th>
</tr> </tr>
</thead>` </thead>`
} }
private _renderHeaderCell = (headerCellData: { colName: TemplateResult, description: TemplateResult }) => { private readonly _renderHeaderCell = (headerCellData: { colName: TemplateResult
description: TemplateResult }): TemplateResult => {
return html`<th scope="col"> return html`<th scope="col">
<div data-toggle="tooltip" data-placement="bottom" data-html="true" title=${headerCellData.description}>${headerCellData.colName}</div> <div data-toggle="tooltip" data-placement="bottom" data-html="true" title=${headerCellData.description}>
${headerCellData.colName}
</div>
</th>` </th>`
} }
private _renderDataRow = (rowData: { _id: number; row: {[key: string]: DynamicTableAcceptedTypes} }) => { private readonly _renderDataRow = (rowData: { _id: number
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).sort((k1, k2) => this.columnOrder.indexOf(k1) - this.columnOrder.indexOf(k2)) ${Object.keys(this.header)
.map(k => this.renderDataCell([k, rowData.row[k] ?? this.schema[k].default], rowData._id))} .sort((k1, k2) => this.columnOrder.indexOf(k1) - this.columnOrder.indexOf(k2))
<td class="form-group"><button type="button" class="peertube-button-link orange-button dynamic-table-remove-row" @click=${() => this._removeRow(rowData._id)}>${unsafeHTML(RemoveSVG)}</button></td> .map(k => this.renderDataCell([k, rowData.row[k] ?? this.schema[k].default], rowData._id))}
<td class="form-group">
<button type="button"
class="peertube-button-link orange-button dynamic-table-remove-row"
@click=${() => this._removeRow(rowData._id)}>
${unsafeHTML(RemoveSVG)}
</button>
</td>
</tr>` </tr>`
} }
private _renderFooter = () => { private readonly _renderFooter = (): TemplateResult => {
return html`<tfoot> return html`<tfoot>
<tr> <tr>
${Object.values(this.header).map(() => html`<td></td>`)} ${Object.values(this.header).map(() => html`<td></td>`)}
<td><button type="button" class="peertube-button-link orange-button dynamic-table-add-row" @click=${this._addRow}>${unsafeHTML(AddSVG)}</button></td> <td>
<button type="button"
class="peertube-button-link orange-button dynamic-table-add-row"
@click=${this._addRow}>
${unsafeHTML(AddSVG)}
</button>
</td>
</tr> </tr>
</tfoot>` </tfoot>`
} }
renderDataCell = (property: [string, DynamicTableAcceptedTypes], rowId: number) => { renderDataCell = (property: [string, DynamicTableAcceptedTypes], rowId: number): TemplateResult => {
let [propertyName, propertyValue] = property let [propertyName, propertyValue] = property
const propertySchema = this.schema[propertyName] ?? {} const propertySchema = this.schema[propertyName] ?? {}
let formElement let formElement
const inputName = `${this.formName.replace(/-/g, '_')}_${propertyName.toString().replace(/-/g, '_')}_${rowId}` const inputName = `${this.formName.replace(/-/g, '_')}_${propertyName.toString().replace(/-/g, '_')}_${rowId}`
const inputId = `peertube-livechat-${this.formName.replace(/_/g, '-')}-${propertyName.toString().replace(/_/g, '-')}-${rowId}` const inputId =
`peertube-livechat-${this.formName.replace(/_/g, '-')}-${propertyName.toString().replace(/_/g, '-')}-${rowId}`
switch (propertySchema.default?.constructor) { switch (propertySchema.default?.constructor) {
case String: case String:
@ -215,15 +234,30 @@ export class DynamicTableFormElement extends LivechatElement {
case 'time': case 'time':
case 'url': case 'url':
case 'week': case 'week':
formElement = this._renderInput(rowId, inputId, inputName, propertyName, propertySchema, propertyValue as string) formElement = this._renderInput(rowId,
inputId,
inputName,
propertyName,
propertySchema,
propertyValue as string)
break break
case 'textarea': case 'textarea':
formElement = this._renderTextarea(rowId, inputId, inputName, propertyName, propertySchema, propertyValue as string) formElement = this._renderTextarea(rowId,
inputId,
inputName,
propertyName,
propertySchema,
propertyValue as string)
break break
case 'select': case 'select':
formElement = this._renderSelect(rowId, inputId, inputName, propertyName, propertySchema, propertyValue as string) formElement = this._renderSelect(rowId,
inputId,
inputName,
propertyName,
propertySchema,
propertyValue as string)
break break
} }
break break
@ -237,7 +271,12 @@ export class DynamicTableFormElement extends LivechatElement {
case 'datetime': case 'datetime':
case 'datetime-local': case 'datetime-local':
case 'time': case 'time':
formElement = this._renderInput(rowId, inputId, inputName, propertyName, propertySchema, (propertyValue as Date).toISOString()) formElement = this._renderInput(rowId,
inputId,
inputName,
propertyName,
propertySchema,
(propertyValue as Date).toISOString())
break break
} }
break break
@ -249,7 +288,12 @@ export class DynamicTableFormElement extends LivechatElement {
case 'number': case 'number':
case 'range': case 'range':
formElement = this._renderInput(rowId, inputId, inputName, propertyName, propertySchema, propertyValue as string) formElement = this._renderInput(rowId,
inputId,
inputName,
propertyName,
propertySchema,
propertyValue as string)
break break
} }
break break
@ -260,7 +304,12 @@ export class DynamicTableFormElement extends LivechatElement {
propertySchema.inputType = 'checkbox' propertySchema.inputType = 'checkbox'
case 'checkbox': case 'checkbox':
formElement = this._renderCheckbox(rowId, inputId, inputName, propertyName, propertySchema, propertyValue as boolean) formElement = this._renderCheckbox(rowId,
inputId,
inputName,
propertyName,
propertySchema,
propertyValue as boolean)
break break
} }
break break
@ -290,27 +339,32 @@ export class DynamicTableFormElement extends LivechatElement {
propertyValue = (propertyValue) ? [propertyValue as (number | string)] : [] propertyValue = (propertyValue) ? [propertyValue as (number | string)] : []
} }
formElement = this._renderInput(rowId, inputId, inputName, propertyName, propertySchema, formElement = this._renderInput(rowId, inputId, inputName, propertyName, propertySchema,
(propertyValue as Array<number | string>)?.join(propertySchema.separator ?? ',') ?? propertyValue ?? propertySchema.default ?? '') (propertyValue)?.join(propertySchema.separator ?? ',') ?? propertyValue ?? propertySchema.default ?? '')
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 = this._renderTextarea(rowId, inputId, inputName, propertyName, propertySchema,
(propertyValue as Array<number | string>)?.join(propertySchema.separator ?? ',') ?? propertyValue ?? propertySchema.default ?? '') (propertyValue)?.join(propertySchema.separator ?? ',') ?? propertyValue ?? propertySchema.default ?? '')
break break
} }
} }
if (!formElement) { if (!formElement) {
console.warn(`value type '${propertyValue.constructor}' is incompatible` console.warn(`value type '${(propertyValue.constructor.toString())}' is incompatible` +
+ `with field type '${propertySchema.inputType}' for form entry '${propertyName.toString()}'.`) `with field type '${propertySchema.inputType as string}' for form entry '${propertyName.toString()}'.`)
} }
return html`<td class="form-group">${formElement}</td>` return html`<td class="form-group">${formElement}</td>`
} }
_renderInput = (rowId: number, inputId: string, inputName: string, propertyName: string, propertySchema: CellDataSchema, propertyValue: string) => { _renderInput = (rowId: number,
inputId: string,
inputName: string,
propertyName: string,
propertySchema: CellDataSchema,
propertyValue: string): TemplateResult => {
return html`<input return html`<input
type=${propertySchema.inputType} type=${propertySchema.inputType}
name=${inputName} name=${inputName}
@ -324,13 +378,20 @@ export class DynamicTableFormElement extends LivechatElement {
@change=${(event: Event) => this._updatePropertyFromValue(event, propertyName, propertySchema, rowId)} @change=${(event: Event) => this._updatePropertyFromValue(event, propertyName, propertySchema, rowId)}
.value=${propertyValue} .value=${propertyValue}
/> />
${(propertySchema.datalist) ? html`<datalist id=${inputId + '-datalist'}> ${(propertySchema.datalist)
? html`<datalist id=${inputId + '-datalist'}>
${(propertySchema.datalist ?? []).map((value) => html`<option value=${value} />`)} ${(propertySchema.datalist ?? []).map((value) => html`<option value=${value} />`)}
</datalist>` : nothing} </datalist>`
: nothing}
` `
} }
_renderTextarea = (rowId: number, inputId: string, inputName: string, propertyName: string, propertySchema: CellDataSchema, propertyValue: string) => { _renderTextarea = (rowId: number,
inputId: string,
inputName: string,
propertyName: string,
propertySchema: CellDataSchema,
propertyValue: string): TemplateResult => {
return html`<textarea return html`<textarea
name=${inputName} name=${inputName}
class="form-control" class="form-control"
@ -344,7 +405,12 @@ export class DynamicTableFormElement extends LivechatElement {
></textarea>` ></textarea>`
} }
_renderCheckbox = (rowId: number, inputId: string, inputName: string, propertyName: string, propertySchema: CellDataSchema, propertyValue: boolean) => { _renderCheckbox = (rowId: number,
inputId: string,
inputName: string,
propertyName: string,
propertySchema: CellDataSchema,
propertyValue: boolean): TemplateResult => {
return html`<input return html`<input
type="checkbox" type="checkbox"
name=${inputName} name=${inputName}
@ -356,7 +422,12 @@ export class DynamicTableFormElement extends LivechatElement {
/>` />`
} }
_renderSelect = (rowId: number, inputId: string, inputName: string, propertyName: string, propertySchema: CellDataSchema, propertyValue: string) => { _renderSelect = (rowId: number,
inputId: string,
inputName: string,
propertyName: string,
propertySchema: CellDataSchema,
propertyValue: string): TemplateResult => {
return html`<select return html`<select
class="form-select" class="form-select"
aria-label="Default select example" aria-label="Default select example"
@ -370,13 +441,19 @@ export class DynamicTableFormElement extends LivechatElement {
</select>` </select>`
} }
_updatePropertyFromValue = (event: Event,
_updatePropertyFromValue = (event: Event, propertyName: string, propertySchema: CellDataSchema, rowId: number) => { propertyName: string,
let target = event.target as (HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement) propertySchema: CellDataSchema,
let value = (target) ? (target instanceof HTMLInputElement && target.type == "checkbox") ? !!(target.checked) : target.value : undefined rowId: number): undefined => {
const target = event.target as (HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement)
const value = (target)
? (target instanceof HTMLInputElement && target.type === 'checkbox')
? !!(target.checked)
: target.value
: undefined
if (value !== undefined) { if (value !== undefined) {
for (let 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:
@ -397,9 +474,8 @@ export class DynamicTableFormElement extends LivechatElement {
} }
console.warn(`Could not update property : Did not find a property named '${propertyName}' in row '${rowId}'`) console.warn(`Could not update property : Did not find a property named '${propertyName}' in row '${rowId}'`)
} } else {
else { console.warn('Could not update property : Target or value was undefined')
console.warn(`Could not update property : Target or value was undefined`)
} }
} }
} }

View File

@ -17,7 +17,6 @@ import { LivechatElement } from './livechat'
@customElement('livechat-help-button') @customElement('livechat-help-button')
export class HelpButtonElement extends LivechatElement { export class HelpButtonElement extends LivechatElement {
@consume({ context: registerClientOptionsContext, subscribe: true }) @consume({ context: registerClientOptionsContext, subscribe: true })
public registerClientOptions: RegisterClientOptions | undefined public registerClientOptions: RegisterClientOptions | undefined
@ -30,14 +29,16 @@ export class HelpButtonElement extends LivechatElement {
@state() @state()
public url: URL = new URL('https://lmddgtfy.net/') public url: URL = new URL('https://lmddgtfy.net/')
private _asyncTaskRender = new Task(this, { private readonly _asyncTaskRender = new Task(this, {
task: async ([registerClientOptions], {signal}) => { task: async ([registerClientOptions]) => {
this.url = new URL(registerClientOptions ? await localizedHelpUrl(registerClientOptions, { page: this.page }) : '') this.url = new URL(registerClientOptions
? await localizedHelpUrl(registerClientOptions, { page: this.page })
: '')
}, },
args: () => [this.registerClientOptions] args: () => [this.registerClientOptions]
}); })
render() { protected override render = (): unknown => {
return this._asyncTaskRender.render({ return this._asyncTaskRender.render({
complete: () => html`<a complete: () => html`<a
href="${this.url.href}" href="${this.url.href}"

View File

@ -8,7 +8,7 @@ import { LitElement } from 'lit'
* Base class for all Custom Elements. * Base class for all Custom Elements.
*/ */
export class LivechatElement extends LitElement { export class LivechatElement extends LitElement {
protected createRenderRoot = () => { protected override createRenderRoot = (): Element | ShadowRoot => {
return this return this
} }
} }