Skip to content

ActivityPub-federated video streaming platform using P2P directly in your web browser

Execute Angular migrations

Chocobozzz017795cf4543
diff --git a/.dprint.json b/.dprint.json
index 503010f3a4..6bd8acb84e 100644
--- a/.dprint.json
+++ b/.dprint.json
@@ -38,8 +38,8 @@
"forStatement.spaceAfterForKeyword": true,
"forStatement.spaceAfterSemiColons": true,
"functionDeclaration.spaceBeforeParentheses": true,
- "functionExpression.spaceBeforeParentheses": false,
- "functionExpression.spaceAfterFunctionKeyword": false,
+ "functionExpression.spaceBeforeParentheses": true,
+ "functionExpression.spaceAfterFunctionKeyword": true,
"getAccessor.spaceBeforeParentheses": true,
"ifStatement.spaceAfterIfKeyword": true,
"importDeclaration.spaceSurroundingNamedImports": true,
diff --git a/.eslintrc.json b/.eslintrc.json
index 17afd1b835..6e484c197b 100644
--- a/.eslintrc.json
+++ b/.eslintrc.json
@@ -50,7 +50,7 @@
"SwitchCase": 1,
"MemberExpression": "off",
// https://github.com/eslint/eslint/issues/15299
- "ignoredNodes": ["PropertyDefinition"]
+ "ignoredNodes": ["PropertyDefinition", "TSTypeParameterInstantiation"]
}
],
"@typescript-eslint/consistent-type-assertions": [
diff --git a/client/src/app/+about/about-contact/about-contact.component.ts b/client/src/app/+about/about-contact/about-contact.component.ts
index f8985f0987..fccceebb5c 100644
--- a/client/src/app/+about/about-contact/about-contact.component.ts
+++ b/client/src/app/+about/about-contact/about-contact.component.ts
@@ -1,5 +1,5 @@
import { NgClass, NgIf } from '@angular/common'
-import { Component, OnInit } from '@angular/core'
+import { Component, OnInit, inject } from '@angular/core'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { ActivatedRoute } from '@angular/router'
import { ServerService } from '@app/core'
@@ -26,20 +26,16 @@ type Prefill = {
imports: [ NgIf, FormsModule, ReactiveFormsModule, NgClass, AlertComponent ]
})
export class AboutContactComponent extends FormReactive implements OnInit {
+ protected formReactiveService = inject(FormReactiveService)
+ private route = inject(ActivatedRoute)
+ private instanceService = inject(InstanceService)
+ private serverService = inject(ServerService)
+
error: string
success: string
private serverConfig: HTMLServerConfig
- constructor (
- protected formReactiveService: FormReactiveService,
- private route: ActivatedRoute,
- private instanceService: InstanceService,
- private serverService: ServerService
- ) {
- super()
- }
-
get instanceName () {
return this.serverConfig.instance.name
}
@@ -68,17 +64,17 @@ export class AboutContactComponent extends FormReactive implements OnInit {
const body = this.form.value['body']
this.instanceService.contactAdministrator(fromEmail, fromName, subject, body)
- .subscribe({
- next: () => {
- this.success = $localize`Your message has been sent.`
- },
+ .subscribe({
+ next: () => {
+ this.success = $localize`Your message has been sent.`
+ },
- error: err => {
- this.error = err.status === HttpStatusCode.FORBIDDEN_403
- ? $localize`You already sent this form recently`
- : err.message
- }
- })
+ error: err => {
+ this.error = err.status === HttpStatusCode.FORBIDDEN_403
+ ? $localize`You already sent this form recently`
+ : err.message
+ }
+ })
}
private prefillForm (prefill: Prefill) {
diff --git a/client/src/app/+about/about-follows/about-follows.component.ts b/client/src/app/+about/about-follows/about-follows.component.ts
index fd677fdc2e..f2696d14af 100644
--- a/client/src/app/+about/about-follows/about-follows.component.ts
+++ b/client/src/app/+about/about-follows/about-follows.component.ts
@@ -1,5 +1,5 @@
import { DecimalPipe, NgFor, NgIf } from '@angular/common'
-import { Component, OnInit } from '@angular/core'
+import { Component, OnInit, inject } from '@angular/core'
import { RouterLink } from '@angular/router'
import { ComponentPagination, hasMoreItems, Notifier, RestService, ServerService } from '@app/core'
import { ActorAvatarComponent } from '@app/shared/shared-actor-image/actor-avatar.component'
@@ -29,8 +29,12 @@ import { SubscriptionImageComponent } from './subscription-image.component'
FollowerImageComponent
]
})
-
export class AboutFollowsComponent implements OnInit {
+ private server = inject(ServerService)
+ private restService = inject(RestService)
+ private notifier = inject(Notifier)
+ private followService = inject(InstanceFollowService)
+
instanceName: string
followers: Actor[] = []
@@ -58,13 +62,6 @@ export class AboutFollowsComponent implements OnInit {
order: -1
}
- constructor (
- private server: ServerService,
- private restService: RestService,
- private notifier: Notifier,
- private followService: InstanceFollowService
- ) { }
-
ngOnInit () {
this.loadMoreFollowers(true)
this.loadMoreSubscriptions(true)
@@ -96,20 +93,20 @@ export class AboutFollowsComponent implements OnInit {
const pagination = this.restService.componentToRestPagination(this.followersPagination)
this.followService.getFollowers({ pagination, sort: this.sort, state: 'accepted' })
- .subscribe({
- next: resultList => {
- if (reset) this.followers = []
+ .subscribe({
+ next: resultList => {
+ if (reset) this.followers = []
- const newFollowers = resultList.data.map(r => this.formatFollow(r.follower))
- this.followers = this.followers.concat(newFollowers)
+ const newFollowers = resultList.data.map(r => this.formatFollow(r.follower))
+ this.followers = this.followers.concat(newFollowers)
- this.followersPagination.totalItems = resultList.total
- },
+ this.followersPagination.totalItems = resultList.total
+ },
- error: err => this.notifier.error(err.message),
+ error: err => this.notifier.error(err.message),
- complete: () => this.loadingFollowers = false
- })
+ complete: () => this.loadingFollowers = false
+ })
}
loadMoreSubscriptions (reset = false) {
@@ -122,20 +119,20 @@ export class AboutFollowsComponent implements OnInit {
const pagination = this.restService.componentToRestPagination(this.subscriptionsPagination)
this.followService.getFollowing({ pagination, sort: this.sort, state: 'accepted' })
- .subscribe({
- next: resultList => {
- if (reset) this.subscriptions = []
+ .subscribe({
+ next: resultList => {
+ if (reset) this.subscriptions = []
- const newFollowings = resultList.data.map(r => this.formatFollow(r.following))
- this.subscriptions = this.subscriptions.concat(newFollowings)
+ const newFollowings = resultList.data.map(r => this.formatFollow(r.following))
+ this.subscriptions = this.subscriptions.concat(newFollowings)
- this.subscriptionsPagination.totalItems = resultList.total
- },
+ this.subscriptionsPagination.totalItems = resultList.total
+ },
- error: err => this.notifier.error(err.message),
+ error: err => this.notifier.error(err.message),
- complete: () => this.loadingSubscriptions = false
- })
+ complete: () => this.loadingSubscriptions = false
+ })
}
private formatFollow (actor: Actor) {
diff --git a/client/src/app/+about/about-follows/follower-image.component.ts b/client/src/app/+about/about-follows/follower-image.component.ts
index 2920402a0b..4bbeabf71a 100644
--- a/client/src/app/+about/about-follows/follower-image.component.ts
+++ b/client/src/app/+about/about-follows/follower-image.component.ts
@@ -1,4 +1,4 @@
-import { Component, OnInit } from '@angular/core'
+import { Component, OnInit, inject } from '@angular/core'
import { ServerService } from '@app/core'
import { Actor } from '@app/shared/shared-main/account/actor.model'
@@ -9,9 +9,9 @@ import { Actor } from '@app/shared/shared-main/account/actor.model'
standalone: true
})
export class FollowerImageComponent implements OnInit {
- avatarUrl: string
+ private server = inject(ServerService)
- constructor (private server: ServerService) {}
+ avatarUrl: string
ngOnInit () {
this.avatarUrl = Actor.GET_ACTOR_AVATAR_URL(this.server.getHTMLConfig().instance, 30)
diff --git a/client/src/app/+about/about-follows/subscription-image.component.ts b/client/src/app/+about/about-follows/subscription-image.component.ts
index 738b32c7f5..e5a99279c6 100644
--- a/client/src/app/+about/about-follows/subscription-image.component.ts
+++ b/client/src/app/+about/about-follows/subscription-image.component.ts
@@ -1,4 +1,4 @@
-import { Component, OnInit } from '@angular/core'
+import { Component, OnInit, inject } from '@angular/core'
import { ServerService } from '@app/core'
import { Actor } from '@app/shared/shared-main/account/actor.model'
@@ -9,9 +9,9 @@ import { Actor } from '@app/shared/shared-main/account/actor.model'
standalone: true
})
export class SubscriptionImageComponent implements OnInit {
- avatarUrl: string
+ private server = inject(ServerService)
- constructor (private server: ServerService) {}
+ avatarUrl: string
ngOnInit () {
this.avatarUrl = Actor.GET_ACTOR_AVATAR_URL(this.server.getHTMLConfig().instance, 30)
diff --git a/client/src/app/+about/about-instance/about-instance.component.ts b/client/src/app/+about/about-instance/about-instance.component.ts
index dd734743dc..6cfcf22cf7 100644
--- a/client/src/app/+about/about-instance/about-instance.component.ts
+++ b/client/src/app/+about/about-instance/about-instance.component.ts
@@ -1,4 +1,4 @@
-import { Component, ElementRef, OnInit, ViewChild } from '@angular/core'
+import { Component, ElementRef, OnInit, inject, viewChild } from '@angular/core'
import { ActivatedRoute, RouterOutlet } from '@angular/router'
import { AboutHTML } from '@app/shared/shared-main/instance/instance.service'
import { ServerConfig, ServerStats } from '@peertube/peertube-models'
@@ -17,17 +17,15 @@ import { HorizontalMenuComponent, HorizontalMenuEntry } from '@app/shared/shared
]
})
export class AboutInstanceComponent implements OnInit {
- @ViewChild('descriptionWrapper') descriptionWrapper: ElementRef<HTMLInputElement>
+ private route = inject(ActivatedRoute)
+
+ readonly descriptionWrapper = viewChild<ElementRef<HTMLInputElement>>('descriptionWrapper')
aboutHTML: AboutHTML
serverStats: ServerStats
serverConfig: ServerConfig
menuEntries: HorizontalMenuEntry[] = []
- constructor (
- private route: ActivatedRoute
- ) {}
-
ngOnInit () {
const {
aboutHTML,
diff --git a/client/src/app/+about/about-instance/about-instance.resolver.ts b/client/src/app/+about/about-instance/about-instance.resolver.ts
index ed1054c3ce..cb96b2f761 100644
--- a/client/src/app/+about/about-instance/about-instance.resolver.ts
+++ b/client/src/app/+about/about-instance/about-instance.resolver.ts
@@ -1,6 +1,6 @@
import { forkJoin, Observable } from 'rxjs'
import { map, switchMap } from 'rxjs/operators'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { ServerService } from '@app/core'
import { About, ServerConfig, ServerStats } from '@peertube/peertube-models'
import { AboutHTML, InstanceService } from '@app/shared/shared-main/instance/instance.service'
@@ -18,12 +18,9 @@ export type ResolverData = {
@Injectable()
export class AboutInstanceResolver {
-
- constructor (
- private instanceService: InstanceService,
- private customMarkupService: CustomMarkupService,
- private serverService: ServerService
- ) {}
+ private instanceService = inject(InstanceService)
+ private customMarkupService = inject(CustomMarkupService)
+ private serverService = inject(ServerService)
resolve (): Observable<ResolverData> {
return forkJoin([
diff --git a/client/src/app/+about/about-instance/children/about-instance-home.component.ts b/client/src/app/+about/about-instance/children/about-instance-home.component.ts
index 33abd13c8a..0771342100 100644
--- a/client/src/app/+about/about-instance/children/about-instance-home.component.ts
+++ b/client/src/app/+about/about-instance/children/about-instance-home.component.ts
@@ -1,5 +1,5 @@
import { NgFor, NgIf } from '@angular/common'
-import { Component, OnInit, ViewChild } from '@angular/core'
+import { Component, OnInit, inject, viewChild } from '@angular/core'
import { ActivatedRoute, Router } from '@angular/router'
import { ServerService } from '@app/core'
import { AboutHTML } from '@app/shared/shared-main/instance/instance.service'
@@ -19,7 +19,11 @@ import { ResolverData } from '../about-instance.resolver'
]
})
export class AboutInstanceHomeComponent implements OnInit {
- @ViewChild('supportModal') supportModal: SupportModalComponent
+ private router = inject(Router)
+ private route = inject(ActivatedRoute)
+ private serverService = inject(ServerService)
+
+ readonly supportModal = viewChild<SupportModalComponent>('supportModal')
aboutHTML: AboutHTML
descriptionElement: HTMLDivElement
@@ -29,12 +33,6 @@ export class AboutInstanceHomeComponent implements OnInit {
config: HTMLServerConfig
- constructor (
- private router: Router,
- private route: ActivatedRoute,
- private serverService: ServerService
- ) {}
-
ngOnInit () {
this.config = this.serverService.getHTMLConfig()
@@ -55,7 +53,7 @@ export class AboutInstanceHomeComponent implements OnInit {
if (!data?.isSupport) return
setTimeout(() => {
- const modal = this.supportModal.show()
+ const modal = this.supportModal().show()
modal.hidden.subscribe(() => this.router.navigateByUrl('/about/instance/home'))
}, 0)
diff --git a/client/src/app/+about/about-instance/children/about-instance-moderation.component.ts b/client/src/app/+about/about-instance/children/about-instance-moderation.component.ts
index ef0e8a391a..5d8e71bc81 100644
--- a/client/src/app/+about/about-instance/children/about-instance-moderation.component.ts
+++ b/client/src/app/+about/about-instance/children/about-instance-moderation.component.ts
@@ -1,5 +1,5 @@
import { CommonModule } from '@angular/common'
-import { Component, OnInit } from '@angular/core'
+import { Component, OnInit, inject } from '@angular/core'
import { ActivatedRoute } from '@angular/router'
import { ServerService } from '@app/core'
import { AboutHTML } from '@app/shared/shared-main/instance/instance.service'
@@ -12,12 +12,10 @@ import { PluginSelectorDirective } from '@app/shared/shared-main/plugins/plugin-
imports: [ CommonModule, PluginSelectorDirective ]
})
export class AboutInstanceModerationComponent implements OnInit {
- aboutHTML: AboutHTML
+ private route = inject(ActivatedRoute)
+ private serverService = inject(ServerService)
- constructor (
- private route: ActivatedRoute,
- private serverService: ServerService
- ) {}
+ aboutHTML: AboutHTML
get instanceName () {
return this.serverService.getHTMLConfig().instance.name
diff --git a/client/src/app/+about/about-instance/children/about-instance-team.component.ts b/client/src/app/+about/about-instance/children/about-instance-team.component.ts
index 6a8f7995f9..5aa4296c62 100644
--- a/client/src/app/+about/about-instance/children/about-instance-team.component.ts
+++ b/client/src/app/+about/about-instance/children/about-instance-team.component.ts
@@ -1,5 +1,5 @@
import { CommonModule } from '@angular/common'
-import { Component, OnInit } from '@angular/core'
+import { Component, OnInit, inject } from '@angular/core'
import { ActivatedRoute } from '@angular/router'
import { ServerService } from '@app/core'
import { AboutHTML } from '@app/shared/shared-main/instance/instance.service'
@@ -11,12 +11,10 @@ import { ResolverData } from '../about-instance.resolver'
imports: [ CommonModule ]
})
export class AboutInstanceTeamComponent implements OnInit {
- aboutHTML: AboutHTML
+ private route = inject(ActivatedRoute)
+ private serverService = inject(ServerService)
- constructor (
- private route: ActivatedRoute,
- private serverService: ServerService
- ) {}
+ aboutHTML: AboutHTML
get instanceName () {
return this.serverService.getHTMLConfig().instance.name
diff --git a/client/src/app/+about/about-instance/children/about-instance-tech.component.ts b/client/src/app/+about/about-instance/children/about-instance-tech.component.ts
index 4e5ba3bd9e..3e63b6e241 100644
--- a/client/src/app/+about/about-instance/children/about-instance-tech.component.ts
+++ b/client/src/app/+about/about-instance/children/about-instance-tech.component.ts
@@ -1,5 +1,5 @@
import { CommonModule } from '@angular/common'
-import { Component, OnInit } from '@angular/core'
+import { Component, OnInit, inject } from '@angular/core'
import { ActivatedRoute } from '@angular/router'
import { ServerService } from '@app/core'
import { AboutHTML } from '@app/shared/shared-main/instance/instance.service'
@@ -13,12 +13,10 @@ import { InstanceFeaturesTableComponent } from '@app/shared/shared-instance/inst
imports: [ CommonModule, PluginSelectorDirective, InstanceFeaturesTableComponent ]
})
export class AboutInstanceTechComponent implements OnInit {
- aboutHTML: AboutHTML
+ private route = inject(ActivatedRoute)
+ private serverService = inject(ServerService)
- constructor (
- private route: ActivatedRoute,
- private serverService: ServerService
- ) {}
+ aboutHTML: AboutHTML
get instanceName () {
return this.serverService.getHTMLConfig().instance.name
diff --git a/client/src/app/+about/about-instance/instance-stat-rules.component.html b/client/src/app/+about/about-instance/instance-stat-rules.component.html
index 156e2523d6..868fbf9ef1 100644
--- a/client/src/app/+about/about-instance/instance-stat-rules.component.html
+++ b/client/src/app/+about/about-instance/instance-stat-rules.component.html
@@ -5,37 +5,37 @@
<div class="blocks" myPluginSelector pluginSelectorId="about-instance-statistics">
<div class="stat">
- <strong>{{ stats.totalModerators + stats.totalAdmins | number }}</strong>
+ <strong>{{ stats().totalModerators + stats().totalAdmins | number }}</strong>
<div i18n>moderators</div>
<my-global-icon iconName="moderation"></my-global-icon>
</div>
<div class="stat">
- <strong>{{ stats.totalUsers | number }}</strong>
+ <strong>{{ stats().totalUsers | number }}</strong>
<div i18n>users</div>
<my-global-icon iconName="user"></my-global-icon>
</div>
<div class="stat">
- <strong>{{ stats.totalLocalVideos | number }}</strong>
+ <strong>{{ stats().totalLocalVideos | number }}</strong>
<a routerLink="/videos/browse" [queryParams]="{ scope: 'local' }" i18n>videos</a>
<my-global-icon iconName="videos"></my-global-icon>
</div>
<div class="stat">
- <strong>{{ stats.totalLocalVideoViews | number }}</strong>
+ <strong>{{ stats().totalLocalVideoViews | number }}</strong>
<div i18n>views</div>
<my-global-icon iconName="eye-open"></my-global-icon>
</div>
<div class="stat">
- <strong>{{ stats.totalLocalVideoComments | number }}</strong>
+ <strong>{{ stats().totalLocalVideoComments | number }}</strong>
<div i18n>comments</div>
<my-global-icon iconName="message-circle"></my-global-icon>
</div>
<div class="stat">
- <strong>{{ stats.totalLocalVideoFilesSize | bytes:1 }}</strong>
+ <strong>{{ stats().totalLocalVideoFilesSize | bytes:1 }}</strong>
<div i18n>hosted videos</div>
<my-global-icon iconName="film"></my-global-icon>
</div>
@@ -47,7 +47,7 @@
<div class="blocks">
- <div class="usage-rule" *ngIf="config.instance.serverCountry">
+ <div class="usage-rule" *ngIf="config().instance.serverCountry">
<div class="icon-container">
<my-global-icon iconName="message-circle"></my-global-icon>
@@ -57,10 +57,10 @@
</div>
<div>
- <strong i18n>This platform has been created in {{ config.instance.serverCountry }}</strong>
+ <strong i18n>This platform has been created in {{ config().instance.serverCountry }}</strong>
<div class="rule-content">
<ng-container i18n>Your content (comments, videos...) must comply with the legislation in force in this country.</ng-container>
- <ng-container *ngIf="aboutHTML.codeOfConduct" i18n> You must also follow our <a routerLink="/about/instance/moderation">code of conduct</a>.</ng-container>
+ <ng-container *ngIf="aboutHTML().codeOfConduct" i18n> You must also follow our <a routerLink="/about/instance/moderation">code of conduct</a>.</ng-container>
</div>
</div>
</div>
@@ -69,7 +69,7 @@
<div class="icon-container">
<my-global-icon iconName="user"></my-global-icon>
- @if (config.signup.allowed && config.signup.allowedForCurrentIP) {
+ @if (config().signup.allowed && config().signup.allowedForCurrentIP) {
<div class="icon-status">
<my-global-icon iconName="tick"></my-global-icon>
</div>
@@ -81,12 +81,12 @@
</div>
<div>
- @if (config.signup.allowed && config.signup.allowedForCurrentIP) {
- @if (config.signup.requiresApproval) {
+ @if (config().signup.allowed && config().signup.allowedForCurrentIP) {
+ @if (config().signup.requiresApproval) {
<strong i18n>You can <a routerLink="/signup">request an account</a> on our platform</strong>
- @if (stats.averageRegistrationRequestResponseTimeMs) {
- <div class="rule-content" i18n>Our moderator will validate it within a {{ stats.averageRegistrationRequestResponseTimeMs | myDaysDurationFormatter }}.</div>
+ @if (stats().averageRegistrationRequestResponseTimeMs) {
+ <div class="rule-content" i18n>Our moderator will validate it within a {{ stats().averageRegistrationRequestResponseTimeMs | myDaysDurationFormatter }}.</div>
} @else {
<div class="rule-content" i18n>Our moderator will validate it within a few days.</div>
}
@@ -99,7 +99,7 @@
</div>
</div>
- <div class="usage-rule" *ngIf="config.federation.enabled">
+ <div class="usage-rule" *ngIf="config().federation.enabled">
<div class="icon-container">
<my-global-icon iconName="fediverse"></my-global-icon>
diff --git a/client/src/app/+about/about-instance/instance-stat-rules.component.ts b/client/src/app/+about/about-instance/instance-stat-rules.component.ts
index 0bc4997052..91bd8ffbff 100644
--- a/client/src/app/+about/about-instance/instance-stat-rules.component.ts
+++ b/client/src/app/+about/about-instance/instance-stat-rules.component.ts
@@ -1,5 +1,5 @@
import { CommonModule, DecimalPipe, NgIf } from '@angular/common'
-import { Component, Input } from '@angular/core'
+import { Component, inject, input } from '@angular/core'
import { RouterLink } from '@angular/router'
import { BytesPipe } from '@app/shared/shared-main/common/bytes.pipe'
import { DaysDurationFormatterPipe } from '@app/shared/shared-main/date/days-duration-formatter.pipe'
@@ -25,13 +25,11 @@ import { AuthService } from '@app/core'
]
})
export class InstanceStatRulesComponent {
- @Input({ required: true }) stats: ServerStats
- @Input({ required: true }) config: ServerConfig
- @Input({ required: true }) aboutHTML: AboutHTML
+ private auth = inject(AuthService)
- constructor (private auth: AuthService) {
-
- }
+ readonly stats = input.required<ServerStats>()
+ readonly config = input.required<ServerConfig>()
+ readonly aboutHTML = input.required<AboutHTML>()
canUpload () {
const user = this.auth.getUser()
@@ -42,14 +40,16 @@ export class InstanceStatRulesComponent {
return true
}
- return this.config.user.videoQuota !== 0 && this.config.user.videoQuotaDaily !== 0
+ const config = this.config()
+ return config.user.videoQuota !== 0 && config.user.videoQuotaDaily !== 0
}
canPublishLive () {
- return this.config.live.enabled
+ return this.config().live.enabled
}
isContactFormEnabled () {
- return this.config.email.enabled && this.config.contactForm.enabled
+ const config = this.config()
+ return config.email.enabled && config.contactForm.enabled
}
}
diff --git a/client/src/app/+about/about-peertube/about-peertube.component.ts b/client/src/app/+about/about-peertube/about-peertube.component.ts
index 729034dc81..08bfc6b66e 100644
--- a/client/src/app/+about/about-peertube/about-peertube.component.ts
+++ b/client/src/app/+about/about-peertube/about-peertube.component.ts
@@ -1,4 +1,4 @@
-import { Component, AfterViewChecked } from '@angular/core'
+import { Component, AfterViewChecked, inject } from '@angular/core'
import { ViewportScroller } from '@angular/common'
@Component({
@@ -7,13 +7,10 @@ import { ViewportScroller } from '@angular/common'
styleUrls: [ './about-peertube.component.scss' ],
standalone: true
})
-
export class AboutPeertubeComponent implements AfterViewChecked {
- private lastScrollHash: string
+ private viewportScroller = inject(ViewportScroller)
- constructor (
- private viewportScroller: ViewportScroller
- ) {}
+ private lastScrollHash: string
ngAfterViewChecked () {
if (window.location.hash && window.location.hash !== this.lastScrollHash) {
diff --git a/client/src/app/+about/about.component.ts b/client/src/app/+about/about.component.ts
index 86cac1bf5a..b09b546609 100644
--- a/client/src/app/+about/about.component.ts
+++ b/client/src/app/+about/about.component.ts
@@ -1,5 +1,5 @@
import { CommonModule } from '@angular/common'
-import { Component, OnInit, ViewChild } from '@angular/core'
+import { Component, OnInit, inject, viewChild } from '@angular/core'
import { RouterOutlet } from '@angular/router'
import { ServerService } from '@app/core'
import { GlobalIconComponent } from '@app/shared/shared-icons/global-icon.component'
@@ -14,11 +14,12 @@ import { HTMLServerConfig } from '@peertube/peertube-models'
selector: 'my-about',
templateUrl: './about.component.html',
styleUrls: [ './about.component.scss' ],
- imports: [ CommonModule, RouterOutlet, HorizontalMenuComponent, GlobalIconComponent, ButtonComponent, SupportModalComponent ]
+ imports: [ CommonModule, RouterOutlet, HorizontalMenuComponent, GlobalIconComponent, ButtonComponent ]
})
-
export class AboutComponent implements OnInit {
- @ViewChild('supportModal') supportModal: SupportModalComponent
+ private server = inject(ServerService)
+
+ readonly supportModal = viewChild<SupportModalComponent>('supportModal')
bannerUrl: string
avatarUrl: string
@@ -27,12 +28,6 @@ export class AboutComponent implements OnInit {
config: HTMLServerConfig
- constructor (
- private server: ServerService
- ) {
-
- }
-
ngOnInit () {
this.config = this.server.getHTMLConfig()
diff --git a/client/src/app/+accounts/account-video-channels/account-video-channels.component.ts b/client/src/app/+accounts/account-video-channels/account-video-channels.component.ts
index 10132a6c8a..e185c83721 100644
--- a/client/src/app/+accounts/account-video-channels/account-video-channels.component.ts
+++ b/client/src/app/+accounts/account-video-channels/account-video-channels.component.ts
@@ -1,6 +1,6 @@
import { from, Subject, Subscription } from 'rxjs'
import { concatMap, map, switchMap, tap } from 'rxjs/operators'
-import { Component, OnDestroy, OnInit } from '@angular/core'
+import { Component, OnDestroy, OnInit, inject } from '@angular/core'
import { ComponentPagination, hasMoreItems, MarkdownService, User, UserService } from '@app/core'
import { SimpleMemoize } from '@app/helpers'
import { NSFWPolicyType, VideoSortField } from '@peertube/peertube-models'
@@ -24,12 +24,18 @@ import { Video } from '@app/shared/shared-main/video/video.model'
imports: [ NgIf, InfiniteScrollerDirective, NgFor, ActorAvatarComponent, RouterLink, SubscribeButtonComponent, VideoMiniatureComponent ]
})
export class AccountVideoChannelsComponent implements OnInit, OnDestroy {
+ private accountService = inject(AccountService)
+ private videoChannelService = inject(VideoChannelService)
+ private videoService = inject(VideoService)
+ private markdown = inject(MarkdownService)
+ private userService = inject(UserService)
+
account: Account
videoChannels: VideoChannel[] = []
videos: { [id: number]: { total: number, videos: Video[] } } = {}
- channelsDescriptionHTML: { [ id: number ]: string } = {}
+ channelsDescriptionHTML: { [id: number]: string } = {}
channelPagination: ComponentPagination = {
currentPage: 1,
@@ -61,23 +67,15 @@ export class AccountVideoChannelsComponent implements OnInit, OnDestroy {
private accountSub: Subscription
- constructor (
- private accountService: AccountService,
- private videoChannelService: VideoChannelService,
- private videoService: VideoService,
- private markdown: MarkdownService,
- private userService: UserService
- ) { }
-
ngOnInit () {
// Parent get the account for us
this.accountSub = this.accountService.accountLoaded
- .subscribe(account => {
- this.account = account
- this.videoChannels = []
+ .subscribe(account => {
+ this.account = account
+ this.videoChannels = []
- this.loadMoreChannels()
- })
+ this.loadMoreChannels()
+ })
this.userService.getAnonymousOrLoggedUser()
.subscribe(user => {
diff --git a/client/src/app/+accounts/account-videos/account-videos.component.ts b/client/src/app/+accounts/account-videos/account-videos.component.ts
index 09051ef824..0a6013bea0 100644
--- a/client/src/app/+accounts/account-videos/account-videos.component.ts
+++ b/client/src/app/+accounts/account-videos/account-videos.component.ts
@@ -1,5 +1,5 @@
import { NgIf } from '@angular/common'
-import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core'
+import { Component, OnDestroy, OnInit, inject, viewChild } from '@angular/core'
import { ComponentPaginationLight, DisableForReuseHook, ScreenService } from '@app/core'
import { Account } from '@app/shared/shared-main/account/account.model'
import { AccountService } from '@app/shared/shared-main/account/account.service'
@@ -15,7 +15,11 @@ import { VideosListComponent } from '../../shared/shared-video-miniature/videos-
imports: [ NgIf, VideosListComponent ]
})
export class AccountVideosComponent implements OnInit, OnDestroy, DisableForReuseHook {
- @ViewChild('videosList') videosList: VideosListComponent
+ private screenService = inject(ScreenService)
+ private accountService = inject(AccountService)
+ private videoService = inject(VideoService)
+
+ readonly videosList = viewChild<VideosListComponent>('videosList')
getVideosObservableFunction = this.getVideosObservable.bind(this)
getSyndicationItemsFunction = this.getSyndicationItems.bind(this)
@@ -29,19 +33,12 @@ export class AccountVideosComponent implements OnInit, OnDestroy, DisableForReus
private accountSub: Subscription
- constructor (
- private screenService: ScreenService,
- private accountService: AccountService,
- private videoService: VideoService
- ) {
- }
-
ngOnInit () {
// Parent get the account for us
this.accountSub = this.accountService.accountLoaded
.subscribe(account => {
this.account = account
- if (this.alreadyLoaded) this.videosList.reloadVideos()
+ if (this.alreadyLoaded) this.videosList().reloadVideos()
this.alreadyLoaded = true
})
diff --git a/client/src/app/+accounts/accounts.component.ts b/client/src/app/+accounts/accounts.component.ts
index f06f2915b1..55b9fd5ff0 100644
--- a/client/src/app/+accounts/accounts.component.ts
+++ b/client/src/app/+accounts/accounts.component.ts
@@ -1,5 +1,5 @@
import { NgClass, NgIf } from '@angular/common'
-import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core'
+import { Component, OnDestroy, OnInit, inject, viewChild } from '@angular/core'
import { ActivatedRoute, Router, RouterLink, RouterLinkActive, RouterOutlet } from '@angular/router'
import { AuthService, MarkdownService, MetaService, Notifier, RedirectService, RestExtractor, ScreenService, UserService } from '@app/core'
import { Account } from '@app/shared/shared-main/account/account.model'
@@ -44,7 +44,22 @@ import { SubscribeButtonComponent } from '../shared/shared-user-subscription/sub
]
})
export class AccountsComponent implements OnInit, OnDestroy {
- @ViewChild('accountReportModal') accountReportModal: AccountReportComponent
+ private route = inject(ActivatedRoute)
+ private router = inject(Router)
+ private userService = inject(UserService)
+ private accountService = inject(AccountService)
+ private videoChannelService = inject(VideoChannelService)
+ private notifier = inject(Notifier)
+ private restExtractor = inject(RestExtractor)
+ private redirectService = inject(RedirectService)
+ private authService = inject(AuthService)
+ private videoService = inject(VideoService)
+ private markdown = inject(MarkdownService)
+ private blocklist = inject(BlocklistService)
+ private screenService = inject(ScreenService)
+ private metaService = inject(MetaService)
+
+ readonly accountReportModal = viewChild<AccountReportComponent>('accountReportModal')
account: Account
accountUser: User
@@ -62,24 +77,6 @@ export class AccountsComponent implements OnInit, OnDestroy {
private routeSub: Subscription
- constructor (
- private route: ActivatedRoute,
- private router: Router,
- private userService: UserService,
- private accountService: AccountService,
- private videoChannelService: VideoChannelService,
- private notifier: Notifier,
- private restExtractor: RestExtractor,
- private redirectService: RedirectService,
- private authService: AuthService,
- private videoService: VideoService,
- private markdown: MarkdownService,
- private blocklist: BlocklistService,
- private screenService: ScreenService,
- private metaService: MetaService
- ) {
- }
-
ngOnInit () {
this.routeSub = this.route.params
.pipe(
@@ -88,10 +85,12 @@ export class AccountsComponent implements OnInit, OnDestroy {
switchMap(accountId => this.accountService.getAccount(accountId)),
tap(account => this.onAccount(account)),
switchMap(account => this.videoChannelService.listAccountVideoChannels({ account })),
- catchError(err => this.restExtractor.redirectTo404IfNotFound(err, 'other', [
- HttpStatusCode.BAD_REQUEST_400,
- HttpStatusCode.NOT_FOUND_404
- ]))
+ catchError(err =>
+ this.restExtractor.redirectTo404IfNotFound(err, 'other', [
+ HttpStatusCode.BAD_REQUEST_400,
+ HttpStatusCode.NOT_FOUND_404
+ ])
+ )
)
.subscribe({
next: videoChannels => {
@@ -187,7 +186,7 @@ export class AccountsComponent implements OnInit, OnDestroy {
}
private showReportModal () {
- this.accountReportModal.show(this.account)
+ this.accountReportModal().show(this.account)
}
private loadUserIfNeeded (account: Account) {
diff --git a/client/src/app/+admin/admin-moderation.component.ts b/client/src/app/+admin/admin-moderation.component.ts
index 4ad157720e..1e0e66c77a 100644
--- a/client/src/app/+admin/admin-moderation.component.ts
+++ b/client/src/app/+admin/admin-moderation.component.ts
@@ -1,4 +1,4 @@
-import { Component, OnInit } from '@angular/core'
+import { Component, OnInit, inject } from '@angular/core'
import { RouterOutlet } from '@angular/router'
import { AuthService, ServerService } from '@app/core'
import { HorizontalMenuComponent, HorizontalMenuEntry } from '@app/shared/shared-main/menu/horizontal-menu.component'
@@ -9,12 +9,10 @@ import { UserRight, UserRightType } from '@peertube/peertube-models'
imports: [ HorizontalMenuComponent, RouterOutlet ]
})
export class AdminModerationComponent implements OnInit {
- menuEntries: HorizontalMenuEntry[] = []
+ private auth = inject(AuthService)
+ private server = inject(ServerService)
- constructor (
- private auth: AuthService,
- private server: ServerService
- ) { }
+ menuEntries: HorizontalMenuEntry[] = []
ngOnInit () {
this.server.configReloaded.subscribe(() => this.buildMenu())
diff --git a/client/src/app/+admin/admin-overview.component.ts b/client/src/app/+admin/admin-overview.component.ts
index 92600e0ee7..2b73f8f3d9 100644
--- a/client/src/app/+admin/admin-overview.component.ts
+++ b/client/src/app/+admin/admin-overview.component.ts
@@ -1,4 +1,4 @@
-import { Component, OnInit } from '@angular/core'
+import { Component, OnInit, inject } from '@angular/core'
import { RouterOutlet } from '@angular/router'
import { AuthService } from '@app/core'
import { HorizontalMenuComponent, HorizontalMenuEntry } from '@app/shared/shared-main/menu/horizontal-menu.component'
@@ -9,11 +9,9 @@ import { UserRight, UserRightType } from '@peertube/peertube-models'
imports: [ HorizontalMenuComponent, RouterOutlet ]
})
export class AdminOverviewComponent implements OnInit {
- menuEntries: HorizontalMenuEntry[] = []
+ private auth = inject(AuthService)
- constructor (
- private auth: AuthService
- ) { }
+ menuEntries: HorizontalMenuEntry[] = []
ngOnInit () {
this.buildMenu()
diff --git a/client/src/app/+admin/admin-settings.component.ts b/client/src/app/+admin/admin-settings.component.ts
index b4318a54c4..955b9ff125 100644
--- a/client/src/app/+admin/admin-settings.component.ts
+++ b/client/src/app/+admin/admin-settings.component.ts
@@ -1,4 +1,4 @@
-import { Component, OnInit } from '@angular/core'
+import { Component, OnInit, inject } from '@angular/core'
import { RouterOutlet } from '@angular/router'
import { AuthService, ServerService } from '@app/core'
import { HorizontalMenuComponent, HorizontalMenuEntry } from '@app/shared/shared-main/menu/horizontal-menu.component'
@@ -9,12 +9,10 @@ import { PluginType, UserRight, UserRightType } from '@peertube/peertube-models'
imports: [ HorizontalMenuComponent, RouterOutlet ]
})
export class AdminSettingsComponent implements OnInit {
- menuEntries: HorizontalMenuEntry[] = []
+ private auth = inject(AuthService)
+ private server = inject(ServerService)
- constructor (
- private auth: AuthService,
- private server: ServerService
- ) { }
+ menuEntries: HorizontalMenuEntry[] = []
ngOnInit () {
this.server.configReloaded.subscribe(() => this.buildMenu())
diff --git a/client/src/app/+admin/config/edit-custom-config/edit-advanced-configuration.component.html b/client/src/app/+admin/config/edit-custom-config/edit-advanced-configuration.component.html
index 8e5d62b8e6..d5e6510c97 100644
--- a/client/src/app/+admin/config/edit-custom-config/edit-advanced-configuration.component.html
+++ b/client/src/app/+admin/config/edit-custom-config/edit-advanced-configuration.component.html
@@ -1,4 +1,4 @@
-<ng-container [formGroup]="form">
+<ng-container [formGroup]="form()">
<div class="pt-two-cols mt-5"> <!-- cache grid -->
@@ -17,12 +17,12 @@
<div class="number-with-unit">
<input
type="number" min="0" id="cachePreviewsSize" class="form-control"
- formControlName="size" [ngClass]="{ 'input-error': formErrors['cache.previews.size'] }"
+ formControlName="size" [ngClass]="{ 'input-error': formErrors()['cache.previews.size'] }"
>
<span i18n>{getCacheSize('previews'), plural, =1 {cached image} other {cached images}}</span>
</div>
- <div *ngIf="formErrors.cache.previews.size" class="form-error" role="alert">{{ formErrors.cache.previews.size }}</div>
+ <div *ngIf="formErrors().cache.previews.size" class="form-error" role="alert">{{ formErrors().cache.previews.size }}</div>
</div>
<div class="form-group" formGroupName="captions">
@@ -31,12 +31,12 @@
<div class="number-with-unit">
<input
type="number" min="0" id="cacheCaptionsSize" class="form-control"
- formControlName="size" [ngClass]="{ 'input-error': formErrors['cache.captions.size'] }"
+ formControlName="size" [ngClass]="{ 'input-error': formErrors()['cache.captions.size'] }"
>
<span i18n>{getCacheSize('captions'), plural, =1 {cached caption} other {cached captions}}</span>
</div>
- <div *ngIf="formErrors.cache.captions.size" class="form-error" role="alert">{{ formErrors.cache.captions.size }}</div>
+ <div *ngIf="formErrors().cache.captions.size" class="form-error" role="alert">{{ formErrors().cache.captions.size }}</div>
</div>
<div class="form-group" formGroupName="torrents">
@@ -45,12 +45,12 @@
<div class="number-with-unit">
<input
type="number" min="0" id="cacheTorrentsSize" class="form-control"
- formControlName="size" [ngClass]="{ 'input-error': formErrors['cache.torrents.size'] }"
+ formControlName="size" [ngClass]="{ 'input-error': formErrors()['cache.torrents.size'] }"
>
<span i18n>{getCacheSize('torrents'), plural, =1 {cached torrent} other {cached torrents}}</span>
</div>
- <div *ngIf="formErrors.cache.torrents.size" class="form-error" role="alert">{{ formErrors.cache.torrents.size }}</div>
+ <div *ngIf="formErrors().cache.torrents.size" class="form-error" role="alert">{{ formErrors().cache.torrents.size }}</div>
</div>
<div class="form-group" formGroupName="torrents">
@@ -59,12 +59,12 @@
<div class="number-with-unit">
<input
type="number" min="0" id="cacheStoryboardsSize" class="form-control"
- formControlName="size" [ngClass]="{ 'input-error': formErrors['cache.storyboards.size'] }"
+ formControlName="size" [ngClass]="{ 'input-error': formErrors()['cache.storyboards.size'] }"
>
<span i18n>{getCacheSize('storyboards'), plural, =1 {cached storyboard} other {cached storyboards}}</span>
</div>
- <div *ngIf="formErrors.cache.storyboards.size" class="form-error" role="alert">{{ formErrors.cache.storyboards.size }}</div>
+ <div *ngIf="formErrors().cache.storyboards.size" class="form-error" role="alert">{{ formErrors().cache.storyboards.size }}</div>
</div>
</ng-container>
@@ -96,10 +96,10 @@
<textarea
id="customizationJavascript" formControlName="javascript" class="form-control" dir="ltr"
- [ngClass]="{ 'input-error': formErrors['instance.customizations.javascript'] }"
+ [ngClass]="{ 'input-error': formErrors()['instance.customizations.javascript'] }"
></textarea>
- <div *ngIf="formErrors.instance.customizations.javascript" class="form-error" role="alert">{{ formErrors.instance.customizations.javascript }}</div>
+ <div *ngIf="formErrors().instance.customizations.javascript" class="form-error" role="alert">{{ formErrors().instance.customizations.javascript }}</div>
</div>
<div class="form-group">
@@ -126,9 +126,9 @@
<textarea
id="customizationCSS" formControlName="css" class="form-control" dir="ltr"
- [ngClass]="{ 'input-error': formErrors['instance.customizations.css'] }"
+ [ngClass]="{ 'input-error': formErrors()['instance.customizations.css'] }"
></textarea>
- <div *ngIf="formErrors.instance.customizations.css" class="form-error" role="alert">{{ formErrors.instance.customizations.css }}</div>
+ <div *ngIf="formErrors().instance.customizations.css" class="form-error" role="alert">{{ formErrors().instance.customizations.css }}</div>
</div>
</ng-container>
</ng-container>
diff --git a/client/src/app/+admin/config/edit-custom-config/edit-advanced-configuration.component.ts b/client/src/app/+admin/config/edit-custom-config/edit-advanced-configuration.component.ts
index 1a4d2bd41d..5a577a3d85 100644
--- a/client/src/app/+admin/config/edit-custom-config/edit-advanced-configuration.component.ts
+++ b/client/src/app/+admin/config/edit-custom-config/edit-advanced-configuration.component.ts
@@ -1,4 +1,4 @@
-import { Component, Input } from '@angular/core'
+import { Component, input } from '@angular/core'
import { FormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms'
import { PeerTubeTemplateDirective } from '../../../shared/shared-main/common/peertube-template.directive'
import { HelpComponent } from '../../../shared/shared-main/buttons/help.component'
@@ -11,10 +11,10 @@ import { NgClass, NgIf } from '@angular/common'
imports: [ FormsModule, ReactiveFormsModule, NgClass, NgIf, HelpComponent, PeerTubeTemplateDirective ]
})
export class EditAdvancedConfigurationComponent {
- @Input() form: FormGroup
- @Input() formErrors: any
+ readonly form = input<FormGroup>(undefined)
+ readonly formErrors = input<any>(undefined)
getCacheSize (type: 'captions' | 'previews' | 'torrents' | 'storyboards') {
- return this.form.value['cache'][type]['size']
+ return this.form().value['cache'][type]['size']
}
}
diff --git a/client/src/app/+admin/config/edit-custom-config/edit-basic-configuration.component.html b/client/src/app/+admin/config/edit-custom-config/edit-basic-configuration.component.html
index a557be07e1..6ccb2e6e44 100644
--- a/client/src/app/+admin/config/edit-custom-config/edit-basic-configuration.component.html
+++ b/client/src/app/+admin/config/edit-custom-config/edit-basic-configuration.component.html
@@ -1,4 +1,4 @@
-<ng-container [formGroup]="form">
+<ng-container [formGroup]="form()">
<div class="pt-two-cols mt-5"> <!-- appearance grid -->
<div class="title-col">
<h2 i18n>APPEARANCE</h2>
@@ -30,7 +30,7 @@
[clearable]="false"
></my-select-custom-value>
- <div *ngIf="formErrors.instance.defaultClientRoute" class="form-error" role="alert">{{ formErrors.instance.defaultClientRoute }}</div>
+ <div *ngIf="formErrors().instance.defaultClientRoute" class="form-error" role="alert">{{ formErrors().instance.defaultClientRoute }}</div>
</div>
<div class="form-group" formGroupName="trending">
@@ -47,7 +47,7 @@
</select>
</div>
- <div *ngIf="formErrors.trending.videos.algorithms.default" class="form-error" role="alert">{{ formErrors.trending.videos.algorithms.default }}</div>
+ <div *ngIf="formErrors().trending.videos.algorithms.default" class="form-error" role="alert">{{ formErrors().trending.videos.algorithms.default }}</div>
</ng-container>
</ng-container>
</div>
@@ -122,7 +122,7 @@
</select>
</div>
- <div *ngIf="formErrors.broadcastMessage.level" class="form-error" role="alert">{{ formErrors.broadcastMessage.level }}</div>
+ <div *ngIf="formErrors().broadcastMessage.level" class="form-error" role="alert">{{ formErrors().broadcastMessage.level }}</div>
</div>
<div class="form-group">
@@ -130,10 +130,10 @@
<my-markdown-textarea
inputId="broadcastMessageMessage" formControlName="message"
- [formError]="formErrors['broadcastMessage.message']" markdownType="to-unsafe-html"
+ [formError]="formErrors()['broadcastMessage.message']" markdownType="to-unsafe-html"
></my-markdown-textarea>
- <div *ngIf="formErrors.broadcastMessage.message" class="form-error" role="alert">{{ formErrors.broadcastMessage.message }}</div>
+ <div *ngIf="formErrors().broadcastMessage.message" class="form-error" role="alert">{{ formErrors().broadcastMessage.message }}</div>
</div>
</ng-container>
@@ -185,12 +185,12 @@
<div class="number-with-unit">
<input
type="number" min="-1" id="signupLimit" class="form-control"
- formControlName="limit" [ngClass]="{ 'input-error': formErrors['signup.limit'] }"
+ formControlName="limit" [ngClass]="{ 'input-error': formErrors()['signup.limit'] }"
>
- <span i18n>{form.value['signup']['limit'], plural, =1 {user} other {users}}</span>
+ <span i18n>{form().value['signup']['limit'], plural, =1 {user} other {users}}</span>
</div>
- <div *ngIf="formErrors.signup.limit" class="form-error" role="alert">{{ formErrors.signup.limit }}</div>
+ <div *ngIf="formErrors().signup.limit" class="form-error" role="alert">{{ formErrors().signup.limit }}</div>
<small i18n *ngIf="hasUnlimitedSignup()" class="muted small">Signup won't be limited to a fixed number of users.</small>
</div>
@@ -201,12 +201,12 @@
<div class="number-with-unit">
<input
type="number" min="1" id="signupMinimumAge" class="form-control"
- formControlName="minimumAge" [ngClass]="{ 'input-error': formErrors['signup.minimumAge'] }"
+ formControlName="minimumAge" [ngClass]="{ 'input-error': formErrors()['signup.minimumAge'] }"
>
- <span i18n>{form.value['signup']['minimumAge'], plural, =1 {year old} other {years old}}</span>
+ <span i18n>{form().value['signup']['minimumAge'], plural, =1 {year old} other {years old}}</span>
</div>
- <div *ngIf="formErrors.signup.minimumAge" class="form-error" role="alert">{{ formErrors.signup.minimumAge }}</div>
+ <div *ngIf="formErrors().signup.minimumAge" class="form-error" role="alert">{{ formErrors().signup.minimumAge }}</div>
</div>
</ng-container>
</my-peertube-checkbox>
@@ -228,7 +228,7 @@
<my-user-real-quota-info class="mt-2 d-block small muted" [videoQuota]="getUserVideoQuota()"></my-user-real-quota-info>
- <div *ngIf="formErrors.user.videoQuota" class="form-error" role="alert">{{ formErrors.user.videoQuota }}</div>
+ <div *ngIf="formErrors().user.videoQuota" class="form-error" role="alert">{{ formErrors().user.videoQuota }}</div>
</div>
<div class="form-group">
@@ -243,7 +243,7 @@
[clearable]="false"
></my-select-custom-value>
- <div *ngIf="formErrors.user.videoQuotaDaily" class="form-error" role="alert">{{ formErrors.user.videoQuotaDaily }}</div>
+ <div *ngIf="formErrors().user.videoQuotaDaily" class="form-error" role="alert">{{ formErrors().user.videoQuotaDaily }}</div>
</div>
<div class="form-group">
<ng-container formGroupName="history">
@@ -281,7 +281,7 @@
<span i18n>jobs in parallel</span>
</div>
- <div *ngIf="formErrors.import.concurrency" class="form-error" role="alert">{{ formErrors.import.concurrency }}</div>
+ <div *ngIf="formErrors().import.concurrency" class="form-error" role="alert">{{ formErrors().import.concurrency }}</div>
</div>
<div class="form-group" formGroupName="http">
@@ -328,12 +328,12 @@
<div class="number-with-unit">
<input
type="number" min="1" id="videoChannelSynchronizationMaxPerUser" class="form-control"
- formControlName="maxPerUser" [ngClass]="{ 'input-error': formErrors['import']['videoChannelSynchronization']['maxPerUser'] }"
+ formControlName="maxPerUser" [ngClass]="{ 'input-error': formErrors()['import']['videoChannelSynchronization']['maxPerUser'] }"
>
- <span i18n>{form.value['import']['videoChannelSynchronization']['maxPerUser'], plural, =1 {sync} other {syncs}}</span>
+ <span i18n>{form().value['import']['videoChannelSynchronization']['maxPerUser'], plural, =1 {sync} other {syncs}}</span>
</div>
- <div *ngIf="formErrors.import.videoChannelSynchronization.maxPerUser" class="form-error" role="alert">{{ formErrors.import.videoChannelSynchronization.maxPerUser }}</div>
+ <div *ngIf="formErrors().import.videoChannelSynchronization.maxPerUser" class="form-error" role="alert">{{ formErrors().import.videoChannelSynchronization.maxPerUser }}</div>
</div>
</ng-container>
@@ -426,12 +426,12 @@
<div class="number-with-unit">
<input
type="number" min="1" id="videoChannelsMaxPerUser" class="form-control"
- formControlName="maxPerUser" [ngClass]="{ 'input-error': formErrors['videoChannels.maxPerUser'] }"
+ formControlName="maxPerUser" [ngClass]="{ 'input-error': formErrors()['videoChannels.maxPerUser'] }"
>
- <span i18n>{form.value['videoChannels']['maxPerUser'], plural, =1 {channel} other {channels}}</span>
+ <span i18n>{form().value['videoChannels']['maxPerUser'], plural, =1 {channel} other {channels}}</span>
</div>
- <div *ngIf="formErrors.videoChannels.maxPerUser" class="form-error" role="alert">{{ formErrors.videoChannels.maxPerUser }}</div>
+ <div *ngIf="formErrors().videoChannels.maxPerUser" class="form-error" role="alert">{{ formErrors().videoChannels.maxPerUser }}</div>
</div>
</div>
</div>
@@ -490,10 +490,10 @@
<input
type="text" id="searchIndexUrl" class="form-control"
- formControlName="url" [ngClass]="{ 'input-error': formErrors['search.searchIndex.url'] }"
+ formControlName="url" [ngClass]="{ 'input-error': formErrors()['search.searchIndex.url'] }"
>
- <div *ngIf="formErrors.search.searchIndex.url" class="form-error" role="alert">{{ formErrors.search.searchIndex.url }}</div>
+ <div *ngIf="formErrors().search.searchIndex.url" class="form-error" role="alert">{{ formErrors().search.searchIndex.url }}</div>
</div>
<div class="mt-3">
@@ -577,7 +577,7 @@
[clearable]="false"
></my-select-custom-value>
- <div *ngIf="formErrors.export.users.maxUserVideoQuota" class="form-error" role="alert">{{ formErrors.export.users.maxUserVideoQuota }}</div>
+ <div *ngIf="formErrors().export.users.maxUserVideoQuota" class="form-error" role="alert">{{ formErrors().export.users.maxUserVideoQuota }}</div>
</div>
<div class="form-group" [ngClass]="getDisabledExportUsersClass()">
@@ -587,7 +587,7 @@
<div i18n class="mt-1 small muted">The archive file is deleted after this period.</div>
- <div *ngIf="formErrors.export.users.exportExpiration" class="form-error" role="alert">{{ formErrors.export.users.exportExpiration }}</div>
+ <div *ngIf="formErrors().export.users.exportExpiration" class="form-error" role="alert">{{ formErrors().export.users.exportExpiration }}</div>
</div>
</ng-container>
@@ -663,9 +663,9 @@
<label i18n for="followingsInstanceAutoFollowIndexUrl">Index URL</label>
<input
type="text" id="followingsInstanceAutoFollowIndexUrl" class="form-control"
- formControlName="indexUrl" [ngClass]="{ 'input-error': formErrors['followings.instance.autoFollowIndex.indexUrl'] }"
+ formControlName="indexUrl" [ngClass]="{ 'input-error': formErrors()['followings.instance.autoFollowIndex.indexUrl'] }"
>
- <div *ngIf="formErrors.followings.instance.autoFollowIndex.indexUrl" class="form-error" role="alert">{{ formErrors.followings.instance.autoFollowIndex.indexUrl }}</div>
+ <div *ngIf="formErrors().followings.instance.autoFollowIndex.indexUrl" class="form-error" role="alert">{{ formErrors().followings.instance.autoFollowIndex.indexUrl }}</div>
</div>
</ng-container>
</my-peertube-checkbox>
@@ -690,10 +690,10 @@
<input
type="text" id="adminEmail" class="form-control"
- formControlName="email" [ngClass]="{ 'input-error': formErrors['admin.email'] }"
+ formControlName="email" [ngClass]="{ 'input-error': formErrors()['admin.email'] }"
>
- <div *ngIf="formErrors.admin.email" class="form-error" role="alert">{{ formErrors.admin.email }}</div>
+ <div *ngIf="formErrors().admin.email" class="form-error" role="alert">{{ formErrors().admin.email }}</div>
</div>
<div class="form-group" formGroupName="contactForm">
@@ -731,10 +731,10 @@
<input
type="text" id="servicesTwitterUsername" class="form-control"
- formControlName="username" [ngClass]="{ 'input-error': formErrors['services.twitter.username'] }"
+ formControlName="username" [ngClass]="{ 'input-error': formErrors()['services.twitter.username'] }"
>
- <div *ngIf="formErrors.services.twitter.username" class="form-error" role="alert">{{ formErrors.services.twitter.username }}</div>
+ <div *ngIf="formErrors().services.twitter.username" class="form-error" role="alert">{{ formErrors().services.twitter.username }}</div>
</div>
</ng-container>
diff --git a/client/src/app/+admin/config/edit-custom-config/edit-basic-configuration.component.ts b/client/src/app/+admin/config/edit-custom-config/edit-basic-configuration.component.ts
index 939a224fc7..50e01d705f 100644
--- a/client/src/app/+admin/config/edit-custom-config/edit-basic-configuration.component.ts
+++ b/client/src/app/+admin/config/edit-custom-config/edit-basic-configuration.component.ts
@@ -1,5 +1,5 @@
-import { NgClass, NgFor, NgIf } from '@angular/common'
-import { Component, Input, OnChanges, OnInit, SimpleChanges } from '@angular/core'
+import { NgClass, NgIf } from '@angular/common'
+import { Component, OnChanges, OnInit, SimpleChanges, inject, input } from '@angular/core'
import { FormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms'
import { RouterLink } from '@angular/router'
import { ThemeService } from '@app/core'
@@ -23,7 +23,6 @@ import { ConfigService } from '../shared/config.service'
FormsModule,
ReactiveFormsModule,
RouterLink,
- NgFor,
SelectCustomValueComponent,
NgIf,
PeertubeCheckboxComponent,
@@ -36,10 +35,13 @@ import { ConfigService } from '../shared/config.service'
]
})
export class EditBasicConfigurationComponent implements OnInit, OnChanges {
- @Input() form: FormGroup
- @Input() formErrors: any
+ private configService = inject(ConfigService)
+ private themeService = inject(ThemeService)
- @Input() serverConfig: HTMLServerConfig
+ readonly form = input<FormGroup>(undefined)
+ readonly formErrors = input<any>(undefined)
+
+ readonly serverConfig = input<HTMLServerConfig>(undefined)
signupAlertMessage: string
defaultLandingPageOptions: SelectOptionsItem[] = []
@@ -48,11 +50,6 @@ export class EditBasicConfigurationComponent implements OnInit, OnChanges {
exportExpirationOptions: SelectOptionsItem[] = []
exportMaxUserVideoQuotaOptions: SelectOptionsItem[] = []
- constructor (
- private configService: ConfigService,
- private themeService: ThemeService
- ) {}
-
ngOnInit () {
this.buildLandingPageOptions()
this.checkSignupField()
@@ -81,7 +78,7 @@ export class EditBasicConfigurationComponent implements OnInit, OnChanges {
}
countExternalAuth () {
- return this.serverConfig.plugin.registeredExternalAuths.length
+ return this.serverConfig().plugin.registeredExternalAuths.length
}
getVideoQuotaOptions () {
@@ -93,18 +90,18 @@ export class EditBasicConfigurationComponent implements OnInit, OnChanges {
}
doesTrendingVideosAlgorithmsEnabledInclude (algorithm: string) {
- const enabled = this.form.value['trending']['videos']['algorithms']['enabled']
+ const enabled = this.form().value['trending']['videos']['algorithms']['enabled']
if (!Array.isArray(enabled)) return false
return !!enabled.find((e: string) => e === algorithm)
}
getUserVideoQuota () {
- return this.form.value['user']['videoQuota']
+ return this.form().value['user']['videoQuota']
}
isExportUsersEnabled () {
- return this.form.value['export']['users']['enabled'] === true
+ return this.form().value['export']['users']['enabled'] === true
}
getDisabledExportUsersClass () {
@@ -112,7 +109,7 @@ export class EditBasicConfigurationComponent implements OnInit, OnChanges {
}
isSignupEnabled () {
- return this.form.value['signup']['enabled'] === true
+ return this.form().value['signup']['enabled'] === true
}
getDisabledSignupClass () {
@@ -120,19 +117,19 @@ export class EditBasicConfigurationComponent implements OnInit, OnChanges {
}
isImportVideosHttpEnabled (): boolean {
- return this.form.value['import']['videos']['http']['enabled'] === true
+ return this.form().value['import']['videos']['http']['enabled'] === true
}
importSynchronizationChecked () {
- return this.isImportVideosHttpEnabled() && this.form.value['import']['videoChannelSynchronization']['enabled']
+ return this.isImportVideosHttpEnabled() && this.form().value['import']['videoChannelSynchronization']['enabled']
}
hasUnlimitedSignup () {
- return this.form.value['signup']['limit'] === -1
+ return this.form().value['signup']['limit'] === -1
}
isSearchIndexEnabled () {
- return this.form.value['search']['searchIndex']['enabled'] === true
+ return this.form().value['search']['searchIndex']['enabled'] === true
}
getDisabledSearchIndexClass () {
@@ -142,7 +139,7 @@ export class EditBasicConfigurationComponent implements OnInit, OnChanges {
// ---------------------------------------------------------------------------
isTranscriptionEnabled () {
- return this.form.value['videoTranscription']['enabled'] === true
+ return this.form().value['videoTranscription']['enabled'] === true
}
getTranscriptionRunnerDisabledClass () {
@@ -152,13 +149,13 @@ export class EditBasicConfigurationComponent implements OnInit, OnChanges {
// ---------------------------------------------------------------------------
isAutoFollowIndexEnabled () {
- return this.form.value['followings']['instance']['autoFollowIndex']['enabled'] === true
+ return this.form().value['followings']['instance']['autoFollowIndex']['enabled'] === true
}
buildLandingPageOptions () {
let links: { label: string, path: string }[] = []
- if (this.serverConfig.homepage.enabled) {
+ if (this.serverConfig().homepage.enabled) {
links.push({ label: $localize`Home`, path: '/home' })
}
@@ -176,11 +173,11 @@ export class EditBasicConfigurationComponent implements OnInit, OnChanges {
}
private checkImportSyncField () {
- const importSyncControl = this.form.get('import.videoChannelSynchronization.enabled')
- const importVideosHttpControl = this.form.get('import.videos.http.enabled')
+ const importSyncControl = this.form().get('import.videoChannelSynchronization.enabled')
+ const importVideosHttpControl = this.form().get('import.videos.http.enabled')
importVideosHttpControl.valueChanges
- .subscribe((httpImportEnabled) => {
+ .subscribe(httpImportEnabled => {
importSyncControl.setValue(httpImportEnabled && importSyncControl.value)
if (httpImportEnabled) {
importSyncControl.enable()
@@ -191,16 +188,17 @@ export class EditBasicConfigurationComponent implements OnInit, OnChanges {
}
private checkSignupField () {
- const signupControl = this.form.get('signup.enabled')
+ const signupControl = this.form().get('signup.enabled')
signupControl.valueChanges
.pipe(pairwise())
.subscribe(([ oldValue, newValue ]) => {
if (oldValue === false && newValue === true) {
/* eslint-disable max-len */
- this.signupAlertMessage = $localize`You enabled signup: we automatically enabled the "Block new videos automatically" checkbox of the "Videos" section just below.`
+ this.signupAlertMessage =
+ $localize`You enabled signup: we automatically enabled the "Block new videos automatically" checkbox of the "Videos" section just below.`
- this.form.patchValue({
+ this.form().patchValue({
autoBlacklist: {
videos: {
ofUsers: {
diff --git a/client/src/app/+admin/config/edit-custom-config/edit-custom-config.component.ts b/client/src/app/+admin/config/edit-custom-config/edit-custom-config.component.ts
index 71d2e19301..b28d2e7e08 100644
--- a/client/src/app/+admin/config/edit-custom-config/edit-custom-config.component.ts
+++ b/client/src/app/+admin/config/edit-custom-config/edit-custom-config.component.ts
@@ -1,5 +1,5 @@
import { NgFor, NgIf } from '@angular/common'
-import { Component, OnInit } from '@angular/core'
+import { Component, OnInit, inject } from '@angular/core'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { ActivatedRoute, Router } from '@angular/router'
import { ConfigService } from '@app/+admin/config/shared/config.service'
@@ -73,6 +73,15 @@ type ComponentCustomConfig = CustomConfig & {
]
})
export class EditCustomConfigComponent extends FormReactive implements OnInit {
+ protected formReactiveService = inject(FormReactiveService)
+ private router = inject(Router)
+ private route = inject(ActivatedRoute)
+ private notifier = inject(Notifier)
+ private configService = inject(ConfigService)
+ private customPage = inject(CustomPageService)
+ private serverService = inject(ServerService)
+ private editConfigurationService = inject(EditConfigurationService)
+
activeNav: string
customConfig: ComponentCustomConfig
@@ -83,23 +92,10 @@ export class EditCustomConfigComponent extends FormReactive implements OnInit {
languageItems: SelectOptionsItem[] = []
categoryItems: SelectOptionsItem[] = []
- constructor (
- protected formReactiveService: FormReactiveService,
- private router: Router,
- private route: ActivatedRoute,
- private notifier: Notifier,
- private configService: ConfigService,
- private customPage: CustomPageService,
- private serverService: ServerService,
- private editConfigurationService: EditConfigurationService
- ) {
- super()
- }
-
ngOnInit () {
this.serverConfig = this.serverService.getHTMLConfig()
- const formGroupData: { [key in keyof ComponentCustomConfig ]: any } = {
+ const formGroupData: { [key in keyof ComponentCustomConfig]: any } = {
instance: {
name: INSTANCE_NAME_VALIDATOR,
shortDescription: INSTANCE_SHORT_DESCRIPTION_VALIDATOR,
@@ -193,7 +189,6 @@ export class EditCustomConfigComponent extends FormReactive implements OnInit {
videoChannelSynchronization: {
enabled: null,
maxPerUser: MAX_SYNC_PER_USER
-
},
users: {
enabled: null
diff --git a/client/src/app/+admin/config/edit-custom-config/edit-homepage.component.html b/client/src/app/+admin/config/edit-custom-config/edit-homepage.component.html
index 7a8fcb3fef..7f694bfef9 100644
--- a/client/src/app/+admin/config/edit-custom-config/edit-homepage.component.html
+++ b/client/src/app/+admin/config/edit-custom-config/edit-homepage.component.html
@@ -1,4 +1,4 @@
-<ng-container [formGroup]="form">
+<ng-container [formGroup]="form()">
<ng-container formGroupName="instanceCustomHomepage">
@@ -18,11 +18,11 @@
<my-markdown-textarea
inputId="instanceCustomHomepageContent" formControlName="content"
[customMarkdownRenderer]="getCustomMarkdownRenderer()" [debounceTime]="500"
- [formError]="formErrors['instanceCustomHomepage.content']"
+ [formError]="formErrors()['instanceCustomHomepage.content']"
dir="ltr"
></my-markdown-textarea>
- <div *ngIf="formErrors.instanceCustomHomepage.content" class="form-error" role="alert">{{ formErrors.instanceCustomHomepage.content }}</div>
+ <div *ngIf="formErrors().instanceCustomHomepage.content" class="form-error" role="alert">{{ formErrors().instanceCustomHomepage.content }}</div>
</div>
</div>
</div>
diff --git a/client/src/app/+admin/config/edit-custom-config/edit-homepage.component.ts b/client/src/app/+admin/config/edit-custom-config/edit-homepage.component.ts
index fec8ee291e..82ec7ff6f0 100644
--- a/client/src/app/+admin/config/edit-custom-config/edit-homepage.component.ts
+++ b/client/src/app/+admin/config/edit-custom-config/edit-homepage.component.ts
@@ -1,4 +1,4 @@
-import { Component, Input } from '@angular/core'
+import { Component, inject, input } from '@angular/core'
import { FormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms'
import { NgIf } from '@angular/common'
import { MarkdownTextareaComponent } from '../../../shared/shared-forms/markdown-textarea.component'
@@ -12,14 +12,12 @@ import { CustomMarkupService } from '@app/shared/shared-custom-markup/custom-mar
imports: [ FormsModule, ReactiveFormsModule, CustomMarkupHelpComponent, MarkdownTextareaComponent, NgIf ]
})
export class EditHomepageComponent {
- @Input() form: FormGroup
- @Input() formErrors: any
+ private customMarkup = inject(CustomMarkupService)
- customMarkdownRenderer: (text: string) => Promise<HTMLElement>
-
- constructor (private customMarkup: CustomMarkupService) {
+ readonly form = input<FormGroup>(undefined)
+ readonly formErrors = input<any>(undefined)
- }
+ customMarkdownRenderer: (text: string) => Promise<HTMLElement>
getCustomMarkdownRenderer () {
return this.customMarkup.getCustomMarkdownRenderer()
diff --git a/client/src/app/+admin/config/edit-custom-config/edit-instance-information.component.html b/client/src/app/+admin/config/edit-custom-config/edit-instance-information.component.html
index 470bee56a8..cc4c0f2f23 100644
--- a/client/src/app/+admin/config/edit-custom-config/edit-instance-information.component.html
+++ b/client/src/app/+admin/config/edit-custom-config/edit-instance-information.component.html
@@ -1,4 +1,4 @@
-<ng-container [formGroup]="form">
+<ng-container [formGroup]="form()">
<ng-container formGroupName="instance">
@@ -41,10 +41,10 @@
<input
type="text" id="instanceName" class="form-control"
- formControlName="name" [ngClass]="{ 'input-error': formErrors.instance.name }"
+ formControlName="name" [ngClass]="{ 'input-error': formErrors().instance.name }"
>
- <div *ngIf="formErrors.instance.name" class="form-error" role="alert">{{ formErrors.instance.name }}</div>
+ <div *ngIf="formErrors().instance.name" class="form-error" role="alert">{{ formErrors().instance.name }}</div>
</div>
<div class="form-group">
@@ -52,10 +52,10 @@
<textarea
id="instanceShortDescription" formControlName="shortDescription" class="form-control small"
- [ngClass]="{ 'input-error': formErrors['instance.shortDescription'] }"
+ [ngClass]="{ 'input-error': formErrors()['instance.shortDescription'] }"
></textarea>
- <div *ngIf="formErrors.instance.shortDescription" class="form-error" role="alert">{{ formErrors.instance.shortDescription }}</div>
+ <div *ngIf="formErrors().instance.shortDescription" class="form-error" role="alert">{{ formErrors().instance.shortDescription }}</div>
</div>
<div class="form-group">
@@ -67,7 +67,7 @@
<my-markdown-textarea
inputId="instanceDescription" formControlName="description"
[customMarkdownRenderer]="getCustomMarkdownRenderer()" [debounceTime]="500"
- [formError]="formErrors['instance.description']"
+ [formError]="formErrors()['instance.description']"
></my-markdown-textarea>
</div>
@@ -77,7 +77,7 @@
<div>
<my-select-checkbox
inputId="instanceCategories"
- formControlName="categories" [availableItems]="categoryItems"
+ formControlName="categories" [availableItems]="categoryItems()"
[selectableGroup]="false"
i18n-placeholder placeholder="Add a new category"
>
@@ -91,7 +91,7 @@
<div>
<my-select-checkbox
inputId="instanceLanguages"
- formControlName="languages" [availableItems]="languageItems"
+ formControlName="languages" [availableItems]="languageItems()"
[selectableGroup]="false"
i18n-placeholder placeholder="Add a new language"
>
@@ -105,10 +105,10 @@
<input
type="text" id="instanceServerCountry" class="form-control"
- formControlName="serverCountry" [ngClass]="{ 'input-error': formErrors.instance.serverCountry }"
+ formControlName="serverCountry" [ngClass]="{ 'input-error': formErrors().instance.serverCountry }"
>
- <div *ngIf="formErrors.instance.serverCountry" class="form-error" role="alert">{{ formErrors.instance.serverCountry }}</div>
+ <div *ngIf="formErrors().instance.serverCountry" class="form-error" role="alert">{{ formErrors().instance.serverCountry }}</div>
</div>
</div>
@@ -130,7 +130,7 @@
<my-markdown-textarea
inputId="instanceSupportText" formControlName="text" markdownType="enhanced"
- [formError]="formErrors['instance.support.text']"
+ [formError]="formErrors()['instance.support.text']"
></my-markdown-textarea>
</div>
@@ -141,10 +141,10 @@
<input
type="text" id="instanceSocialExternalLink" class="form-control"
- formControlName="externalLink" [ngClass]="{ 'input-error': formErrors.instance.social.externalLink }"
+ formControlName="externalLink" [ngClass]="{ 'input-error': formErrors().instance.social.externalLink }"
>
- <div *ngIf="formErrors.instance.social.externalLink" class="form-error" role="alert">{{ formErrors.instance.social.externalLink }}</div>
+ <div *ngIf="formErrors().instance.social.externalLink" class="form-error" role="alert">{{ formErrors().instance.social.externalLink }}</div>
</div>
<div class="form-group">
@@ -152,10 +152,10 @@
<input
type="text" id="instanceSocialMastodonLink" class="form-control"
- formControlName="mastodonLink" [ngClass]="{ 'input-error': formErrors.instance.social.mastodonLink }"
+ formControlName="mastodonLink" [ngClass]="{ 'input-error': formErrors().instance.social.mastodonLink }"
>
- <div *ngIf="formErrors.instance.social.mastodonLink" class="form-error" role="alert">{{ formErrors.instance.social.mastodonLink }}</div>
+ <div *ngIf="formErrors().instance.social.mastodonLink" class="form-error" role="alert">{{ formErrors().instance.social.mastodonLink }}</div>
</div>
<div class="form-group">
@@ -163,10 +163,10 @@
<input
type="text" id="instanceSocialBlueskyLink" class="form-control"
- formControlName="blueskyLink" [ngClass]="{ 'input-error': formErrors.instance.social.blueskyLink }"
+ formControlName="blueskyLink" [ngClass]="{ 'input-error': formErrors().instance.social.blueskyLink }"
>
- <div *ngIf="formErrors.instance.social.blueskyLink" class="form-error" role="alert">{{ formErrors.instance.social.blueskyLink }}</div>
+ <div *ngIf="formErrors().instance.social.blueskyLink" class="form-error" role="alert">{{ formErrors().instance.social.blueskyLink }}</div>
</div>
</ng-container>
@@ -217,7 +217,7 @@
</select>
</div>
- <div *ngIf="formErrors.instance.defaultNSFWPolicy" class="form-error" role="alert">{{ formErrors.instance.defaultNSFWPolicy }}</div>
+ <div *ngIf="formErrors().instance.defaultNSFWPolicy" class="form-error" role="alert">{{ formErrors().instance.defaultNSFWPolicy }}</div>
</div>
<div class="form-group">
@@ -225,7 +225,7 @@
<my-markdown-textarea
inputId="instanceTerms" formControlName="terms" markdownType="enhanced"
- [formError]="formErrors['instance.terms']"
+ [formError]="formErrors()['instance.terms']"
></my-markdown-textarea>
</div>
@@ -234,7 +234,7 @@
<my-markdown-textarea
inputId="instanceCodeOfConduct" formControlName="codeOfConduct" markdownType="enhanced"
- [formError]="formErrors['instance.codeOfConduct']"
+ [formError]="formErrors()['instance.codeOfConduct']"
></my-markdown-textarea>
</div>
@@ -244,7 +244,7 @@
<my-markdown-textarea
inputId="instanceModerationInformation" formControlName="moderationInformation" markdownType="enhanced"
- [formError]="formErrors['instance.moderationInformation']"
+ [formError]="formErrors()['instance.moderationInformation']"
></my-markdown-textarea>
</div>
@@ -264,7 +264,7 @@
<my-markdown-textarea
inputId="instanceAdministrator" formControlName="administrator" markdownType="enhanced"
- [formError]="formErrors['instance.administrator']"
+ [formError]="formErrors()['instance.administrator']"
></my-markdown-textarea>
</div>
@@ -274,7 +274,7 @@
<my-markdown-textarea
inputId="instanceCreationReason" formControlName="creationReason" markdownType="enhanced"
- [formError]="formErrors['instance.creationReason']"
+ [formError]="formErrors()['instance.creationReason']"
></my-markdown-textarea>
</div>
@@ -284,7 +284,7 @@
<my-markdown-textarea
inputId="instanceMaintenanceLifetime" formControlName="maintenanceLifetime" markdownType="enhanced"
- [formError]="formErrors['instance.maintenanceLifetime']"
+ [formError]="formErrors()['instance.maintenanceLifetime']"
></my-markdown-textarea>
</div>
@@ -294,7 +294,7 @@
<my-markdown-textarea
inputId="instanceBusinessModel" formControlName="businessModel" markdownType="enhanced"
- [formError]="formErrors['instance.businessModel']"
+ [formError]="formErrors()['instance.businessModel']"
></my-markdown-textarea>
</div>
@@ -314,7 +314,7 @@
<my-markdown-textarea
inputId="instanceHardwareInformation" formControlName="hardwareInformation" markdownType="enhanced"
- [formError]="formErrors['instance.hardwareInformation']"
+ [formError]="formErrors()['instance.hardwareInformation']"
></my-markdown-textarea>
</div>
diff --git a/client/src/app/+admin/config/edit-custom-config/edit-instance-information.component.ts b/client/src/app/+admin/config/edit-custom-config/edit-instance-information.component.ts
index 3662592820..df574077e5 100644
--- a/client/src/app/+admin/config/edit-custom-config/edit-instance-information.component.ts
+++ b/client/src/app/+admin/config/edit-custom-config/edit-instance-information.component.ts
@@ -1,6 +1,6 @@
import { NgClass, NgIf } from '@angular/common'
import { HttpErrorResponse } from '@angular/common/http'
-import { Component, Input, OnInit } from '@angular/core'
+import { Component, OnInit, inject, input } from '@angular/core'
import { FormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms'
import { RouterLink } from '@angular/router'
import { Notifier, ServerService } from '@app/core'
@@ -40,26 +40,22 @@ import { HelpComponent } from '../../../shared/shared-main/buttons/help.componen
]
})
export class EditInstanceInformationComponent implements OnInit {
- @Input() form: FormGroup
- @Input() formErrors: any
+ private customMarkup = inject(CustomMarkupService)
+ private notifier = inject(Notifier)
+ private instanceService = inject(InstanceService)
+ private server = inject(ServerService)
- @Input() languageItems: SelectOptionsItem[] = []
- @Input() categoryItems: SelectOptionsItem[] = []
+ readonly form = input<FormGroup>(undefined)
+ readonly formErrors = input<any>(undefined)
+
+ readonly languageItems = input<SelectOptionsItem[]>([])
+ readonly categoryItems = input<SelectOptionsItem[]>([])
instanceBannerUrl: string
instanceAvatars: ActorImage[] = []
private serverConfig: HTMLServerConfig
- constructor (
- private customMarkup: CustomMarkupService,
- private notifier: Notifier,
- private instanceService: InstanceService,
- private server: ServerService
- ) {
-
- }
-
get instanceName () {
return this.server.getHTMLConfig().instance.name
}
@@ -139,5 +135,4 @@ export class EditInstanceInformationComponent implements OnInit {
this.updateActorImages()
})
}
-
}
diff --git a/client/src/app/+admin/config/edit-custom-config/edit-live-configuration.component.html b/client/src/app/+admin/config/edit-custom-config/edit-live-configuration.component.html
index a60372dd1a..8e5c1a1e10 100644
--- a/client/src/app/+admin/config/edit-custom-config/edit-live-configuration.component.html
+++ b/client/src/app/+admin/config/edit-custom-config/edit-live-configuration.component.html
@@ -1,4 +1,4 @@
-<ng-container [formGroup]="form">
+<ng-container [formGroup]="form()">
<div class="pt-two-cols mt-5">
<div class="title-col">
@@ -52,10 +52,10 @@
<div class="number-with-unit">
<input type="number" id="liveMaxInstanceLives" formControlName="maxInstanceLives" />
- <span i18n>{form.value['live']['maxInstanceLives'], plural, =1 {live} other {lives}}</span>
+ <span i18n>{form().value['live']['maxInstanceLives'], plural, =1 {live} other {lives}}</span>
</div>
- <div *ngIf="formErrors.live.maxInstanceLives" class="form-error" role="alert">{{ formErrors.live.maxInstanceLives }}</div>
+ <div *ngIf="formErrors().live.maxInstanceLives" class="form-error" role="alert">{{ formErrors().live.maxInstanceLives }}</div>
</div>
<div class="form-group" [ngClass]="getDisabledLiveClass()">
@@ -64,10 +64,10 @@
<div class="number-with-unit">
<input type="number" id="liveMaxUserLives" formControlName="maxUserLives" />
- <span i18n>{form.value['live']['maxUserLives'], plural, =1 {live} other {lives}}</span>
+ <span i18n>{form().value['live']['maxUserLives'], plural, =1 {live} other {lives}}</span>
</div>
- <div *ngIf="formErrors.live.maxUserLives" class="form-error" role="alert">{{ formErrors.live.maxUserLives }}</div>
+ <div *ngIf="formErrors().live.maxUserLives" class="form-error" role="alert">{{ formErrors().live.maxUserLives }}</div>
</div>
<div class="form-group" [ngClass]="getDisabledLiveClass()">
@@ -75,7 +75,7 @@
<my-select-options inputId="liveMaxDuration" [items]="liveMaxDurationOptions" formControlName="maxDuration"></my-select-options>
- <div *ngIf="formErrors.live.maxDuration" class="form-error" role="alert">{{ formErrors.live.maxDuration }}</div>
+ <div *ngIf="formErrors().live.maxDuration" class="form-error" role="alert">{{ formErrors().live.maxDuration }}</div>
</div>
</ng-container>
@@ -123,7 +123,7 @@
<span>FPS</span>
</div>
- <div *ngIf="formErrors.live.transcoding.fps.max" class="form-error" role="alert">{{ formErrors.live.transcoding.fps.max }}</div>
+ <div *ngIf="formErrors().live.transcoding.fps.max" class="form-error" role="alert">{{ formErrors().live.transcoding.fps.max }}</div>
</div>
<div class="ms-2 mt-3">
@@ -193,7 +193,7 @@
formControlName="threads"
[clearable]="false"
></my-select-custom-value>
- <div *ngIf="formErrors.live.transcoding.threads" class="form-error" role="alert">{{ formErrors.live.transcoding.threads }}</div>
+ <div *ngIf="formErrors().live.transcoding.threads" class="form-error" role="alert">{{ formErrors().live.transcoding.threads }}</div>
</div>
<div class="form-group mt-4" [ngClass]="getDisabledLiveLocalTranscodingClass()">
@@ -202,7 +202,7 @@
<my-select-options inputId="liveTranscodingProfile" formControlName="profile" [items]="transcodingProfiles"></my-select-options>
- <div *ngIf="formErrors.live.transcoding.profile" class="form-error" role="alert">{{ formErrors.live.transcoding.profile }}</div>
+ <div *ngIf="formErrors().live.transcoding.profile" class="form-error" role="alert">{{ formErrors().live.transcoding.profile }}</div>
</div>
</ng-container>
diff --git a/client/src/app/+admin/config/edit-custom-config/edit-live-configuration.component.ts b/client/src/app/+admin/config/edit-custom-config/edit-live-configuration.component.ts
index 93be7a300e..fb5820f969 100644
--- a/client/src/app/+admin/config/edit-custom-config/edit-live-configuration.component.ts
+++ b/client/src/app/+admin/config/edit-custom-config/edit-live-configuration.component.ts
@@ -1,5 +1,5 @@
import { SelectOptionsItem } from 'src/types/select-options-item.model'
-import { Component, Input, OnChanges, OnInit, SimpleChanges } from '@angular/core'
+import { Component, OnChanges, OnInit, SimpleChanges, inject, input } from '@angular/core'
import { FormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms'
import { HTMLServerConfig } from '@peertube/peertube-models'
import { ConfigService } from '../shared/config.service'
@@ -29,9 +29,12 @@ import { PeertubeCheckboxComponent } from '../../../shared/shared-forms/peertube
]
})
export class EditLiveConfigurationComponent implements OnInit, OnChanges {
- @Input() form: FormGroup
- @Input() formErrors: any
- @Input() serverConfig: HTMLServerConfig
+ private configService = inject(ConfigService)
+ private editConfigurationService = inject(EditConfigurationService)
+
+ readonly form = input<FormGroup>(undefined)
+ readonly formErrors = input<any>(undefined)
+ readonly serverConfig = input<HTMLServerConfig>(undefined)
transcodingThreadOptions: SelectOptionsItem[] = []
transcodingProfiles: SelectOptionsItem[] = []
@@ -39,11 +42,6 @@ export class EditLiveConfigurationComponent implements OnInit, OnChanges {
liveMaxDurationOptions: SelectOptionsItem[] = []
liveResolutions: ResolutionOption[] = []
- constructor (
- private configService: ConfigService,
- private editConfigurationService: EditConfigurationService
- ) { }
-
ngOnInit () {
this.transcodingThreadOptions = this.configService.transcodingThreadOptions
@@ -65,7 +63,7 @@ export class EditLiveConfigurationComponent implements OnInit, OnChanges {
}
buildAvailableTranscodingProfile () {
- const profiles = this.serverConfig.live.transcoding.availableProfiles
+ const profiles = this.serverConfig().live.transcoding.availableProfiles
return profiles.map(p => {
if (p === 'default') {
@@ -81,15 +79,15 @@ export class EditLiveConfigurationComponent implements OnInit, OnChanges {
}
getLiveRTMPPort () {
- return this.serverConfig.live.rtmp.port
+ return this.serverConfig().live.rtmp.port
}
isLiveEnabled () {
- return this.editConfigurationService.isLiveEnabled(this.form)
+ return this.editConfigurationService.isLiveEnabled(this.form())
}
isRemoteRunnerLiveEnabled () {
- return this.editConfigurationService.isRemoteRunnerLiveEnabled(this.form)
+ return this.editConfigurationService.isRemoteRunnerLiveEnabled(this.form())
}
getDisabledLiveClass () {
@@ -105,10 +103,10 @@ export class EditLiveConfigurationComponent implements OnInit, OnChanges {
}
isLiveTranscodingEnabled () {
- return this.editConfigurationService.isLiveTranscodingEnabled(this.form)
+ return this.editConfigurationService.isLiveTranscodingEnabled(this.form())
}
getTotalTranscodingThreads () {
- return this.editConfigurationService.getTotalTranscodingThreads(this.form)
+ return this.editConfigurationService.getTotalTranscodingThreads(this.form())
}
}
diff --git a/client/src/app/+admin/config/edit-custom-config/edit-vod-transcoding.component.html b/client/src/app/+admin/config/edit-custom-config/edit-vod-transcoding.component.html
index 3c804f0cca..4dd5472be7 100644
--- a/client/src/app/+admin/config/edit-custom-config/edit-vod-transcoding.component.html
+++ b/client/src/app/+admin/config/edit-custom-config/edit-vod-transcoding.component.html
@@ -1,4 +1,4 @@
-<ng-container [formGroup]="form">
+<ng-container [formGroup]="form()">
<div class="pt-two-cols mt-4">
<div class="title-col"></div>
@@ -151,7 +151,7 @@
<span>FPS</span>
</div>
- <div *ngIf="formErrors.transcoding.fps.max" class="form-error" role="alert">{{ formErrors.transcoding.fps.max }}</div>
+ <div *ngIf="formErrors().transcoding.fps.max" class="form-error" role="alert">{{ formErrors().transcoding.fps.max }}</div>
</div>
<div class="form-group" [ngClass]="getTranscodingDisabledClass()">
@@ -220,7 +220,7 @@
[clearable]="false"
></my-select-custom-value>
- <div *ngIf="formErrors.transcoding.threads" class="form-error" role="alert">{{ formErrors.transcoding.threads }}</div>
+ <div *ngIf="formErrors().transcoding.threads" class="form-error" role="alert">{{ formErrors().transcoding.threads }}</div>
</div>
<div class="form-group" [ngClass]="getLocalTranscodingDisabledClass()">
@@ -232,7 +232,7 @@
<span i18n>jobs in parallel</span>
</div>
- <div *ngIf="formErrors.transcoding.concurrency" class="form-error" role="alert">{{ formErrors.transcoding.concurrency }}</div>
+ <div *ngIf="formErrors().transcoding.concurrency" class="form-error" role="alert">{{ formErrors().transcoding.concurrency }}</div>
</div>
<div class="form-group" [ngClass]="getLocalTranscodingDisabledClass()">
@@ -241,7 +241,7 @@
<my-select-options inputId="transcodingProfile" formControlName="profile" [items]="transcodingProfiles"></my-select-options>
- <div *ngIf="formErrors.transcoding.profile" class="form-error" role="alert">{{ formErrors.transcoding.profile }}</div>
+ <div *ngIf="formErrors().transcoding.profile" class="form-error" role="alert">{{ formErrors().transcoding.profile }}</div>
</div>
</ng-container>
diff --git a/client/src/app/+admin/config/edit-custom-config/edit-vod-transcoding.component.ts b/client/src/app/+admin/config/edit-custom-config/edit-vod-transcoding.component.ts
index b75094ffe9..7c5640965b 100644
--- a/client/src/app/+admin/config/edit-custom-config/edit-vod-transcoding.component.ts
+++ b/client/src/app/+admin/config/edit-custom-config/edit-vod-transcoding.component.ts
@@ -1,5 +1,5 @@
import { NgClass, NgFor, NgIf } from '@angular/common'
-import { Component, Input, OnChanges, OnInit, SimpleChanges } from '@angular/core'
+import { Component, OnChanges, OnInit, SimpleChanges, inject, input } from '@angular/core'
import { FormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms'
import { RouterLink } from '@angular/router'
import { Notifier } from '@app/core'
@@ -30,9 +30,13 @@ import { EditConfigurationService, ResolutionOption } from './edit-configuration
]
})
export class EditVODTranscodingComponent implements OnInit, OnChanges {
- @Input() form: FormGroup
- @Input() formErrors: any
- @Input() serverConfig: HTMLServerConfig
+ private configService = inject(ConfigService)
+ private editConfigurationService = inject(EditConfigurationService)
+ private notifier = inject(Notifier)
+
+ readonly form = input<FormGroup>(undefined)
+ readonly formErrors = input<any>(undefined)
+ readonly serverConfig = input<HTMLServerConfig>(undefined)
transcodingThreadOptions: SelectOptionsItem[] = []
transcodingProfiles: SelectOptionsItem[] = []
@@ -40,12 +44,6 @@ export class EditVODTranscodingComponent implements OnInit, OnChanges {
additionalVideoExtensions = ''
- constructor (
- private configService: ConfigService,
- private editConfigurationService: EditConfigurationService,
- private notifier: Notifier
- ) { }
-
ngOnInit () {
this.transcodingThreadOptions = this.configService.transcodingThreadOptions
this.resolutions = this.editConfigurationService.getTranscodingResolutions()
@@ -57,12 +55,12 @@ export class EditVODTranscodingComponent implements OnInit, OnChanges {
if (changes['serverConfig']) {
this.transcodingProfiles = this.buildAvailableTranscodingProfile()
- this.additionalVideoExtensions = this.serverConfig.video.file.extensions.join(' ')
+ this.additionalVideoExtensions = this.serverConfig().video.file.extensions.join(' ')
}
}
buildAvailableTranscodingProfile () {
- const profiles = this.serverConfig.transcoding.availableProfiles
+ const profiles = this.serverConfig().transcoding.availableProfiles
return profiles.map(p => {
if (p === 'default') {
@@ -78,19 +76,19 @@ export class EditVODTranscodingComponent implements OnInit, OnChanges {
}
isRemoteRunnerVODEnabled () {
- return this.editConfigurationService.isRemoteRunnerVODEnabled(this.form)
+ return this.editConfigurationService.isRemoteRunnerVODEnabled(this.form())
}
isTranscodingEnabled () {
- return this.editConfigurationService.isTranscodingEnabled(this.form)
+ return this.editConfigurationService.isTranscodingEnabled(this.form())
}
isHLSEnabled () {
- return this.editConfigurationService.isHLSEnabled(this.form)
+ return this.editConfigurationService.isHLSEnabled(this.form())
}
isStudioEnabled () {
- return this.editConfigurationService.isStudioEnabled(this.form)
+ return this.editConfigurationService.isStudioEnabled(this.form())
}
getTranscodingDisabledClass () {
@@ -110,14 +108,14 @@ export class EditVODTranscodingComponent implements OnInit, OnChanges {
}
getTotalTranscodingThreads () {
- return this.editConfigurationService.getTotalTranscodingThreads(this.form)
+ return this.editConfigurationService.getTotalTranscodingThreads(this.form())
}
private checkTranscodingFields () {
- const transcodingControl = this.form.get('transcoding.enabled')
- const videoStudioControl = this.form.get('videoStudio.enabled')
- const hlsControl = this.form.get('transcoding.hls.enabled')
- const webVideosControl = this.form.get('transcoding.webVideos.enabled')
+ const transcodingControl = this.form().get('transcoding.enabled')
+ const videoStudioControl = this.form().get('videoStudio.enabled')
+ const hlsControl = this.form().get('transcoding.hls.enabled')
+ const webVideosControl = this.form().get('transcoding.webVideos.enabled')
webVideosControl.valueChanges
.subscribe(newValue => {
@@ -125,7 +123,11 @@ export class EditVODTranscodingComponent implements OnInit, OnChanges {
hlsControl.setValue(true)
// eslint-disable-next-line max-len
- this.notifier.info($localize`Automatically enable HLS transcoding because at least 1 output format must be enabled when transcoding is enabled`, '', 10000)
+ this.notifier.info(
+ $localize`Automatically enable HLS transcoding because at least 1 output format must be enabled when transcoding is enabled`,
+ '',
+ 10000
+ )
}
})
@@ -134,8 +136,12 @@ export class EditVODTranscodingComponent implements OnInit, OnChanges {
if (newValue === false && webVideosControl.value === false) {
webVideosControl.setValue(true)
- // eslint-disable-next-line max-len
- this.notifier.info($localize`Automatically enable Web Videos transcoding because at least 1 output format must be enabled when transcoding is enabled`, '', 10000)
+ this.notifier.info(
+ // eslint-disable-next-line max-len
+ $localize`Automatically enable Web Videos transcoding because at least 1 output format must be enabled when transcoding is enabled`,
+ '',
+ 10000
+ )
}
})
diff --git a/client/src/app/+admin/config/shared/config.service.ts b/client/src/app/+admin/config/shared/config.service.ts
index 3c38949451..2f500664e5 100644
--- a/client/src/app/+admin/config/shared/config.service.ts
+++ b/client/src/app/+admin/config/shared/config.service.ts
@@ -1,6 +1,6 @@
import { catchError } from 'rxjs/operators'
import { HttpClient } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { RestExtractor } from '@app/core'
import { CustomConfig } from '@peertube/peertube-models'
import { SelectOptionsItem } from '../../../../types/select-options-item.model'
@@ -8,16 +8,16 @@ import { environment } from '../../../../environments/environment'
@Injectable()
export class ConfigService {
+ private authHttp = inject(HttpClient)
+ private restExtractor = inject(RestExtractor)
+
private static BASE_APPLICATION_URL = environment.apiUrl + '/api/v1/config'
videoQuotaOptions: SelectOptionsItem[] = []
videoQuotaDailyOptions: SelectOptionsItem[] = []
transcodingThreadOptions: SelectOptionsItem[] = []
- constructor (
- private authHttp: HttpClient,
- private restExtractor: RestExtractor
- ) {
+ constructor () {
this.videoQuotaOptions = [
{ id: -1, label: $localize`Unlimited` },
{ id: 0, label: $localize`None - no upload possible` },
@@ -60,11 +60,11 @@ export class ConfigService {
getCustomConfig () {
return this.authHttp.get<CustomConfig>(ConfigService.BASE_APPLICATION_URL + '/custom')
- .pipe(catchError(res => this.restExtractor.handleError(res)))
+ .pipe(catchError(res => this.restExtractor.handleError(res)))
}
updateCustomConfig (data: CustomConfig) {
return this.authHttp.put<CustomConfig>(ConfigService.BASE_APPLICATION_URL + '/custom', data)
- .pipe(catchError(res => this.restExtractor.handleError(res)))
+ .pipe(catchError(res => this.restExtractor.handleError(res)))
}
}
diff --git a/client/src/app/+admin/follows/followers-list/followers-list.component.ts b/client/src/app/+admin/follows/followers-list/followers-list.component.ts
index 0bd861a232..e2248fc7a2 100644
--- a/client/src/app/+admin/follows/followers-list/followers-list.component.ts
+++ b/client/src/app/+admin/follows/followers-list/followers-list.component.ts
@@ -1,5 +1,5 @@
import { NgIf } from '@angular/common'
-import { Component, OnInit } from '@angular/core'
+import { Component, OnInit, inject } from '@angular/core'
import { ConfirmService, Notifier, RestPagination, RestTable } from '@app/core'
import { formatICU } from '@app/helpers'
import { InstanceFollowService } from '@app/shared/shared-instance/instance-follow.service'
@@ -33,7 +33,11 @@ import { AutoColspanDirective } from '../../../shared/shared-main/common/auto-co
PTDatePipe
]
})
-export class FollowersListComponent extends RestTable <ActorFollow> implements OnInit {
+export class FollowersListComponent extends RestTable<ActorFollow> implements OnInit {
+ private confirmService = inject(ConfirmService)
+ private notifier = inject(Notifier)
+ private followService = inject(InstanceFollowService)
+
followers: ActorFollow[] = []
totalRecords = 0
sort: SortMeta = { field: 'createdAt', order: -1 }
@@ -43,14 +47,6 @@ export class FollowersListComponent extends RestTable <ActorFollow> implements O
bulkActions: DropdownAction<ActorFollow[]>[] = []
- constructor (
- private confirmService: ConfirmService,
- private notifier: Notifier,
- private followService: InstanceFollowService
- ) {
- super()
- }
-
ngOnInit () {
this.initialize()
@@ -108,20 +104,20 @@ export class FollowersListComponent extends RestTable <ActorFollow> implements O
if (res === false) return
this.followService.rejectFollower(follows)
- .subscribe({
- next: () => {
- // eslint-disable-next-line max-len
- const message = formatICU(
- $localize`Rejected {count, plural, =1 {{followerName} follow request} other {{count} follow requests}}`,
- { count: follows.length, followerName: this.buildFollowerName(follows[0]) }
- )
- this.notifier.success(message)
-
- this.reloadData()
- },
-
- error: err => this.notifier.error(err.message)
- })
+ .subscribe({
+ next: () => {
+ // eslint-disable-next-line max-len
+ const message = formatICU(
+ $localize`Rejected {count, plural, =1 {{followerName} follow request} other {{count} follow requests}}`,
+ { count: follows.length, followerName: this.buildFollowerName(follows[0]) }
+ )
+ this.notifier.success(message)
+
+ this.reloadData()
+ },
+
+ error: err => this.notifier.error(err.message)
+ })
}
async deleteFollowers (follows: ActorFollow[]) {
@@ -140,21 +136,21 @@ export class FollowersListComponent extends RestTable <ActorFollow> implements O
if (res === false) return
this.followService.removeFollower(follows)
- .subscribe({
- next: () => {
- // eslint-disable-next-line max-len
- const message = formatICU(
- $localize`Removed {count, plural, =1 {{followerName} follow request} other {{count} follow requests}}`,
- icuParams
- )
+ .subscribe({
+ next: () => {
+ // eslint-disable-next-line max-len
+ const message = formatICU(
+ $localize`Removed {count, plural, =1 {{followerName} follow request} other {{count} follow requests}}`,
+ icuParams
+ )
- this.notifier.success(message)
+ this.notifier.success(message)
- this.reloadData()
- },
+ this.reloadData()
+ },
- error: err => this.notifier.error(err.message)
- })
+ error: err => this.notifier.error(err.message)
+ })
}
buildFollowerName (follow: ActorFollow) {
@@ -163,13 +159,13 @@ export class FollowersListComponent extends RestTable <ActorFollow> implements O
protected reloadDataInternal () {
this.followService.getFollowers({ pagination: this.pagination, sort: this.sort, search: this.search })
- .subscribe({
- next: resultList => {
- this.followers = resultList.data
- this.totalRecords = resultList.total
- },
-
- error: err => this.notifier.error(err.message)
- })
+ .subscribe({
+ next: resultList => {
+ this.followers = resultList.data
+ this.totalRecords = resultList.total
+ },
+
+ error: err => this.notifier.error(err.message)
+ })
}
}
diff --git a/client/src/app/+admin/follows/following-list/follow-modal.component.ts b/client/src/app/+admin/follows/following-list/follow-modal.component.ts
index c144e35e43..df8032aaac 100644
--- a/client/src/app/+admin/follows/following-list/follow-modal.component.ts
+++ b/client/src/app/+admin/follows/following-list/follow-modal.component.ts
@@ -1,5 +1,5 @@
import { NgClass, NgIf } from '@angular/common'
-import { Component, EventEmitter, OnInit, Output, ViewChild } from '@angular/core'
+import { Component, OnInit, inject, output, viewChild } from '@angular/core'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { Notifier } from '@app/core'
import { formatICU } from '@app/helpers'
@@ -20,23 +20,19 @@ import { GlobalIconComponent } from '../../../shared/shared-icons/global-icon.co
imports: [ GlobalIconComponent, FormsModule, ReactiveFormsModule, NgClass, NgIf, AlertComponent ]
})
export class FollowModalComponent extends FormReactive implements OnInit {
- @ViewChild('modal', { static: true }) modal: NgbModal
+ protected formReactiveService = inject(FormReactiveService)
+ private modalService = inject(NgbModal)
+ private followService = inject(InstanceFollowService)
+ private notifier = inject(Notifier)
- @Output() newFollow = new EventEmitter<void>()
+ readonly modal = viewChild<NgbModal>('modal')
+
+ readonly newFollow = output()
placeholder = 'example.com\[email protected]\[email protected]'
private openedModal: NgbModalRef
- constructor (
- protected formReactiveService: FormReactiveService,
- private modalService: NgbModal,
- private followService: InstanceFollowService,
- private notifier: Notifier
- ) {
- super()
- }
-
ngOnInit () {
this.buildForm({
hostsOrHandles: UNIQUE_HOSTS_OR_HANDLE_VALIDATOR
@@ -44,7 +40,7 @@ export class FollowModalComponent extends FormReactive implements OnInit {
}
openModal () {
- this.openedModal = this.modalService.open(this.modal, { centered: true })
+ this.openedModal = this.modalService.open(this.modal(), { centered: true })
}
hide () {
diff --git a/client/src/app/+admin/follows/following-list/following-list.component.ts b/client/src/app/+admin/follows/following-list/following-list.component.ts
index e3ea405ec2..e804881430 100644
--- a/client/src/app/+admin/follows/following-list/following-list.component.ts
+++ b/client/src/app/+admin/follows/following-list/following-list.component.ts
@@ -1,5 +1,5 @@
import { NgIf } from '@angular/common'
-import { Component, OnInit, ViewChild } from '@angular/core'
+import { Component, OnInit, inject, viewChild } from '@angular/core'
import { ConfirmService, Notifier, RestPagination, RestTable } from '@app/core'
import { formatICU } from '@app/helpers'
import { InstanceFollowService } from '@app/shared/shared-instance/instance-follow.service'
@@ -34,8 +34,12 @@ import { FollowModalComponent } from './follow-modal.component'
ButtonComponent
]
})
-export class FollowingListComponent extends RestTable <ActorFollow> implements OnInit {
- @ViewChild('followModal') followModal: FollowModalComponent
+export class FollowingListComponent extends RestTable<ActorFollow> implements OnInit {
+ private notifier = inject(Notifier)
+ private confirmService = inject(ConfirmService)
+ private followService = inject(InstanceFollowService)
+
+ readonly followModal = viewChild<FollowModalComponent>('followModal')
following: ActorFollow[] = []
totalRecords = 0
@@ -46,14 +50,6 @@ export class FollowingListComponent extends RestTable <ActorFollow> implements O
bulkActions: DropdownAction<ActorFollow[]>[] = []
- constructor (
- private notifier: Notifier,
- private confirmService: ConfirmService,
- private followService: InstanceFollowService
- ) {
- super()
- }
-
ngOnInit () {
this.initialize()
@@ -72,7 +68,7 @@ export class FollowingListComponent extends RestTable <ActorFollow> implements O
}
openFollowModal () {
- this.followModal.openModal()
+ this.followModal().openModal()
}
isInstanceFollowing (follow: ActorFollow) {
@@ -113,13 +109,13 @@ export class FollowingListComponent extends RestTable <ActorFollow> implements O
protected reloadDataInternal () {
this.followService.getFollowing({ pagination: this.pagination, sort: this.sort, search: this.search })
- .subscribe({
- next: resultList => {
- this.following = resultList.data
- this.totalRecords = resultList.total
- },
-
- error: err => this.notifier.error(err.message)
- })
+ .subscribe({
+ next: resultList => {
+ this.following = resultList.data
+ this.totalRecords = resultList.total
+ },
+
+ error: err => this.notifier.error(err.message)
+ })
}
}
diff --git a/client/src/app/+admin/follows/shared/redundancy-checkbox.component.html b/client/src/app/+admin/follows/shared/redundancy-checkbox.component.html
index 8a57d65f09..e4a466c8e9 100644
--- a/client/src/app/+admin/follows/shared/redundancy-checkbox.component.html
+++ b/client/src/app/+admin/follows/shared/redundancy-checkbox.component.html
@@ -1,3 +1,3 @@
<my-peertube-checkbox
- [inputName]="host + '-redundancy-allowed'" [(ngModel)]="redundancyAllowed" (ngModelChange)="updateRedundancyState()"
-></my-peertube-checkbox>
\ No newline at end of file
+ [inputName]="host() + '-redundancy-allowed'" [(ngModel)]="redundancyAllowed" (ngModelChange)="updateRedundancyState()"
+></my-peertube-checkbox>
diff --git a/client/src/app/+admin/follows/shared/redundancy-checkbox.component.ts b/client/src/app/+admin/follows/shared/redundancy-checkbox.component.ts
index 6f32ea0ead..39af376581 100644
--- a/client/src/app/+admin/follows/shared/redundancy-checkbox.component.ts
+++ b/client/src/app/+admin/follows/shared/redundancy-checkbox.component.ts
@@ -1,4 +1,4 @@
-import { Component, Input } from '@angular/core'
+import { Component, inject, input } from '@angular/core'
import { Notifier } from '@app/core'
import { FormsModule } from '@angular/forms'
import { PeertubeCheckboxComponent } from '../../../shared/shared-forms/peertube-checkbox.component'
@@ -10,24 +10,22 @@ import { RedundancyService } from '@app/shared/shared-main/video/redundancy.serv
imports: [ PeertubeCheckboxComponent, FormsModule ]
})
export class RedundancyCheckboxComponent {
- @Input() redundancyAllowed: boolean
- @Input() host: string
+ private notifier = inject(Notifier)
+ private redundancyService = inject(RedundancyService)
- constructor (
- private notifier: Notifier,
- private redundancyService: RedundancyService
- ) { }
+ readonly redundancyAllowed = input<boolean>(undefined)
+ readonly host = input<string>(undefined)
updateRedundancyState () {
- this.redundancyService.updateRedundancy(this.host, this.redundancyAllowed)
- .subscribe({
- next: () => {
- const stateLabel = this.redundancyAllowed ? $localize`enabled` : $localize`disabled`
+ this.redundancyService.updateRedundancy(this.host(), this.redundancyAllowed())
+ .subscribe({
+ next: () => {
+ const stateLabel = this.redundancyAllowed() ? $localize`enabled` : $localize`disabled`
- this.notifier.success($localize`Redundancy for ${this.host} is ${stateLabel}`)
- },
+ this.notifier.success($localize`Redundancy for ${this.host()} is ${stateLabel}`)
+ },
- error: err => this.notifier.error(err.message)
- })
+ error: err => this.notifier.error(err.message)
+ })
}
}
diff --git a/client/src/app/+admin/follows/video-redundancies-list/video-redundancies-list.component.ts b/client/src/app/+admin/follows/video-redundancies-list/video-redundancies-list.component.ts
index b5347db952..33daeea0b1 100644
--- a/client/src/app/+admin/follows/video-redundancies-list/video-redundancies-list.component.ts
+++ b/client/src/app/+admin/follows/video-redundancies-list/video-redundancies-list.component.ts
@@ -1,5 +1,5 @@
import { NgFor, NgIf } from '@angular/common'
-import { Component, OnInit } from '@angular/core'
+import { Component, OnInit, inject } from '@angular/core'
import { FormsModule } from '@angular/forms'
import { ConfirmService, Notifier, RestPagination, RestTable, ServerService } from '@app/core'
import { BytesPipe } from '@app/shared/shared-main/common/bytes.pipe'
@@ -38,6 +38,11 @@ import { VideoRedundancyInformationComponent } from './video-redundancy-informat
]
})
export class VideoRedundanciesListComponent extends RestTable implements OnInit {
+ private notifier = inject(Notifier)
+ private confirmService = inject(ConfirmService)
+ private redundancyService = inject(RedundancyService)
+ private serverService = inject(ServerService)
+
private static LS_DISPLAY_TYPE = 'video-redundancies-list-display-type'
videoRedundancies: VideoRedundancy[] = []
@@ -56,12 +61,7 @@ export class VideoRedundanciesListComponent extends RestTable implements OnInit
private bytesPipe: BytesPipe
- constructor (
- private notifier: Notifier,
- private confirmService: ConfirmService,
- private redundancyService: RedundancyService,
- private serverService: ServerService
- ) {
+ constructor () {
super()
this.bytesPipe = new BytesPipe()
@@ -77,15 +77,15 @@ export class VideoRedundanciesListComponent extends RestTable implements OnInit
this.initialize()
this.serverService.getServerStats()
- .subscribe(res => {
- const redundancies = res.videosRedundancy
+ .subscribe(res => {
+ const redundancies = res.videosRedundancy
- if (redundancies.length === 0) this.noRedundancies = true
+ if (redundancies.length === 0) this.noRedundancies = true
- for (const r of redundancies) {
- this.buildPieData(r)
- }
- })
+ for (const r of redundancies) {
+ this.buildPieData(r)
+ }
+ })
}
isDisplayingRemoteVideos () {
@@ -184,7 +184,6 @@ export class VideoRedundanciesListComponent extends RestTable implements OnInit
error: err => this.notifier.error(err.message)
})
-
}
protected reloadDataInternal () {
@@ -197,16 +196,16 @@ export class VideoRedundanciesListComponent extends RestTable implements OnInit
}
this.redundancyService.listVideoRedundancies(options)
- .subscribe({
- next: resultList => {
- this.videoRedundancies = resultList.data
- this.totalRecords = resultList.total
+ .subscribe({
+ next: resultList => {
+ this.videoRedundancies = resultList.data
+ this.totalRecords = resultList.total
- this.dataLoaded = true
- },
+ this.dataLoaded = true
+ },
- error: err => this.notifier.error(err.message)
- })
+ error: err => this.notifier.error(err.message)
+ })
}
private loadSelectLocalStorage () {
diff --git a/client/src/app/+admin/follows/video-redundancies-list/video-redundancy-information.component.html b/client/src/app/+admin/follows/video-redundancies-list/video-redundancy-information.component.html
index 4976cf38ce..2b94ae2e0c 100644
--- a/client/src/app/+admin/follows/video-redundancies-list/video-redundancy-information.component.html
+++ b/client/src/app/+admin/follows/video-redundancies-list/video-redundancy-information.component.html
@@ -1,19 +1,19 @@
<div>
<span class="label">Url</span>
- <a target="_blank" rel="noopener noreferrer" [href]="redundancyElement.fileUrl">{{ redundancyElement.fileUrl }}</a>
+ <a target="_blank" rel="noopener noreferrer" [href]="redundancyElement().fileUrl">{{ redundancyElement().fileUrl }}</a>
</div>
<div>
<span class="label">Created on</span>
- <span>{{ redundancyElement.createdAt | ptDate: 'medium' }}</span>
+ <span>{{ redundancyElement().createdAt | ptDate: 'medium' }}</span>
</div>
<div>
<span class="label">Expires on</span>
- <span>{{ redundancyElement.expiresOn | ptDate: 'medium' }}</span>
+ <span>{{ redundancyElement().expiresOn | ptDate: 'medium' }}</span>
</div>
<div>
<span class="label">Size</span>
- <span>{{ redundancyElement.size | bytes: 1 }}</span>
+ <span>{{ redundancyElement().size | bytes: 1 }}</span>
</div>
diff --git a/client/src/app/+admin/follows/video-redundancies-list/video-redundancy-information.component.ts b/client/src/app/+admin/follows/video-redundancies-list/video-redundancy-information.component.ts
index d185523cbe..7fce055b0f 100644
--- a/client/src/app/+admin/follows/video-redundancies-list/video-redundancy-information.component.ts
+++ b/client/src/app/+admin/follows/video-redundancies-list/video-redundancy-information.component.ts
@@ -1,4 +1,4 @@
-import { Component, Input } from '@angular/core'
+import { Component, input } from '@angular/core'
import { PTDatePipe } from '@app/shared/shared-main/common/date.pipe'
import { RedundancyInformation } from '@peertube/peertube-models'
import { BytesPipe } from '../../../shared/shared-main/common/bytes.pipe'
@@ -10,5 +10,5 @@ import { BytesPipe } from '../../../shared/shared-main/common/bytes.pipe'
imports: [ PTDatePipe, BytesPipe ]
})
export class VideoRedundancyInformationComponent {
- @Input() redundancyElement: RedundancyInformation
+ readonly redundancyElement = input<RedundancyInformation>(undefined)
}
diff --git a/client/src/app/+admin/moderation/abuse-list/abuse-list.component.ts b/client/src/app/+admin/moderation/abuse-list/abuse-list.component.ts
index afb1a44275..ddcc69534d 100644
--- a/client/src/app/+admin/moderation/abuse-list/abuse-list.component.ts
+++ b/client/src/app/+admin/moderation/abuse-list/abuse-list.component.ts
@@ -1,13 +1,11 @@
import { Component } from '@angular/core'
import { AbuseListTableComponent } from '../../../shared/shared-abuse-list/abuse-list-table.component'
-import { GlobalIconComponent } from '../../../shared/shared-icons/global-icon.component'
@Component({
selector: 'my-abuse-list',
templateUrl: './abuse-list.component.html',
styleUrls: [],
- imports: [ GlobalIconComponent, AbuseListTableComponent ]
+ imports: [ AbuseListTableComponent ]
})
export class AbuseListComponent {
-
}
diff --git a/client/src/app/+admin/moderation/registration-list/admin-registration.service.ts b/client/src/app/+admin/moderation/registration-list/admin-registration.service.ts
index f8ab04c713..b43bd53836 100644
--- a/client/src/app/+admin/moderation/registration-list/admin-registration.service.ts
+++ b/client/src/app/+admin/moderation/registration-list/admin-registration.service.ts
@@ -2,7 +2,7 @@ import { SortMeta } from 'primeng/api'
import { from } from 'rxjs'
import { catchError, concatMap, toArray } from 'rxjs/operators'
import { HttpClient, HttpParams } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { RestExtractor, RestPagination, RestService } from '@app/core'
import { arrayify } from '@peertube/peertube-core-utils'
import { ResultList, UserRegistration, UserRegistrationUpdateState } from '@peertube/peertube-models'
@@ -10,13 +10,11 @@ import { environment } from '../../../../environments/environment'
@Injectable()
export class AdminRegistrationService {
- private static BASE_REGISTRATION_URL = environment.apiUrl + '/api/v1/users/registrations'
+ private authHttp = inject(HttpClient)
+ private restExtractor = inject(RestExtractor)
+ private restService = inject(RestService)
- constructor (
- private authHttp: HttpClient,
- private restExtractor: RestExtractor,
- private restService: RestService
- ) { }
+ private static BASE_REGISTRATION_URL = environment.apiUrl + '/api/v1/users/registrations'
listRegistrations (options: {
pagination: RestPagination
diff --git a/client/src/app/+admin/moderation/registration-list/process-registration-modal.component.ts b/client/src/app/+admin/moderation/registration-list/process-registration-modal.component.ts
index 8b811b2eca..d94e4d5273 100644
--- a/client/src/app/+admin/moderation/registration-list/process-registration-modal.component.ts
+++ b/client/src/app/+admin/moderation/registration-list/process-registration-modal.component.ts
@@ -1,5 +1,5 @@
import { NgClass, NgIf } from '@angular/common'
-import { Component, EventEmitter, OnInit, Output, ViewChild } from '@angular/core'
+import { Component, OnInit, inject, output, viewChild } from '@angular/core'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { Notifier, ServerService } from '@app/core'
import { FormReactive } from '@app/shared/shared-forms/form-reactive'
@@ -19,25 +19,21 @@ import { REGISTRATION_MODERATION_RESPONSE_VALIDATOR } from './process-registrati
imports: [ NgIf, GlobalIconComponent, FormsModule, ReactiveFormsModule, NgClass, PeertubeCheckboxComponent, AlertComponent ]
})
export class ProcessRegistrationModalComponent extends FormReactive implements OnInit {
- @ViewChild('modal', { static: true }) modal: NgbModal
+ protected formReactiveService = inject(FormReactiveService)
+ private server = inject(ServerService)
+ private modalService = inject(NgbModal)
+ private notifier = inject(Notifier)
+ private registrationService = inject(AdminRegistrationService)
- @Output() registrationProcessed = new EventEmitter()
+ readonly modal = viewChild<NgbModal>('modal')
+
+ readonly registrationProcessed = output()
registration: UserRegistration
private openedModal: NgbModalRef
private processMode: 'accept' | 'reject'
- constructor (
- protected formReactiveService: FormReactiveService,
- private server: ServerService,
- private modalService: NgbModal,
- private notifier: Notifier,
- private registrationService: AdminRegistrationService
- ) {
- super()
- }
-
ngOnInit () {
this.buildForm({
moderationResponse: REGISTRATION_MODERATION_RESPONSE_VALIDATOR,
@@ -61,7 +57,7 @@ export class ProcessRegistrationModalComponent extends FormReactive implements O
preventEmailDelivery: !this.isEmailEnabled() || registration.emailVerified !== true
})
- this.openedModal = this.modalService.open(this.modal, { centered: true })
+ this.openedModal = this.modalService.open(this.modal(), { centered: true })
}
hide () {
diff --git a/client/src/app/+admin/moderation/registration-list/registration-list.component.ts b/client/src/app/+admin/moderation/registration-list/registration-list.component.ts
index 1d579e6dbf..8da1f59986 100644
--- a/client/src/app/+admin/moderation/registration-list/registration-list.component.ts
+++ b/client/src/app/+admin/moderation/registration-list/registration-list.component.ts
@@ -1,5 +1,5 @@
import { NgClass, NgIf } from '@angular/common'
-import { Component, OnInit, ViewChild } from '@angular/core'
+import { Component, OnInit, inject, viewChild } from '@angular/core'
import { ActivatedRoute, Router } from '@angular/router'
import { ConfirmService, MarkdownService, Notifier, RestPagination, RestTable, ServerService } from '@app/core'
import { formatICU } from '@app/helpers'
@@ -37,8 +37,16 @@ import { ProcessRegistrationModalComponent } from './process-registration-modal.
PTDatePipe
]
})
-export class RegistrationListComponent extends RestTable <UserRegistration> implements OnInit {
- @ViewChild('processRegistrationModal', { static: true }) processRegistrationModal: ProcessRegistrationModalComponent
+export class RegistrationListComponent extends RestTable<UserRegistration> implements OnInit {
+ protected route = inject(ActivatedRoute)
+ protected router = inject(Router)
+ private server = inject(ServerService)
+ private notifier = inject(Notifier)
+ private markdownRenderer = inject(MarkdownService)
+ private confirmService = inject(ConfirmService)
+ private adminRegistrationService = inject(AdminRegistrationService)
+
+ readonly processRegistrationModal = viewChild<ProcessRegistrationModalComponent>('processRegistrationModal')
registrations: (UserRegistration & { registrationReasonHTML?: string, moderationResponseHTML?: string })[] = []
totalRecords = 0
@@ -52,15 +60,7 @@ export class RegistrationListComponent extends RestTable <UserRegistration> impl
requiresEmailVerification: boolean
- constructor (
- protected route: ActivatedRoute,
- protected router: Router,
- private server: ServerService,
- private notifier: Notifier,
- private markdownRenderer: MarkdownService,
- private confirmService: ConfirmService,
- private adminRegistrationService: AdminRegistrationService
- ) {
+ constructor () {
super()
this.registrationActions = [
@@ -137,7 +137,7 @@ export class RegistrationListComponent extends RestTable <UserRegistration> impl
}
private openRegistrationRequestProcessModal (registration: UserRegistration, mode: 'accept' | 'reject') {
- this.processRegistrationModal.openModal(registration, mode)
+ this.processRegistrationModal().openModal(registration, mode)
}
private async removeRegistrations (registrations: UserRegistration[]) {
diff --git a/client/src/app/+admin/moderation/video-block-list/video-block-list.component.ts b/client/src/app/+admin/moderation/video-block-list/video-block-list.component.ts
index 0e18972b81..b9300a45d2 100644
--- a/client/src/app/+admin/moderation/video-block-list/video-block-list.component.ts
+++ b/client/src/app/+admin/moderation/video-block-list/video-block-list.component.ts
@@ -1,5 +1,5 @@
import { NgClass, NgIf } from '@angular/common'
-import { Component, OnInit } from '@angular/core'
+import { Component, OnInit, inject } from '@angular/core'
import { ActivatedRoute, Router } from '@angular/router'
import { ConfirmService, MarkdownService, Notifier, RestPagination, RestTable, ServerService } from '@app/core'
import { PTDatePipe } from '@app/shared/shared-main/common/date.pipe'
@@ -42,6 +42,15 @@ import { VideoCellComponent } from '../../../shared/shared-tables/video-cell.com
]
})
export class VideoBlockListComponent extends RestTable implements OnInit {
+ protected route = inject(ActivatedRoute)
+ protected router = inject(Router)
+ private notifier = inject(Notifier)
+ private serverService = inject(ServerService)
+ private confirmService = inject(ConfirmService)
+ private videoBlocklistService = inject(VideoBlockService)
+ private markdownRenderer = inject(MarkdownService)
+ private videoService = inject(VideoService)
+
blocklist: (VideoBlacklist & { reasonHtml?: string })[] = []
totalRecords = 0
sort: SortMeta = { field: 'createdAt', order: -1 }
@@ -66,16 +75,7 @@ export class VideoBlockListComponent extends RestTable implements OnInit {
}
]
- constructor (
- protected route: ActivatedRoute,
- protected router: Router,
- private notifier: Notifier,
- private serverService: ServerService,
- private confirmService: ConfirmService,
- private videoBlocklistService: VideoBlockService,
- private markdownRenderer: MarkdownService,
- private videoService: VideoService
- ) {
+ constructor () {
super()
this.videoBlocklistActions = [
diff --git a/client/src/app/+admin/moderation/watched-words-list/watched-words-list-admin.component.ts b/client/src/app/+admin/moderation/watched-words-list/watched-words-list-admin.component.ts
index a0696b4083..7d1ccb1d48 100644
--- a/client/src/app/+admin/moderation/watched-words-list/watched-words-list-admin.component.ts
+++ b/client/src/app/+admin/moderation/watched-words-list/watched-words-list-admin.component.ts
@@ -1,12 +1,11 @@
import { Component } from '@angular/core'
-import { GlobalIconComponent } from '@app/shared/shared-icons/global-icon.component'
+
import { WatchedWordsListAdminOwnerComponent } from '@app/shared/standalone-watched-words/watched-words-list-admin-owner.component'
@Component({
templateUrl: './watched-words-list-admin.component.html',
imports: [
- GlobalIconComponent,
WatchedWordsListAdminOwnerComponent
]
})
-export class WatchedWordsListAdminComponent { }
+export class WatchedWordsListAdminComponent {}
diff --git a/client/src/app/+admin/overview/comments/video-comment-list.component.ts b/client/src/app/+admin/overview/comments/video-comment-list.component.ts
index 415428ea14..001db1393b 100644
--- a/client/src/app/+admin/overview/comments/video-comment-list.component.ts
+++ b/client/src/app/+admin/overview/comments/video-comment-list.component.ts
@@ -1,16 +1,13 @@
import { Component } from '@angular/core'
import { VideoCommentService } from '@app/shared/shared-video-comment/video-comment.service'
import { FeedFormat } from '@peertube/peertube-models'
-import { GlobalIconComponent } from '../../../shared/shared-icons/global-icon.component'
-import { FeedComponent } from '../../../shared/shared-main/feeds/feed.component'
+
import { VideoCommentListAdminOwnerComponent } from '../../../shared/shared-video-comment/video-comment-list-admin-owner.component'
@Component({
selector: 'my-video-comment-list',
templateUrl: './video-comment-list.component.html',
imports: [
- GlobalIconComponent,
- FeedComponent,
VideoCommentListAdminOwnerComponent
]
})
diff --git a/client/src/app/+admin/overview/users/user-edit/user-create.component.ts b/client/src/app/+admin/overview/users/user-edit/user-create.component.ts
index f62f62eba7..af0d364c78 100644
--- a/client/src/app/+admin/overview/users/user-edit/user-create.component.ts
+++ b/client/src/app/+admin/overview/users/user-edit/user-create.component.ts
@@ -1,5 +1,5 @@
import { NgClass, NgFor, NgIf, NgTemplateOutlet } from '@angular/common'
-import { Component, OnInit } from '@angular/core'
+import { Component, OnInit, inject } from '@angular/core'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { Router, RouterLink } from '@angular/router'
import { ConfigService } from '@app/+admin/config/shared/config.service'
@@ -54,18 +54,18 @@ import { UserPasswordComponent } from './user-password.component'
]
})
export class UserCreateComponent extends UserEdit implements OnInit {
+ protected serverService = inject(ServerService)
+ protected formReactiveService = inject(FormReactiveService)
+ protected configService = inject(ConfigService)
+ protected screenService = inject(ScreenService)
+ protected auth = inject(AuthService)
+ private router = inject(Router)
+ private notifier = inject(Notifier)
+ private userAdminService = inject(UserAdminService)
+
error: string
- constructor (
- protected serverService: ServerService,
- protected formReactiveService: FormReactiveService,
- protected configService: ConfigService,
- protected screenService: ScreenService,
- protected auth: AuthService,
- private router: Router,
- private notifier: Notifier,
- private userAdminService: UserAdminService
- ) {
+ constructor () {
super()
this.buildQuotaOptions()
diff --git a/client/src/app/+admin/overview/users/user-edit/user-password.component.ts b/client/src/app/+admin/overview/users/user-edit/user-password.component.ts
index f0b09e9647..92329211c0 100644
--- a/client/src/app/+admin/overview/users/user-edit/user-password.component.ts
+++ b/client/src/app/+admin/overview/users/user-edit/user-password.component.ts
@@ -1,4 +1,4 @@
-import { Component, Input, OnInit } from '@angular/core'
+import { Component, OnInit, inject, input } from '@angular/core'
import { Notifier } from '@app/core'
import { USER_PASSWORD_VALIDATOR } from '@app/shared/form-validators/user-validators'
import { FormReactive } from '@app/shared/shared-forms/form-reactive'
@@ -15,20 +15,16 @@ import { UserAdminService } from '@app/shared/shared-users/user-admin.service'
imports: [ FormsModule, ReactiveFormsModule, NgClass, NgIf ]
})
export class UserPasswordComponent extends FormReactive implements OnInit {
- @Input() userId: number
- @Input() username: string
+ protected formReactiveService = inject(FormReactiveService)
+ private notifier = inject(Notifier)
+ private userAdminService = inject(UserAdminService)
+
+ readonly userId = input<number>(undefined)
+ readonly username = input<string>(undefined)
error: string
showPassword = false
- constructor (
- protected formReactiveService: FormReactiveService,
- private notifier: Notifier,
- private userAdminService: UserAdminService
- ) {
- super()
- }
-
ngOnInit () {
this.buildForm({
password: USER_PASSWORD_VALIDATOR
@@ -40,9 +36,9 @@ export class UserPasswordComponent extends FormReactive implements OnInit {
const userUpdate: UserUpdate = this.form.value
- this.userAdminService.updateUser(this.userId, userUpdate)
+ this.userAdminService.updateUser(this.userId(), userUpdate)
.subscribe({
- next: () => this.notifier.success($localize`Password changed for user ${this.username}.`),
+ next: () => this.notifier.success($localize`Password changed for user ${this.username()}.`),
error: err => {
this.error = err.message
diff --git a/client/src/app/+admin/overview/users/user-edit/user-update.component.ts b/client/src/app/+admin/overview/users/user-edit/user-update.component.ts
index edf2b4404e..f77848b79a 100644
--- a/client/src/app/+admin/overview/users/user-edit/user-update.component.ts
+++ b/client/src/app/+admin/overview/users/user-edit/user-update.component.ts
@@ -1,5 +1,5 @@
import { NgClass, NgFor, NgIf, NgTemplateOutlet } from '@angular/common'
-import { Component, OnDestroy, OnInit } from '@angular/core'
+import { Component, OnDestroy, OnInit, inject } from '@angular/core'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { ActivatedRoute, Router, RouterLink } from '@angular/router'
import { ConfigService } from '@app/+admin/config/shared/config.service'
@@ -52,23 +52,23 @@ import { UserPasswordComponent } from './user-password.component'
]
})
export class UserUpdateComponent extends UserEdit implements OnInit, OnDestroy {
+ protected formReactiveService = inject(FormReactiveService)
+ protected serverService = inject(ServerService)
+ protected configService = inject(ConfigService)
+ protected screenService = inject(ScreenService)
+ protected auth = inject(AuthService)
+ private route = inject(ActivatedRoute)
+ private router = inject(Router)
+ private notifier = inject(Notifier)
+ private userService = inject(UserService)
+ private twoFactorService = inject(TwoFactorService)
+ private userAdminService = inject(UserAdminService)
+
error: string
private paramsSub: Subscription
- constructor (
- protected formReactiveService: FormReactiveService,
- protected serverService: ServerService,
- protected configService: ConfigService,
- protected screenService: ScreenService,
- protected auth: AuthService,
- private route: ActivatedRoute,
- private router: Router,
- private notifier: Notifier,
- private userService: UserService,
- private twoFactorService: TwoFactorService,
- private userAdminService: UserAdminService
- ) {
+ constructor () {
super()
this.buildQuotaOptions()
@@ -168,7 +168,6 @@ export class UserUpdateComponent extends UserEdit implements OnInit, OnDestroy {
error: err => this.notifier.error(err.message)
})
-
}
private onUserFetched (userJson: UserType) {
diff --git a/client/src/app/+admin/overview/users/user-list/user-list.component.ts b/client/src/app/+admin/overview/users/user-list/user-list.component.ts
index 3bb5f20ab2..9c73514920 100644
--- a/client/src/app/+admin/overview/users/user-list/user-list.component.ts
+++ b/client/src/app/+admin/overview/users/user-list/user-list.component.ts
@@ -1,5 +1,5 @@
import { NgClass, NgIf } from '@angular/common'
-import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core'
+import { Component, OnDestroy, OnInit, inject, viewChild } from '@angular/core'
import { FormsModule } from '@angular/forms'
import { ActivatedRoute, Router, RouterLink } from '@angular/router'
import {
@@ -79,10 +79,21 @@ type UserForList = User & {
ProgressBarComponent
]
})
-export class UserListComponent extends RestTable <User> implements OnInit, OnDestroy {
+export class UserListComponent extends RestTable<User> implements OnInit, OnDestroy {
+ protected route = inject(ActivatedRoute)
+ protected router = inject(Router)
+ private notifier = inject(Notifier)
+ private confirmService = inject(ConfirmService)
+ private auth = inject(AuthService)
+ private blocklist = inject(BlocklistService)
+ private userAdminService = inject(UserAdminService)
+ private peertubeLocalStorage = inject(LocalStorageService)
+ private hooks = inject(HooksService)
+ private pluginService = inject(PluginService)
+
private static readonly LS_SELECTED_COLUMNS_KEY = 'admin-user-list-selected-columns'
- @ViewChild('userBanModal', { static: true }) userBanModal: UserBanModalComponent
+ readonly userBanModal = viewChild<UserBanModalComponent>('userBanModal')
users: (User & { accountMutedStatus: AccountMutedStatus })[] = []
@@ -115,21 +126,6 @@ export class UserListComponent extends RestTable <User> implements OnInit, OnDes
private _selectedColumns: string[] = []
- constructor (
- protected route: ActivatedRoute,
- protected router: Router,
- private notifier: Notifier,
- private confirmService: ConfirmService,
- private auth: AuthService,
- private blocklist: BlocklistService,
- private userAdminService: UserAdminService,
- private peertubeLocalStorage: LocalStorageService,
- private hooks: HooksService,
- private pluginService: PluginService
- ) {
- super()
- }
-
get authUser () {
return this.auth.getUser()
}
@@ -262,7 +258,7 @@ export class UserListComponent extends RestTable <User> implements OnInit, OnDes
}
}
- this.userBanModal.openModal(users)
+ this.userBanModal().openModal(users)
}
onUserChanged () {
@@ -281,19 +277,19 @@ export class UserListComponent extends RestTable <User> implements OnInit, OnDes
if (res === false) return
this.userAdminService.unbanUsers(users)
- .subscribe({
- next: () => {
- this.notifier.success(
- formatICU(
- $localize`{count, plural, =1 {1 user unbanned.} other {{count} users unbanned.}}`,
- { count: users.length }
- )
+ .subscribe({
+ next: () => {
+ this.notifier.success(
+ formatICU(
+ $localize`{count, plural, =1 {1 user unbanned.} other {{count} users unbanned.}}`,
+ { count: users.length }
)
- this.reloadData()
- },
+ )
+ this.reloadData()
+ },
- error: err => this.notifier.error(err.message)
- })
+ error: err => this.notifier.error(err.message)
+ })
}
async removeUsers (users: User[]) {
diff --git a/client/src/app/+admin/overview/videos/video-admin.service.ts b/client/src/app/+admin/overview/videos/video-admin.service.ts
index 166b1fe041..63aae2caf0 100644
--- a/client/src/app/+admin/overview/videos/video-admin.service.ts
+++ b/client/src/app/+admin/overview/videos/video-admin.service.ts
@@ -1,5 +1,5 @@
import { HttpClient, HttpParams } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { RestExtractor, RestPagination, RestService } from '@app/core'
import { AdvancedInputFilter } from '@app/shared/shared-forms/advanced-input-filter.component'
import { Video } from '@app/shared/shared-main/video/video.model'
@@ -11,13 +11,10 @@ import { catchError, switchMap } from 'rxjs/operators'
@Injectable()
export class VideoAdminService {
-
- constructor (
- private videoService: VideoService,
- private authHttp: HttpClient,
- private restExtractor: RestExtractor,
- private restService: RestService
- ) {}
+ private videoService = inject(VideoService)
+ private authHttp = inject(HttpClient)
+ private restExtractor = inject(RestExtractor)
+ private restService = inject(RestService)
getAdminVideos (
options: CommonVideoParams & { pagination: RestPagination, search?: string }
@@ -28,16 +25,16 @@ export class VideoAdminService {
params = this.videoService.buildCommonVideosParams({ params, ...omit(options, [ 'search', 'pagination' ]) })
params = params.set('start', pagination.start.toString())
- .set('count', pagination.count.toString())
+ .set('count', pagination.count.toString())
params = this.buildAdminParamsFromSearch(search, params)
return this.authHttp
- .get<ResultList<Video>>(VideoService.BASE_VIDEO_URL, { params })
- .pipe(
- switchMap(res => this.videoService.extractVideos(res)),
- catchError(err => this.restExtractor.handleError(err))
- )
+ .get<ResultList<Video>>(VideoService.BASE_VIDEO_URL, { params })
+ .pipe(
+ switchMap(res => this.videoService.extractVideos(res)),
+ catchError(err => this.restExtractor.handleError(err))
+ )
}
buildAdminInputFilter (): AdvancedInputFilter[] {
diff --git a/client/src/app/+admin/overview/videos/video-list.component.ts b/client/src/app/+admin/overview/videos/video-list.component.ts
index 1ab24baabf..347015fec2 100644
--- a/client/src/app/+admin/overview/videos/video-list.component.ts
+++ b/client/src/app/+admin/overview/videos/video-list.component.ts
@@ -1,5 +1,5 @@
import { NgClass, NgFor, NgIf } from '@angular/common'
-import { Component, OnInit, ViewChild } from '@angular/core'
+import { Component, OnInit, inject, viewChild } from '@angular/core'
import { ActivatedRoute, Router, RouterLink } from '@angular/router'
import { AuthService, ConfirmService, Notifier, RestPagination, RestTable, ServerService } from '@app/core'
import { formatICU } from '@app/helpers'
@@ -59,8 +59,20 @@ import { VideoAdminService } from './video-admin.service'
BytesPipe
]
})
-export class VideoListComponent extends RestTable <Video> implements OnInit {
- @ViewChild('videoBlockModal') videoBlockModal: VideoBlockComponent
+export class VideoListComponent extends RestTable<Video> implements OnInit {
+ protected route = inject(ActivatedRoute)
+ protected router = inject(Router)
+ private confirmService = inject(ConfirmService)
+ private auth = inject(AuthService)
+ private notifier = inject(Notifier)
+ private videoService = inject(VideoService)
+ private videoAdminService = inject(VideoAdminService)
+ private videoBlockService = inject(VideoBlockService)
+ private videoCaptionService = inject(VideoCaptionService)
+ private server = inject(ServerService)
+ private videoFileTokenService = inject(VideoFileTokenService)
+
+ readonly videoBlockModal = viewChild<VideoBlockComponent>('videoBlockModal')
videos: Video[] = []
@@ -91,23 +103,7 @@ export class VideoListComponent extends RestTable <Video> implements OnInit {
loading = true
- private videoFileTokens: { [ videoId: number ]: string } = {}
-
- constructor (
- protected route: ActivatedRoute,
- protected router: Router,
- private confirmService: ConfirmService,
- private auth: AuthService,
- private notifier: Notifier,
- private videoService: VideoService,
- private videoAdminService: VideoAdminService,
- private videoBlockService: VideoBlockService,
- private videoCaptionService: VideoCaptionService,
- private server: ServerService,
- private videoFileTokenService: VideoFileTokenService
- ) {
- super()
- }
+ private videoFileTokens: { [videoId: number]: string } = {}
get authUser () {
return this.auth.getUser()
@@ -132,7 +128,7 @@ export class VideoListComponent extends RestTable <Video> implements OnInit {
},
{
label: $localize`Block`,
- handler: videos => this.videoBlockModal.show(videos),
+ handler: videos => this.videoBlockModal().show(videos),
isDisplayed: videos => this.authUser.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST) && videos.every(v => !v.blacklisted),
iconName: 'no'
},
diff --git a/client/src/app/+admin/plugins/plugin-list-installed/plugin-list-installed.component.ts b/client/src/app/+admin/plugins/plugin-list-installed/plugin-list-installed.component.ts
index bff12e18bf..f85809873e 100644
--- a/client/src/app/+admin/plugins/plugin-list-installed/plugin-list-installed.component.ts
+++ b/client/src/app/+admin/plugins/plugin-list-installed/plugin-list-installed.component.ts
@@ -1,5 +1,5 @@
import { NgFor, NgIf } from '@angular/common'
-import { Component, OnInit } from '@angular/core'
+import { Component, OnInit, inject } from '@angular/core'
import { ActivatedRoute, Router } from '@angular/router'
import { PluginApiService } from '@app/+admin/plugins/shared/plugin-api.service'
import { ComponentPagination, ConfirmService, hasMoreItems, Notifier, resetCurrentPage, updatePaginationOnDelete } from '@app/core'
@@ -26,6 +26,13 @@ import { PluginCardComponent } from '../shared/plugin-card.component'
]
})
export class PluginListInstalledComponent implements OnInit {
+ private pluginService = inject(PluginService)
+ private pluginApiService = inject(PluginApiService)
+ private notifier = inject(Notifier)
+ private confirmService = inject(ConfirmService)
+ private router = inject(Router)
+ private route = inject(ActivatedRoute)
+
pluginType: PluginType_Type
pagination: ComponentPagination = {
@@ -41,16 +48,6 @@ export class PluginListInstalledComponent implements OnInit {
onDataSubject = new Subject<any[]>()
- constructor (
- private pluginService: PluginService,
- private pluginApiService: PluginApiService,
- private notifier: Notifier,
- private confirmService: ConfirmService,
- private router: Router,
- private route: ActivatedRoute
- ) {
- }
-
ngOnInit () {
if (!this.route.snapshot.queryParams['pluginType']) {
const queryParams = { pluginType: PluginType.PLUGIN }
@@ -76,16 +73,16 @@ export class PluginListInstalledComponent implements OnInit {
loadMorePlugins () {
this.pluginApiService.getPlugins(this.pluginType, this.pagination, this.sort)
- .subscribe({
- next: res => {
- this.plugins = this.plugins.concat(res.data)
- this.pagination.totalItems = res.total
+ .subscribe({
+ next: res => {
+ this.plugins = this.plugins.concat(res.data)
+ this.pagination.totalItems = res.total
- this.onDataSubject.next(res.data)
- },
+ this.onDataSubject.next(res.data)
+ },
- error: err => this.notifier.error(err.message)
- })
+ error: err => this.notifier.error(err.message)
+ })
}
onNearOfBottom () {
@@ -171,21 +168,21 @@ export class PluginListInstalledComponent implements OnInit {
this.updating[pluginKey] = true
this.pluginApiService.update(plugin.name, plugin.type)
- .pipe()
- .subscribe({
- next: res => {
- this.updating[pluginKey] = false
+ .pipe()
+ .subscribe({
+ next: res => {
+ this.updating[pluginKey] = false
- this.notifier.success($localize`${plugin.name} updated.`)
+ this.notifier.success($localize`${plugin.name} updated.`)
- Object.assign(plugin, res)
- },
+ Object.assign(plugin, res)
+ },
- error: err => {
- this.notifier.error(err.message)
- this.updating[pluginKey] = false
- }
- })
+ error: err => {
+ this.notifier.error(err.message)
+ this.updating[pluginKey] = false
+ }
+ })
}
getShowRouterLink (plugin: PeerTubePlugin) {
diff --git a/client/src/app/+admin/plugins/plugin-search/plugin-search.component.ts b/client/src/app/+admin/plugins/plugin-search/plugin-search.component.ts
index adf0743e51..fddefc2d1d 100644
--- a/client/src/app/+admin/plugins/plugin-search/plugin-search.component.ts
+++ b/client/src/app/+admin/plugins/plugin-search/plugin-search.component.ts
@@ -1,5 +1,5 @@
import { NgFor, NgIf } from '@angular/common'
-import { Component, OnInit } from '@angular/core'
+import { Component, OnInit, inject } from '@angular/core'
import { ActivatedRoute, Router } from '@angular/router'
import { PluginApiService } from '@app/+admin/plugins/shared/plugin-api.service'
import { ComponentPagination, ConfirmService, hasMoreItems, Notifier, PluginService, resetCurrentPage } from '@app/core'
@@ -32,6 +32,13 @@ import { PluginCardComponent } from '../shared/plugin-card.component'
]
})
export class PluginSearchComponent implements OnInit {
+ private pluginService = inject(PluginService)
+ private pluginApiService = inject(PluginApiService)
+ private notifier = inject(Notifier)
+ private confirmService = inject(ConfirmService)
+ private router = inject(Router)
+ private route = inject(ActivatedRoute)
+
pluginType: PluginType_Type
pagination: ComponentPagination = {
@@ -52,16 +59,6 @@ export class PluginSearchComponent implements OnInit {
private searchSubject = new Subject<string>()
- constructor (
- private pluginService: PluginService,
- private pluginApiService: PluginApiService,
- private notifier: Notifier,
- private confirmService: ConfirmService,
- private router: Router,
- private route: ActivatedRoute
- ) {
- }
-
ngOnInit () {
if (!this.route.snapshot.queryParams['pluginType']) {
const queryParams = { pluginType: PluginType.PLUGIN }
@@ -79,11 +76,11 @@ export class PluginSearchComponent implements OnInit {
})
this.searchSubject.asObservable()
- .pipe(
- debounceTime(400),
- distinctUntilChanged()
- )
- .subscribe(search => this.router.navigate([], { queryParams: { search }, queryParamsHandling: 'merge' }))
+ .pipe(
+ debounceTime(400),
+ distinctUntilChanged()
+ )
+ .subscribe(search => this.router.navigate([], { queryParams: { search }, queryParamsHandling: 'merge' }))
}
onSearchChange (event: Event) {
@@ -103,23 +100,23 @@ export class PluginSearchComponent implements OnInit {
this.isSearching = true
this.pluginApiService.searchAvailablePlugins(this.pluginType, this.pagination, this.sort, this.search)
- .subscribe({
- next: res => {
- this.isSearching = false
+ .subscribe({
+ next: res => {
+ this.isSearching = false
- this.plugins = this.plugins.concat(res.data)
- this.pagination.totalItems = res.total
+ this.plugins = this.plugins.concat(res.data)
+ this.pagination.totalItems = res.total
- this.onDataSubject.next(res.data)
- },
+ this.onDataSubject.next(res.data)
+ },
- error: err => {
- logger.error(err)
+ error: err => {
+ logger.error(err)
- const message = $localize`The plugin index is not available. Please retry later.`
- this.notifier.error(message)
- }
- })
+ const message = $localize`The plugin index is not available. Please retry later.`
+ this.notifier.error(message)
+ }
+ })
}
onNearOfBottom () {
@@ -154,21 +151,21 @@ export class PluginSearchComponent implements OnInit {
this.installing[plugin.npmName] = true
this.pluginApiService.install(plugin.npmName)
- .subscribe({
- next: () => {
- this.installing[plugin.npmName] = false
- this.pluginInstalled = true
+ .subscribe({
+ next: () => {
+ this.installing[plugin.npmName] = false
+ this.pluginInstalled = true
- this.notifier.success($localize`${plugin.name} installed.`)
+ this.notifier.success($localize`${plugin.name} installed.`)
- plugin.installed = true
- },
+ plugin.installed = true
+ },
- error: err => {
- this.installing[plugin.npmName] = false
+ error: err => {
+ this.installing[plugin.npmName] = false
- this.notifier.error(err.message)
- }
- })
+ this.notifier.error(err.message)
+ }
+ })
}
}
diff --git a/client/src/app/+admin/plugins/plugin-show-installed/plugin-show-installed.component.ts b/client/src/app/+admin/plugins/plugin-show-installed/plugin-show-installed.component.ts
index 0a9b16714e..ef2fa4dceb 100644
--- a/client/src/app/+admin/plugins/plugin-show-installed/plugin-show-installed.component.ts
+++ b/client/src/app/+admin/plugins/plugin-show-installed/plugin-show-installed.component.ts
@@ -1,6 +1,6 @@
import { Subscription } from 'rxjs'
import { map, switchMap } from 'rxjs/operators'
-import { Component, OnDestroy, OnInit } from '@angular/core'
+import { Component, OnDestroy, OnInit, inject } from '@angular/core'
import { ActivatedRoute } from '@angular/router'
import { HooksService, Notifier, PluginService } from '@app/core'
import { FormReactive } from '@app/shared/shared-forms/form-reactive'
@@ -18,6 +18,13 @@ import { BuildFormArgument } from '@app/shared/form-validators/form-validator.mo
imports: [ NgIf, FormsModule, ReactiveFormsModule, NgFor, DynamicFormFieldComponent ]
})
export class PluginShowInstalledComponent extends FormReactive implements OnInit, OnDestroy {
+ protected formReactiveService = inject(FormReactiveService)
+ private pluginService = inject(PluginService)
+ private pluginAPIService = inject(PluginApiService)
+ private notifier = inject(Notifier)
+ private hooks = inject(HooksService)
+ private route = inject(ActivatedRoute)
+
plugin: PeerTubePlugin
registeredSettings: RegisterServerSettingOptions[] = []
pluginTypeLabel: string
@@ -25,17 +32,6 @@ export class PluginShowInstalledComponent extends FormReactive implements OnInit
private sub: Subscription
private npmName: string
- constructor (
- protected formReactiveService: FormReactiveService,
- private pluginService: PluginService,
- private pluginAPIService: PluginApiService,
- private notifier: Notifier,
- private hooks: HooksService,
- private route: ActivatedRoute
- ) {
- super()
- }
-
ngOnInit () {
this.sub = this.route.params.subscribe(
routeParams => {
@@ -54,13 +50,13 @@ export class PluginShowInstalledComponent extends FormReactive implements OnInit
const settings = this.form.value
this.pluginAPIService.updatePluginSettings(this.plugin.name, this.plugin.type, settings)
- .subscribe({
- next: () => {
- this.notifier.success($localize`Settings updated.`)
- },
+ .subscribe({
+ next: () => {
+ this.notifier.success($localize`Settings updated.`)
+ },
- error: err => this.notifier.error(err.message)
- })
+ error: err => this.notifier.error(err.message)
+ })
}
hasRegisteredSettings () {
@@ -83,23 +79,23 @@ export class PluginShowInstalledComponent extends FormReactive implements OnInit
private loadPlugin (npmName: string) {
this.pluginAPIService.getPlugin(npmName)
- .pipe(switchMap(plugin => {
- return this.pluginAPIService.getPluginRegisteredSettings(plugin.name, plugin.type)
- .pipe(map(data => ({ plugin, registeredSettings: data.registeredSettings })))
- }))
- .subscribe({
- next: async ({ plugin, registeredSettings }) => {
- this.plugin = plugin
+ .pipe(switchMap(plugin => {
+ return this.pluginAPIService.getPluginRegisteredSettings(plugin.name, plugin.type)
+ .pipe(map(data => ({ plugin, registeredSettings: data.registeredSettings })))
+ }))
+ .subscribe({
+ next: async ({ plugin, registeredSettings }) => {
+ this.plugin = plugin
- this.registeredSettings = await this.translateSettings(registeredSettings)
+ this.registeredSettings = await this.translateSettings(registeredSettings)
- this.pluginTypeLabel = this.pluginAPIService.getPluginTypeLabel(this.plugin.type)
+ this.pluginTypeLabel = this.pluginAPIService.getPluginTypeLabel(this.plugin.type)
- this.buildSettingsForm()
- },
+ this.buildSettingsForm()
+ },
- error: err => this.notifier.error(err.message)
- })
+ error: err => this.notifier.error(err.message)
+ })
}
private buildSettingsForm () {
diff --git a/client/src/app/+admin/plugins/shared/plugin-api.service.ts b/client/src/app/+admin/plugins/shared/plugin-api.service.ts
index e1bd2f1256..d23ceb4d14 100644
--- a/client/src/app/+admin/plugins/shared/plugin-api.service.ts
+++ b/client/src/app/+admin/plugins/shared/plugin-api.service.ts
@@ -1,6 +1,6 @@
import { catchError } from 'rxjs/operators'
import { HttpClient, HttpParams } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { ComponentPagination, RestExtractor, RestService } from '@app/core'
import { PluginService } from '@app/core/plugins/plugin.service'
import {
@@ -17,14 +17,12 @@ import { environment } from '../../../../environments/environment'
@Injectable()
export class PluginApiService {
- private static BASE_PLUGIN_URL = environment.apiUrl + '/api/v1/plugins'
+ private authHttp = inject(HttpClient)
+ private restExtractor = inject(RestExtractor)
+ private restService = inject(RestService)
+ private pluginService = inject(PluginService)
- constructor (
- private authHttp: HttpClient,
- private restExtractor: RestExtractor,
- private restService: RestService,
- private pluginService: PluginService
- ) { }
+ private static BASE_PLUGIN_URL = environment.apiUrl + '/api/v1/plugins'
getPluginTypeLabel (type: PluginType_Type) {
if (type === PluginType.PLUGIN) {
@@ -46,7 +44,7 @@ export class PluginApiService {
params = params.append('pluginType', pluginType.toString())
return this.authHttp.get<ResultList<PeerTubePlugin>>(PluginApiService.BASE_PLUGIN_URL, { params })
- .pipe(catchError(res => this.restExtractor.handleError(res)))
+ .pipe(catchError(res => this.restExtractor.handleError(res)))
}
searchAvailablePlugins (
@@ -64,14 +62,14 @@ export class PluginApiService {
if (search) params = params.append('search', search)
return this.authHttp.get<ResultList<PeerTubePluginIndex>>(PluginApiService.BASE_PLUGIN_URL + '/available', { params })
- .pipe(catchError(res => this.restExtractor.handleError(res)))
+ .pipe(catchError(res => this.restExtractor.handleError(res)))
}
getPlugin (npmName: string) {
const path = PluginApiService.BASE_PLUGIN_URL + '/' + npmName
return this.authHttp.get<PeerTubePlugin>(path)
- .pipe(catchError(res => this.restExtractor.handleError(res)))
+ .pipe(catchError(res => this.restExtractor.handleError(res)))
}
getPluginRegisteredSettings (pluginName: string, pluginType: PluginType_Type) {
@@ -79,9 +77,9 @@ export class PluginApiService {
const path = PluginApiService.BASE_PLUGIN_URL + '/' + npmName + '/registered-settings'
return this.authHttp.get<RegisteredServerSettings>(path)
- .pipe(
- catchError(res => this.restExtractor.handleError(res))
- )
+ .pipe(
+ catchError(res => this.restExtractor.handleError(res))
+ )
}
updatePluginSettings (pluginName: string, pluginType: PluginType_Type, settings: any) {
@@ -89,7 +87,7 @@ export class PluginApiService {
const path = PluginApiService.BASE_PLUGIN_URL + '/' + npmName + '/settings'
return this.authHttp.put(path, { settings })
- .pipe(catchError(res => this.restExtractor.handleError(res)))
+ .pipe(catchError(res => this.restExtractor.handleError(res)))
}
uninstall (pluginName: string, pluginType: PluginType_Type) {
@@ -98,7 +96,7 @@ export class PluginApiService {
}
return this.authHttp.post(PluginApiService.BASE_PLUGIN_URL + '/uninstall', body)
- .pipe(catchError(res => this.restExtractor.handleError(res)))
+ .pipe(catchError(res => this.restExtractor.handleError(res)))
}
update (pluginName: string, pluginType: PluginType_Type) {
@@ -107,7 +105,7 @@ export class PluginApiService {
}
return this.authHttp.post(PluginApiService.BASE_PLUGIN_URL + '/update', body)
- .pipe(catchError(res => this.restExtractor.handleError(res)))
+ .pipe(catchError(res => this.restExtractor.handleError(res)))
}
install (npmName: string) {
@@ -116,7 +114,7 @@ export class PluginApiService {
}
return this.authHttp.post(PluginApiService.BASE_PLUGIN_URL + '/install', body)
- .pipe(catchError(res => this.restExtractor.handleError(res)))
+ .pipe(catchError(res => this.restExtractor.handleError(res)))
}
getPluginOrThemeHref (type: PluginType_Type, name: string) {
diff --git a/client/src/app/+admin/plugins/shared/plugin-card.component.html b/client/src/app/+admin/plugins/shared/plugin-card.component.html
index 8ec9573b07..73cf067340 100644
--- a/client/src/app/+admin/plugins/shared/plugin-card.component.html
+++ b/client/src/app/+admin/plugins/shared/plugin-card.component.html
@@ -1,15 +1,15 @@
<div class="card plugin">
<div class="card-body">
<div class="first-row">
- <span class="plugin-name">{{ plugin.name }}</span>
+ <span class="plugin-name">{{ plugin().name }}</span>
- <span class="plugin-version">{{ version }}</span>
+ <span class="plugin-version">{{ version() }}</span>
- <a class="plugin-icon" target="_blank" rel="noopener noreferrer" [href]="plugin.homepage" i18n-title title="Homepage (new window)">
+ <a class="plugin-icon" target="_blank" rel="noopener noreferrer" [href]="plugin().homepage" i18n-title title="Homepage (new window)">
<my-global-icon iconName="home"></my-global-icon>
</a>
- <a class="plugin-icon" target="_blank" rel="noopener noreferrer" [href]="getPluginOrThemeHref(plugin.name)" i18n-title title="NPM page (new window)">
+ <a class="plugin-icon" target="_blank" rel="noopener noreferrer" [href]="getPluginOrThemeHref(plugin().name)" i18n-title title="NPM page (new window)">
<my-global-icon iconName="registry"></my-global-icon>
</a>
@@ -21,7 +21,7 @@
</div>
<div class="second-row">
- <div dir="auto" class="description">{{ plugin.description }}</div>
+ <div dir="auto" class="description">{{ plugin().description }}</div>
</div>
</div>
</div>
diff --git a/client/src/app/+admin/plugins/shared/plugin-card.component.ts b/client/src/app/+admin/plugins/shared/plugin-card.component.ts
index 045e0cdd14..1041870c17 100644
--- a/client/src/app/+admin/plugins/shared/plugin-card.component.ts
+++ b/client/src/app/+admin/plugins/shared/plugin-card.component.ts
@@ -1,4 +1,4 @@
-import { Component, Input } from '@angular/core'
+import { Component, inject, input } from '@angular/core'
import { PeerTubePlugin, PeerTubePluginIndex, PluginType_Type } from '@peertube/peertube-models'
import { PluginApiService } from './plugin-api.service'
import { GlobalIconComponent } from '../../../shared/shared-icons/global-icon.component'
@@ -9,18 +9,14 @@ import { GlobalIconComponent } from '../../../shared/shared-icons/global-icon.co
styleUrls: [ './plugin-card.component.scss' ],
imports: [ GlobalIconComponent ]
})
-
export class PluginCardComponent {
- @Input() plugin: PeerTubePluginIndex | PeerTubePlugin
- @Input() version: string
- @Input() pluginType: PluginType_Type
+ private pluginApiService = inject(PluginApiService)
- constructor (
- private pluginApiService: PluginApiService
- ) {
- }
+ readonly plugin = input<PeerTubePluginIndex | PeerTubePlugin>(undefined)
+ readonly version = input<string>(undefined)
+ readonly pluginType = input<PluginType_Type>(undefined)
getPluginOrThemeHref (name: string) {
- return this.pluginApiService.getPluginOrThemeHref(this.pluginType, name)
+ return this.pluginApiService.getPluginOrThemeHref(this.pluginType(), name)
}
}
diff --git a/client/src/app/+admin/shared/user-email-info.component.html b/client/src/app/+admin/shared/user-email-info.component.html
index 92a1c9a275..c7146a68b9 100644
--- a/client/src/app/+admin/shared/user-email-info.component.html
+++ b/client/src/app/+admin/shared/user-email-info.component.html
@@ -1,13 +1,13 @@
<ng-container>
- <a [href]="'mailto:' + entry.email" [title]="getTitle()">
- @if (showEmailVerifyInformation) {
- @if (entry.emailVerified === true) {
- &#x2713; {{ entry.email }}
+ <a [href]="'mailto:' + entry().email" [title]="getTitle()">
+ @if (showEmailVerifyInformation()) {
+ @if (entry().emailVerified === true) {
+ &#x2713; {{ entry().email }}
} @else {
- <em *ngIf="!entry.emailVerified">? {{ entry.email }}</em>
+ <em *ngIf="!entry().emailVerified">? {{ entry().email }}</em>
}
} @else {
- {{ entry.email }}
+ {{ entry().email }}
}
</a>
</ng-container>
diff --git a/client/src/app/+admin/shared/user-email-info.component.ts b/client/src/app/+admin/shared/user-email-info.component.ts
index 40f9a4595e..80c9b10fb7 100644
--- a/client/src/app/+admin/shared/user-email-info.component.ts
+++ b/client/src/app/+admin/shared/user-email-info.component.ts
@@ -1,4 +1,4 @@
-import { Component, Input, booleanAttribute } from '@angular/core'
+import { Component, booleanAttribute, input } from '@angular/core'
import { User, UserRegistration } from '@peertube/peertube-models'
import { NgIf } from '@angular/common'
@@ -9,11 +9,11 @@ import { NgIf } from '@angular/common'
imports: [ NgIf ]
})
export class UserEmailInfoComponent {
- @Input() entry: User | UserRegistration
- @Input({ transform: booleanAttribute }) showEmailVerifyInformation: boolean
+ readonly entry = input<User | UserRegistration>(undefined)
+ readonly showEmailVerifyInformation = input<boolean, unknown>(undefined, { transform: booleanAttribute })
getTitle () {
- if (this.entry.emailVerified) {
+ if (this.entry().emailVerified) {
return $localize`User email has been verified`
}
diff --git a/client/src/app/+admin/shared/user-real-quota-info.component.ts b/client/src/app/+admin/shared/user-real-quota-info.component.ts
index 18bb9b272f..6a8b1a7643 100644
--- a/client/src/app/+admin/shared/user-real-quota-info.component.ts
+++ b/client/src/app/+admin/shared/user-real-quota-info.component.ts
@@ -1,4 +1,4 @@
-import { Component, Input, OnInit } from '@angular/core'
+import { Component, OnInit, inject, input } from '@angular/core'
import { ServerService } from '@app/core'
import { HTMLServerConfig, VideoResolution } from '@peertube/peertube-models'
import { BytesPipe } from '../../shared/shared-main/common/bytes.pipe'
@@ -10,11 +10,11 @@ import { NgIf } from '@angular/common'
imports: [ NgIf, BytesPipe ]
})
export class UserRealQuotaInfoComponent implements OnInit {
- @Input() videoQuota: number | string
+ private server = inject(ServerService)
- private serverConfig: HTMLServerConfig
+ readonly videoQuota = input<number | string>(undefined)
- constructor (private server: ServerService) { }
+ private serverConfig: HTMLServerConfig
ngOnInit () {
this.serverConfig = this.server.getHTMLConfig()
@@ -41,6 +41,6 @@ export class UserRealQuotaInfoComponent implements OnInit {
}
getQuotaAsNumber () {
- return parseInt(this.videoQuota + '', 10)
+ return parseInt(this.videoQuota() + '', 10)
}
}
diff --git a/client/src/app/+admin/system/debug/debug.component.ts b/client/src/app/+admin/system/debug/debug.component.ts
index 750d1578f0..44d1c833e9 100644
--- a/client/src/app/+admin/system/debug/debug.component.ts
+++ b/client/src/app/+admin/system/debug/debug.component.ts
@@ -1,24 +1,18 @@
-import { Component, OnInit } from '@angular/core'
+import { Component, OnInit, inject } from '@angular/core'
import { Notifier } from '@app/core'
import { Debug } from '@peertube/peertube-models'
import { DebugService } from './debug.service'
-import { GlobalIconComponent } from '@app/shared/shared-icons/global-icon.component'
@Component({
templateUrl: './debug.component.html',
styleUrls: [ './debug.component.scss' ],
- imports: [
- GlobalIconComponent
- ]
+ imports: []
})
export class DebugComponent implements OnInit {
- debug: Debug
+ private debugService = inject(DebugService)
+ private notifier = inject(Notifier)
- constructor (
- private debugService: DebugService,
- private notifier: Notifier
- ) {
- }
+ debug: Debug
ngOnInit (): void {
this.load()
@@ -26,10 +20,10 @@ export class DebugComponent implements OnInit {
load () {
this.debugService.getDebug()
- .subscribe({
- next: debug => this.debug = debug,
+ .subscribe({
+ next: debug => this.debug = debug,
- error: err => this.notifier.error(err.message)
- })
+ error: err => this.notifier.error(err.message)
+ })
}
}
diff --git a/client/src/app/+admin/system/debug/debug.service.ts b/client/src/app/+admin/system/debug/debug.service.ts
index 24d3b2ab8e..5e67d10c99 100644
--- a/client/src/app/+admin/system/debug/debug.service.ts
+++ b/client/src/app/+admin/system/debug/debug.service.ts
@@ -1,24 +1,22 @@
import { Observable } from 'rxjs'
import { catchError } from 'rxjs/operators'
import { HttpClient } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { RestExtractor } from '@app/core'
import { Debug } from '@peertube/peertube-models'
import { environment } from '../../../../environments/environment'
@Injectable()
export class DebugService {
- private static BASE_DEBUG_URL = environment.apiUrl + '/api/v1/server/debug'
+ private authHttp = inject(HttpClient)
+ private restExtractor = inject(RestExtractor)
- constructor (
- private authHttp: HttpClient,
- private restExtractor: RestExtractor
- ) {}
+ private static BASE_DEBUG_URL = environment.apiUrl + '/api/v1/server/debug'
getDebug (): Observable<Debug> {
return this.authHttp.get<Debug>(DebugService.BASE_DEBUG_URL)
- .pipe(
- catchError(err => this.restExtractor.handleError(err))
- )
+ .pipe(
+ catchError(err => this.restExtractor.handleError(err))
+ )
}
}
diff --git a/client/src/app/+admin/system/jobs/job.service.ts b/client/src/app/+admin/system/jobs/job.service.ts
index 740adf742a..0c7486c625 100644
--- a/client/src/app/+admin/system/jobs/job.service.ts
+++ b/client/src/app/+admin/system/jobs/job.service.ts
@@ -2,7 +2,7 @@ import { SortMeta } from 'primeng/api'
import { Observable } from 'rxjs'
import { catchError, map } from 'rxjs/operators'
import { HttpClient, HttpParams } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { RestExtractor, RestPagination, RestService } from '@app/core'
import { Job, ResultList } from '@peertube/peertube-models'
import { environment } from '../../../../environments/environment'
@@ -11,13 +11,11 @@ import { JobTypeClient } from '../../../../types/job-type-client.type'
@Injectable()
export class JobService {
- private static BASE_JOB_URL = environment.apiUrl + '/api/v1/jobs'
+ private authHttp = inject(HttpClient)
+ private restService = inject(RestService)
+ private restExtractor = inject(RestExtractor)
- constructor (
- private authHttp: HttpClient,
- private restService: RestService,
- private restExtractor: RestExtractor
- ) {}
+ private static BASE_JOB_URL = environment.apiUrl + '/api/v1/jobs'
listJobs (options: {
jobState?: JobStateClient
@@ -33,12 +31,12 @@ export class JobService {
if (jobType !== 'all') params = params.append('jobType', jobType)
return this.authHttp.get<ResultList<Job>>(JobService.BASE_JOB_URL + `/${jobState || ''}`, { params })
- .pipe(
- map(res => this.restExtractor.convertResultListDateToHuman(res, [ 'createdAt', 'processedOn', 'finishedOn' ], 'precise')),
- map(res => this.restExtractor.applyToResultListData(res, this.prettyPrintData.bind(this))),
- map(res => this.restExtractor.applyToResultListData(res, this.buildUniqId.bind(this))),
- catchError(err => this.restExtractor.handleError(err))
- )
+ .pipe(
+ map(res => this.restExtractor.convertResultListDateToHuman(res, [ 'createdAt', 'processedOn', 'finishedOn' ], 'precise')),
+ map(res => this.restExtractor.applyToResultListData(res, this.prettyPrintData.bind(this))),
+ map(res => this.restExtractor.applyToResultListData(res, this.buildUniqId.bind(this))),
+ catchError(err => this.restExtractor.handleError(err))
+ )
}
private prettyPrintData (obj: Job) {
diff --git a/client/src/app/+admin/system/jobs/jobs.component.ts b/client/src/app/+admin/system/jobs/jobs.component.ts
index 614a6622db..4ff7dd7ee2 100644
--- a/client/src/app/+admin/system/jobs/jobs.component.ts
+++ b/client/src/app/+admin/system/jobs/jobs.component.ts
@@ -1,9 +1,9 @@
-import { NgClass, NgFor, NgIf } from '@angular/common'
-import { Component, OnInit } from '@angular/core'
+import { NgClass, NgIf } from '@angular/common'
+import { Component, OnInit, inject } from '@angular/core'
import { FormsModule } from '@angular/forms'
import { Notifier, RestPagination, RestTable } from '@app/core'
import { SelectOptionsComponent } from '@app/shared/shared-forms/select/select-options.component'
-import { GlobalIconComponent } from '@app/shared/shared-icons/global-icon.component'
+
import { AutoColspanDirective } from '@app/shared/shared-main/common/auto-colspan.directive'
import { NgbTooltip } from '@ng-bootstrap/ng-bootstrap'
import { Job, JobState, JobType } from '@peertube/peertube-models'
@@ -23,7 +23,6 @@ import { JobService } from './job.service'
styleUrls: [ './jobs.component.scss' ],
imports: [
FormsModule,
- NgFor,
NgClass,
ButtonComponent,
TableModule,
@@ -31,12 +30,14 @@ import { JobService } from './job.service'
NgIf,
NgbTooltip,
TableExpanderIconComponent,
- GlobalIconComponent,
SelectOptionsComponent,
AutoColspanDirective
]
})
export class JobsComponent extends RestTable implements OnInit {
+ private notifier = inject(Notifier)
+ private jobsService = inject(JobService)
+
private static LS_STATE = 'jobs-list-state'
private static LS_TYPE = 'jobs-list-type'
@@ -87,13 +88,6 @@ export class JobsComponent extends RestTable implements OnInit {
sort: SortMeta = { field: 'createdAt', order: -1 }
pagination: RestPagination = { count: this.rowsPerPage, start: 0 }
- constructor (
- private notifier: Notifier,
- private jobsService: JobService
- ) {
- super()
- }
-
ngOnInit () {
this.loadJobStateAndType()
this.initialize()
diff --git a/client/src/app/+admin/system/logs/logs.component.ts b/client/src/app/+admin/system/logs/logs.component.ts
index a16e5978ca..7ed95610be 100644
--- a/client/src/app/+admin/system/logs/logs.component.ts
+++ b/client/src/app/+admin/system/logs/logs.component.ts
@@ -1,5 +1,5 @@
import { NgClass, NgFor, NgIf } from '@angular/common'
-import { Component, ElementRef, OnInit, ViewChild } from '@angular/core'
+import { Component, ElementRef, OnInit, inject, viewChild } from '@angular/core'
import { FormsModule } from '@angular/forms'
import { LocalStorageService, Notifier } from '@app/core'
import { SelectOptionsComponent } from '@app/shared/shared-forms/select/select-options.component'
@@ -29,10 +29,14 @@ import { LogsService } from './logs.service'
]
})
export class LogsComponent implements OnInit {
+ private logsService = inject(LogsService)
+ private notifier = inject(Notifier)
+ private localStorage = inject(LocalStorageService)
+
private static LS_LOG_TYPE_CHOICE_KEY = 'admin-logs-log-type-choice'
- @ViewChild('logsElement', { static: true }) logsElement: ElementRef<HTMLElement>
- @ViewChild('logsContent', { static: true }) logsContent: ElementRef<HTMLElement>
+ readonly logsElement = viewChild<ElementRef<HTMLElement>>('logsElement')
+ readonly logsContent = viewChild<ElementRef<HTMLElement>>('logsContent')
loading = false
@@ -48,12 +52,6 @@ export class LogsComponent implements OnInit {
logType: 'audit' | 'standard'
tagsOneOf: string[] = []
- constructor (
- private logsService: LogsService,
- private notifier: Notifier,
- private localStorage: LocalStorageService
- ) { }
-
ngOnInit (): void {
this.buildTimeChoices()
this.buildLevelChoices()
@@ -91,7 +89,7 @@ export class LogsComponent implements OnInit {
this.rawLogs = this.logs.map(l => `${l.level} ${l.localeDate} ${l.message} ${l.meta}`).join('\n')
setTimeout(() => {
- this.logsElement.nativeElement.scrollIntoView({ block: 'end', inline: 'nearest' })
+ this.logsElement().nativeElement.scrollIntoView({ block: 'end', inline: 'nearest' })
})
},
diff --git a/client/src/app/+admin/system/logs/logs.service.ts b/client/src/app/+admin/system/logs/logs.service.ts
index b157ae9df5..5347e40f3c 100644
--- a/client/src/app/+admin/system/logs/logs.service.ts
+++ b/client/src/app/+admin/system/logs/logs.service.ts
@@ -1,5 +1,5 @@
import { HttpClient, HttpParams } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { RestExtractor, RestService } from '@app/core'
import { ServerLogLevel } from '@peertube/peertube-models'
import { catchError, map } from 'rxjs/operators'
@@ -8,15 +8,13 @@ import { LogRow } from './log-row.model'
@Injectable()
export class LogsService {
+ private authHttp = inject(HttpClient)
+ private restService = inject(RestService)
+ private restExtractor = inject(RestExtractor)
+
private static BASE_LOG_URL = environment.apiUrl + '/api/v1/server/logs'
private static BASE_AUDIT_LOG_URL = environment.apiUrl + '/api/v1/server/audit-logs'
- constructor (
- private authHttp: HttpClient,
- private restService: RestService,
- private restExtractor: RestExtractor
- ) {}
-
getLogs (options: {
isAuditLog: boolean
startDate: string
@@ -38,9 +36,9 @@ export class LogsService {
: LogsService.BASE_LOG_URL
return this.authHttp.get<LogRow[]>(path, { params })
- .pipe(
- map(rows => rows.map(r => new LogRow(r))),
- catchError(err => this.restExtractor.handleError(err))
- )
+ .pipe(
+ map(rows => rows.map(r => new LogRow(r))),
+ catchError(err => this.restExtractor.handleError(err))
+ )
}
}
diff --git a/client/src/app/+admin/system/runners/runner-job-list/runner-job-list.component.ts b/client/src/app/+admin/system/runners/runner-job-list/runner-job-list.component.ts
index 5e8fa5b762..2680789a24 100644
--- a/client/src/app/+admin/system/runners/runner-job-list/runner-job-list.component.ts
+++ b/client/src/app/+admin/system/runners/runner-job-list/runner-job-list.component.ts
@@ -1,6 +1,6 @@
import { NgClass, NgIf } from '@angular/common'
-import { Component, OnInit } from '@angular/core'
-import { RouterLink } from '@angular/router'
+import { Component, OnInit, inject } from '@angular/core'
+
import { ConfirmService, Notifier, RestPagination, RestTable } from '@app/core'
import { formatICU } from '@app/helpers'
import { NgbTooltip } from '@ng-bootstrap/ng-bootstrap'
@@ -8,7 +8,7 @@ import { RunnerJob, RunnerJobState } from '@peertube/peertube-models'
import { SharedModule, SortMeta } from 'primeng/api'
import { TableModule } from 'primeng/table'
import { AdvancedInputFilter, AdvancedInputFilterComponent } from '../../../../shared/shared-forms/advanced-input-filter.component'
-import { GlobalIconComponent } from '../../../../shared/shared-icons/global-icon.component'
+
import { AutoColspanDirective } from '../../../../shared/shared-main/common/auto-colspan.directive'
import { ActionDropdownComponent, DropdownAction } from '../../../../shared/shared-main/buttons/action-dropdown.component'
import { ButtonComponent } from '../../../../shared/shared-main/buttons/button.component'
@@ -19,8 +19,6 @@ import { RunnerJobFormatted, RunnerService } from '../runner.service'
selector: 'my-runner-job-list',
templateUrl: './runner-job-list.component.html',
imports: [
- GlobalIconComponent,
- RouterLink,
TableModule,
SharedModule,
NgbTooltip,
@@ -33,7 +31,11 @@ import { RunnerJobFormatted, RunnerService } from '../runner.service'
AutoColspanDirective
]
})
-export class RunnerJobListComponent extends RestTable <RunnerJob> implements OnInit {
+export class RunnerJobListComponent extends RestTable<RunnerJob> implements OnInit {
+ private runnerService = inject(RunnerService)
+ private notifier = inject(Notifier)
+ private confirmService = inject(ConfirmService)
+
runnerJobs: RunnerJobFormatted[] = []
totalRecords = 0
@@ -67,14 +69,6 @@ export class RunnerJobListComponent extends RestTable <RunnerJob> implements OnI
}
]
- constructor (
- private runnerService: RunnerService,
- private notifier: Notifier,
- private confirmService: ConfirmService
- ) {
- super()
- }
-
ngOnInit () {
this.actions = [
[
@@ -126,20 +120,20 @@ export class RunnerJobListComponent extends RestTable <RunnerJob> implements OnI
if (res === false) return
this.runnerService.cancelJobs(jobs)
- .subscribe({
- next: () => {
- this.reloadData()
-
- this.notifier.success(
- formatICU(
- $localize`{count, plural, =1 {Job cancelled} other {{count} jobs cancelled}}`,
- { count: jobs.length }
- )
+ .subscribe({
+ next: () => {
+ this.reloadData()
+
+ this.notifier.success(
+ formatICU(
+ $localize`{count, plural, =1 {Job cancelled} other {{count} jobs cancelled}}`,
+ { count: jobs.length }
)
- },
+ )
+ },
- error: err => this.notifier.error(err.message)
- })
+ error: err => this.notifier.error(err.message)
+ })
}
async removeJobs (jobs: RunnerJob[]) {
@@ -153,20 +147,20 @@ export class RunnerJobListComponent extends RestTable <RunnerJob> implements OnI
if (res === false) return
this.runnerService.removeJobs(jobs)
- .subscribe({
- next: () => {
- this.reloadData()
-
- this.notifier.success(
- formatICU(
- $localize`{count, plural, =1 {Job removed} other {{count} jobs removed}}`,
- { count: jobs.length }
- )
+ .subscribe({
+ next: () => {
+ this.reloadData()
+
+ this.notifier.success(
+ formatICU(
+ $localize`{count, plural, =1 {Job removed} other {{count} jobs removed}}`,
+ { count: jobs.length }
)
- },
+ )
+ },
- error: err => this.notifier.error(err.message)
- })
+ error: err => this.notifier.error(err.message)
+ })
}
getStateBadgeColor (job: RunnerJob) {
diff --git a/client/src/app/+admin/system/runners/runner-list/runner-list.component.ts b/client/src/app/+admin/system/runners/runner-list/runner-list.component.ts
index bd05f47bdf..03a36c8143 100644
--- a/client/src/app/+admin/system/runners/runner-list/runner-list.component.ts
+++ b/client/src/app/+admin/system/runners/runner-list/runner-list.component.ts
@@ -1,4 +1,4 @@
-import { Component, OnInit } from '@angular/core'
+import { Component, OnInit, inject } from '@angular/core'
import { ConfirmService, Notifier, RestPagination, RestTable } from '@app/core'
import { PTDatePipe } from '@app/shared/shared-main/common/date.pipe'
import { NgbTooltip } from '@ng-bootstrap/ng-bootstrap'
@@ -21,7 +21,11 @@ import { RunnerService } from '../runner.service'
PTDatePipe
]
})
-export class RunnerListComponent extends RestTable <Runner> implements OnInit {
+export class RunnerListComponent extends RestTable<Runner> implements OnInit {
+ private runnerService = inject(RunnerService)
+ private notifier = inject(Notifier)
+ private confirmService = inject(ConfirmService)
+
runners: Runner[] = []
totalRecords = 0
@@ -30,14 +34,6 @@ export class RunnerListComponent extends RestTable <Runner> implements OnInit {
actions: DropdownAction<Runner>[][] = []
- constructor (
- private runnerService: RunnerService,
- private notifier: Notifier,
- private confirmService: ConfirmService
- ) {
- super()
- }
-
ngOnInit () {
this.actions = [
[
@@ -64,14 +60,14 @@ export class RunnerListComponent extends RestTable <Runner> implements OnInit {
if (res === false) return
this.runnerService.deleteRunner(runner)
- .subscribe({
- next: () => {
- this.reloadData()
- this.notifier.success($localize`Runner removed.`)
- },
+ .subscribe({
+ next: () => {
+ this.reloadData()
+ this.notifier.success($localize`Runner removed.`)
+ },
- error: err => this.notifier.error(err.message)
- })
+ error: err => this.notifier.error(err.message)
+ })
}
protected reloadDataInternal () {
diff --git a/client/src/app/+admin/system/runners/runner-registration-token-list/runner-registration-token-list.component.ts b/client/src/app/+admin/system/runners/runner-registration-token-list/runner-registration-token-list.component.ts
index 1b9f2f9a6a..c29bf62c70 100644
--- a/client/src/app/+admin/system/runners/runner-registration-token-list/runner-registration-token-list.component.ts
+++ b/client/src/app/+admin/system/runners/runner-registration-token-list/runner-registration-token-list.component.ts
@@ -1,12 +1,12 @@
-import { Component, OnInit } from '@angular/core'
-import { RouterLink } from '@angular/router'
+import { Component, OnInit, inject } from '@angular/core'
+
import { ConfirmService, Notifier, RestPagination, RestTable } from '@app/core'
import { PTDatePipe } from '@app/shared/shared-main/common/date.pipe'
import { NgbTooltip } from '@ng-bootstrap/ng-bootstrap'
import { RunnerRegistrationToken } from '@peertube/peertube-models'
import { SharedModule, SortMeta } from 'primeng/api'
import { TableModule } from 'primeng/table'
-import { GlobalIconComponent } from '../../../../shared/shared-icons/global-icon.component'
+
import { ActionDropdownComponent, DropdownAction } from '../../../../shared/shared-main/buttons/action-dropdown.component'
import { ButtonComponent } from '../../../../shared/shared-main/buttons/button.component'
import { CopyButtonComponent } from '../../../../shared/shared-main/buttons/copy-button.component'
@@ -18,8 +18,6 @@ import { RunnerService } from '../runner.service'
styleUrls: [ './runner-registration-token-list.component.scss' ],
templateUrl: './runner-registration-token-list.component.html',
imports: [
- GlobalIconComponent,
- RouterLink,
TableModule,
SharedModule,
NgbTooltip,
@@ -30,7 +28,11 @@ import { RunnerService } from '../runner.service'
PTDatePipe
]
})
-export class RunnerRegistrationTokenListComponent extends RestTable <RunnerRegistrationToken> implements OnInit {
+export class RunnerRegistrationTokenListComponent extends RestTable<RunnerRegistrationToken> implements OnInit {
+ private runnerService = inject(RunnerService)
+ private notifier = inject(Notifier)
+ private confirmService = inject(ConfirmService)
+
registrationTokens: RunnerRegistrationToken[] = []
totalRecords = 0
@@ -39,14 +41,6 @@ export class RunnerRegistrationTokenListComponent extends RestTable <RunnerRegis
actions: DropdownAction<RunnerRegistrationToken>[][] = []
- constructor (
- private runnerService: RunnerService,
- private notifier: Notifier,
- private confirmService: ConfirmService
- ) {
- super()
- }
-
ngOnInit () {
this.actions = [
[
@@ -85,14 +79,14 @@ export class RunnerRegistrationTokenListComponent extends RestTable <RunnerRegis
if (res === false) return
this.runnerService.removeToken(token)
- .subscribe({
- next: () => {
- this.reloadData()
- this.notifier.success($localize`Registration token removed.`)
- },
-
- error: err => this.notifier.error(err.message)
- })
+ .subscribe({
+ next: () => {
+ this.reloadData()
+ this.notifier.success($localize`Registration token removed.`)
+ },
+
+ error: err => this.notifier.error(err.message)
+ })
}
protected reloadDataInternal () {
diff --git a/client/src/app/+admin/system/runners/runner.service.ts b/client/src/app/+admin/system/runners/runner.service.ts
index cc2308047a..772c51890d 100644
--- a/client/src/app/+admin/system/runners/runner.service.ts
+++ b/client/src/app/+admin/system/runners/runner.service.ts
@@ -1,7 +1,7 @@
import { SortMeta } from 'primeng/api'
import { catchError, concatMap, forkJoin, from, map, toArray } from 'rxjs'
import { HttpClient, HttpParams } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { RestExtractor, RestPagination, RestService, ServerService } from '@app/core'
import { arrayify, peertubeTranslate } from '@peertube/peertube-core-utils'
import { ResultList, Runner, RunnerJob, RunnerJobAdmin, RunnerJobState, RunnerRegistrationToken } from '@peertube/peertube-models'
@@ -14,14 +14,12 @@ export type RunnerJobFormatted = RunnerJob & {
@Injectable()
export class RunnerService {
- private static BASE_RUNNER_URL = environment.apiUrl + '/api/v1/runners'
+ private authHttp = inject(HttpClient)
+ private server = inject(ServerService)
+ private restService = inject(RestService)
+ private restExtractor = inject(RestExtractor)
- constructor (
- private authHttp: HttpClient,
- private server: ServerService,
- private restService: RestService,
- private restExtractor: RestExtractor
- ) {}
+ private static BASE_RUNNER_URL = environment.apiUrl + '/api/v1/runners'
listRegistrationTokens (options: {
pagination: RestPagination
@@ -33,7 +31,7 @@ export class RunnerService {
params = this.restService.addRestGetParams(params, pagination, sort)
return this.authHttp.get<ResultList<RunnerRegistrationToken>>(RunnerService.BASE_RUNNER_URL + '/registration-tokens', { params })
- .pipe(catchError(res => this.restExtractor.handleError(res)))
+ .pipe(catchError(res => this.restExtractor.handleError(res)))
}
generateToken () {
@@ -147,7 +145,7 @@ export class RunnerService {
params = this.restService.addRestGetParams(params, pagination, sort)
return this.authHttp.get<ResultList<Runner>>(RunnerService.BASE_RUNNER_URL + '/', { params })
- .pipe(catchError(res => this.restExtractor.handleError(res)))
+ .pipe(catchError(res => this.restExtractor.handleError(res)))
}
deleteRunner (runner: Runner) {
diff --git a/client/src/app/+error-page/error-page.component.ts b/client/src/app/+error-page/error-page.component.ts
index 8b97fce658..b44a6c4153 100644
--- a/client/src/app/+error-page/error-page.component.ts
+++ b/client/src/app/+error-page/error-page.component.ts
@@ -1,5 +1,4 @@
-import { NgIf } from '@angular/common'
-import { Component, OnInit } from '@angular/core'
+import { Component, OnInit, inject } from '@angular/core'
import { Title } from '@angular/platform-browser'
import { Router } from '@angular/router'
import { LoginLinkComponent } from '@app/shared/shared-main/users/login-link.component'
@@ -9,16 +8,16 @@ import { HttpStatusCode, HttpStatusCodeType } from '@peertube/peertube-models'
selector: 'my-error-page',
templateUrl: './error-page.component.html',
styleUrls: [ './error-page.component.scss' ],
- imports: [ NgIf, LoginLinkComponent ]
+ imports: [ LoginLinkComponent ]
})
export class ErrorPageComponent implements OnInit {
+ private titleService = inject(Title)
+ private router = inject(Router)
+
status: HttpStatusCodeType = HttpStatusCode.NOT_FOUND_404
type: 'video' | 'other' = 'other'
- public constructor (
- private titleService: Title,
- private router: Router
- ) {
+ public constructor () {
const state = this.router.getCurrentNavigation()?.extras.state
this.type = state?.type || this.type
this.status = state?.obj.status || this.status
diff --git a/client/src/app/+home/home.component.ts b/client/src/app/+home/home.component.ts
index 30418b0a2b..0d320cf84f 100644
--- a/client/src/app/+home/home.component.ts
+++ b/client/src/app/+home/home.component.ts
@@ -1,4 +1,4 @@
-import { Component, ElementRef, OnInit, ViewChild } from '@angular/core'
+import { Component, ElementRef, OnInit, inject, viewChild } from '@angular/core'
import { CustomPageService } from '@app/shared/shared-main/custom-page/custom-page.service'
import { CustomMarkupContainerComponent } from '../shared/shared-custom-markup/custom-markup-container.component'
@@ -6,15 +6,12 @@ import { CustomMarkupContainerComponent } from '../shared/shared-custom-markup/c
templateUrl: './home.component.html',
imports: [ CustomMarkupContainerComponent ]
})
-
export class HomeComponent implements OnInit {
- @ViewChild('contentWrapper') contentWrapper: ElementRef<HTMLInputElement>
+ private customPageService = inject(CustomPageService)
- homepageContent: string
+ readonly contentWrapper = viewChild<ElementRef<HTMLInputElement>>('contentWrapper')
- constructor (
- private customPageService: CustomPageService
- ) { }
+ homepageContent: string
ngOnInit () {
this.customPageService.getInstanceHomepage()
diff --git a/client/src/app/+login/login.component.ts b/client/src/app/+login/login.component.ts
index 24e575928d..9e8cafb7da 100644
--- a/client/src/app/+login/login.component.ts
+++ b/client/src/app/+login/login.component.ts
@@ -1,5 +1,5 @@
-import { NgClass, NgFor, NgIf, NgTemplateOutlet } from '@angular/common'
-import { AfterViewInit, Component, ElementRef, OnInit, ViewChild } from '@angular/core'
+import { NgClass, NgFor, NgIf } from '@angular/common'
+import { AfterViewInit, Component, ElementRef, OnInit, inject, viewChild } from '@angular/core'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { ActivatedRoute, Router, RouterLink } from '@angular/router'
import { AuthService, Notifier, RedirectService, SessionStorageService, UserService } from '@app/core'
@@ -32,7 +32,6 @@ import { PluginSelectorDirective } from '../shared/shared-main/plugins/plugin-se
ReactiveFormsModule,
AutofocusDirective,
NgClass,
- NgTemplateOutlet,
InputTextComponent,
NgFor,
InstanceBannerComponent,
@@ -41,13 +40,23 @@ import { PluginSelectorDirective } from '../shared/shared-main/plugins/plugin-se
AlertComponent
]
})
-
export class LoginComponent extends FormReactive implements OnInit, AfterViewInit {
+ protected formReactiveService = inject(FormReactiveService)
+ private route = inject(ActivatedRoute)
+ private modalService = inject(NgbModal)
+ private authService = inject(AuthService)
+ private userService = inject(UserService)
+ private redirectService = inject(RedirectService)
+ private notifier = inject(Notifier)
+ private hooks = inject(HooksService)
+ private storage = inject(SessionStorageService)
+ private router = inject(Router)
+
private static SESSION_STORAGE_REDIRECT_URL_KEY = 'login-previous-url'
- @ViewChild('forgotPasswordModal', { static: true }) forgotPasswordModal: ElementRef
- @ViewChild('otpTokenInput') otpTokenInput: InputTextComponent
- @ViewChild('instanceAboutAccordion') instanceAboutAccordion: InstanceAboutAccordionComponent
+ readonly forgotPasswordModal = viewChild<ElementRef>('forgotPasswordModal')
+ readonly otpTokenInput = viewChild<InputTextComponent>('otpTokenInput')
+ readonly instanceAboutAccordion = viewChild<InstanceAboutAccordionComponent>('instanceAboutAccordion')
accordion: NgbAccordionDirective
error: string = null
@@ -72,21 +81,6 @@ export class LoginComponent extends FormReactive implements OnInit, AfterViewIni
private openedForgotPasswordModal: NgbModalRef
private serverConfig: ServerConfig
- constructor (
- protected formReactiveService: FormReactiveService,
- private route: ActivatedRoute,
- private modalService: NgbModal,
- private authService: AuthService,
- private userService: UserService,
- private redirectService: RedirectService,
- private notifier: Notifier,
- private hooks: HooksService,
- private storage: SessionStorageService,
- private router: Router
- ) {
- super()
- }
-
get signupAllowed () {
return this.serverConfig.signup.allowed === true
}
@@ -98,8 +92,9 @@ export class LoginComponent extends FormReactive implements OnInit, AfterViewIni
onTermsClick (event: Event, instanceInformation: HTMLElement) {
event.preventDefault()
- if (this.instanceAboutAccordion) {
- this.instanceAboutAccordion.expandTerms()
+ const instanceAboutAccordion = this.instanceAboutAccordion()
+ if (instanceAboutAccordion) {
+ instanceAboutAccordion.expandTerms()
instanceInformation.scrollIntoView({ behavior: 'smooth' })
}
}
@@ -191,7 +186,7 @@ The link will expire within 1 hour.`
}
openForgotPasswordModal () {
- this.openedForgotPasswordModal = this.modalService.open(this.forgotPasswordModal)
+ this.openedForgotPasswordModal = this.modalService.open(this.forgotPasswordModal())
}
hideForgotPasswordModal () {
@@ -199,7 +194,7 @@ The link will expire within 1 hour.`
}
onInstanceAboutAccordionInit (instanceAboutAccordion: InstanceAboutAccordionComponent) {
- this.accordion = instanceAboutAccordion.accordion
+ this.accordion = instanceAboutAccordion.accordion()
}
private loadExternalAuthToken (username: string, token: string) {
@@ -230,7 +225,7 @@ The link will expire within 1 hour.`
setTimeout(() => {
this.form.get('otp-token').setValidators(USER_OTP_TOKEN_VALIDATOR.VALIDATORS)
- this.otpTokenInput.focus()
+ this.otpTokenInput().focus()
})
return
diff --git a/client/src/app/+my-account/my-account-abuses/my-account-abuses-list.component.ts b/client/src/app/+my-account/my-account-abuses/my-account-abuses-list.component.ts
index d1ad3efba7..1ee807f818 100644
--- a/client/src/app/+my-account/my-account-abuses/my-account-abuses-list.component.ts
+++ b/client/src/app/+my-account/my-account-abuses/my-account-abuses-list.component.ts
@@ -1,13 +1,11 @@
import { Component } from '@angular/core'
import { AbuseListTableComponent } from '../../shared/shared-abuse-list/abuse-list-table.component'
-import { GlobalIconComponent } from '../../shared/shared-icons/global-icon.component'
@Component({
selector: 'my-account-abuses-list',
templateUrl: './my-account-abuses-list.component.html',
styleUrls: [],
- imports: [ GlobalIconComponent, AbuseListTableComponent ]
+ imports: [ AbuseListTableComponent ]
})
export class MyAccountAbusesListComponent {
-
}
diff --git a/client/src/app/+my-account/my-account-applications/my-account-applications.component.ts b/client/src/app/+my-account/my-account-applications/my-account-applications.component.ts
index b615e63964..29b613a556 100644
--- a/client/src/app/+my-account/my-account-applications/my-account-applications.component.ts
+++ b/client/src/app/+my-account/my-account-applications/my-account-applications.component.ts
@@ -1,4 +1,4 @@
-import { Component, OnInit } from '@angular/core'
+import { Component, OnInit, inject } from '@angular/core'
import { AuthService, ConfirmService, Notifier, ScopedTokensService } from '@app/core'
import { VideoService } from '@app/shared/shared-main/video/video.service'
import { FeedFormat, ScopedToken } from '@peertube/peertube-models'
@@ -12,19 +12,17 @@ import { InputTextComponent } from '../../shared/shared-forms/input-text.compone
imports: [ InputTextComponent ]
})
export class MyAccountApplicationsComponent implements OnInit {
+ private authService = inject(AuthService)
+ private scopedTokensService = inject(ScopedTokensService)
+ private videoService = inject(VideoService)
+ private notifier = inject(Notifier)
+ private confirmService = inject(ConfirmService)
+
feedUrl: string
feedToken: string
private baseURL = environment.originServerUrl || window.location.origin
- constructor (
- private authService: AuthService,
- private scopedTokensService: ScopedTokensService,
- private videoService: VideoService,
- private notifier: Notifier,
- private confirmService: ConfirmService
- ) {}
-
ngOnInit () {
this.feedUrl = this.baseURL
diff --git a/client/src/app/+my-account/my-account-import-export/my-account-export.component.ts b/client/src/app/+my-account/my-account-import-export/my-account-export.component.ts
index d76a6814d1..edca5c594b 100644
--- a/client/src/app/+my-account/my-account-import-export/my-account-export.component.ts
+++ b/client/src/app/+my-account/my-account-import-export/my-account-export.component.ts
@@ -1,5 +1,5 @@
import { NgFor, NgIf } from '@angular/common'
-import { Component, Input, OnInit, ViewChild } from '@angular/core'
+import { Component, OnInit, inject, input, viewChild } from '@angular/core'
import { FormsModule } from '@angular/forms'
import { AuthService, ServerService } from '@app/core'
import { AlertComponent } from '@app/shared/shared-main/common/alert.component'
@@ -19,9 +19,14 @@ import { UserImportExportService } from './user-import-export.service'
imports: [ NgIf, NgFor, GlobalIconComponent, PeertubeCheckboxComponent, FormsModule, PTDatePipe, BytesPipe, AlertComponent ]
})
export class MyAccountExportComponent implements OnInit {
- @ViewChild('exportModal', { static: true }) exportModal: NgbModal
+ private authService = inject(AuthService)
+ private server = inject(ServerService)
+ private userImportExportService = inject(UserImportExportService)
+ private modalService = inject(NgbModal)
- @Input() videoQuotaUsed: number
+ readonly exportModal = viewChild<NgbModal>('exportModal')
+
+ readonly videoQuotaUsed = input<number>(undefined)
userExports: UserExport[] = []
@@ -33,15 +38,8 @@ export class MyAccountExportComponent implements OnInit {
private exportModalOpened: NgbModalRef
private requestingArchive = false
- constructor (
- private authService: AuthService,
- private server: ServerService,
- private userImportExportService: UserImportExportService,
- private modalService: NgbModal
- ) {}
-
ngOnInit () {
- this.archiveWeightEstimation = this.videoQuotaUsed
+ this.archiveWeightEstimation = this.videoQuotaUsed()
this.reloadUserExports()
}
@@ -70,7 +68,7 @@ export class MyAccountExportComponent implements OnInit {
this.exportWithVideosFiles = false
this.errorInModal = undefined
- this.exportModalOpened = this.modalService.open(this.exportModal, { centered: true })
+ this.exportModalOpened = this.modalService.open(this.exportModal(), { centered: true })
}
requestNewArchive () {
@@ -105,8 +103,9 @@ export class MyAccountExportComponent implements OnInit {
const error = err.body as PeerTubeProblemDocument
if (error.code === ServerErrorCode.MAX_USER_VIDEO_QUOTA_EXCEEDED_FOR_USER_EXPORT) {
- // eslint-disable-next-line max-len
- this.errorInModal = $localize`Video files cannot be included in the export because you have exceeded the maximum video quota allowed by your administrator to export this archive.`
+ this.errorInModal =
+ // eslint-disable-next-line max-len
+ $localize`Video files cannot be included in the export because you have exceeded the maximum video quota allowed by your administrator to export this archive.`
return
}
diff --git a/client/src/app/+my-account/my-account-import-export/my-account-import-export.component.ts b/client/src/app/+my-account/my-account-import-export/my-account-import-export.component.ts
index adcc9b4f44..7189859562 100644
--- a/client/src/app/+my-account/my-account-import-export/my-account-import-export.component.ts
+++ b/client/src/app/+my-account/my-account-import-export/my-account-import-export.component.ts
@@ -1,22 +1,20 @@
-import { Component, OnInit, ViewChild } from '@angular/core'
+import { Component, OnInit, inject, viewChild } from '@angular/core'
import { CanComponentDeactivate, UserService } from '@app/core'
-import { GlobalIconComponent } from '../../shared/shared-icons/global-icon.component'
+
import { MyAccountExportComponent } from './my-account-export.component'
import { MyAccountImportComponent } from './my-account-import.component'
@Component({
selector: 'my-account-import-export',
templateUrl: './my-account-import-export.component.html',
- imports: [ GlobalIconComponent, MyAccountImportComponent, MyAccountExportComponent ]
+ imports: [ MyAccountImportComponent, MyAccountExportComponent ]
})
export class MyAccountImportExportComponent implements OnInit, CanComponentDeactivate {
- @ViewChild('accountImport') accountImport: MyAccountImportComponent
+ private userService = inject(UserService)
- videoQuotaUsed: number
+ readonly accountImport = viewChild<MyAccountImportComponent>('accountImport')
- constructor (
- private userService: UserService
- ) {}
+ videoQuotaUsed: number
ngOnInit () {
this.userService.getMyVideoQuotaUsed()
@@ -24,6 +22,6 @@ export class MyAccountImportExportComponent implements OnInit, CanComponentDeact
}
canDeactivate () {
- return this.accountImport?.canDeactivate() || { canDeactivate: true }
+ return this.accountImport()?.canDeactivate() || { canDeactivate: true }
}
}
diff --git a/client/src/app/+my-account/my-account-import-export/my-account-import.component.ts b/client/src/app/+my-account/my-account-import-export/my-account-import.component.ts
index e7d8d30440..5c32936798 100644
--- a/client/src/app/+my-account/my-account-import-export/my-account-import.component.ts
+++ b/client/src/app/+my-account/my-account-import-export/my-account-import.component.ts
@@ -1,6 +1,6 @@
import { NgIf } from '@angular/common'
import { HttpErrorResponse } from '@angular/common/http'
-import { Component, Input, OnDestroy, OnInit } from '@angular/core'
+import { Component, OnDestroy, OnInit, inject, input } from '@angular/core'
import { AuthService, CanComponentDeactivate, Notifier, ServerService } from '@app/core'
import { buildHTTPErrorResponse, genericUploadErrorHandler, getUploadXRetryConfig } from '@app/helpers'
import { AlertComponent } from '@app/shared/shared-main/common/alert.component'
@@ -20,7 +20,13 @@ import { UserImportExportService } from './user-import-export.service'
imports: [ NgIf, UploadProgressComponent, NgbTooltip, PTDatePipe, AlertComponent ]
})
export class MyAccountImportComponent implements OnInit, OnDestroy, CanComponentDeactivate {
- @Input() videoQuotaUsed: number
+ private authService = inject(AuthService)
+ private server = inject(ServerService)
+ private userImportExportService = inject(UserImportExportService)
+ private resumableUploadService = inject(UploadxService)
+ private notifier = inject(Notifier)
+
+ readonly videoQuotaUsed = input<number>(undefined)
uploadingArchive = false
archiveUploadFinished = false
@@ -35,14 +41,6 @@ export class MyAccountImportComponent implements OnInit, OnDestroy, CanComponent
private uploadServiceSubscription: Subscription
private alreadyRefreshedToken = false
- constructor (
- private authService: AuthService,
- private server: ServerService,
- private userImportExportService: UserImportExportService,
- private resumableUploadService: UploadxService,
- private notifier: Notifier
- ) {}
-
ngOnInit () {
this.userImportExportService.getLatestImport({ userId: this.authService.getUser().id })
.subscribe(res => this.latestImport = res)
@@ -113,10 +111,10 @@ export class MyAccountImportComponent implements OnInit, OnDestroy, CanComponent
const user = this.authService.getUser()
- if (user.videoQuota !== -1 && this.videoQuotaUsed + file.size > user.videoQuota) {
+ if (user.videoQuota !== -1 && this.videoQuotaUsed() + file.size > user.videoQuota) {
const bytePipes = new BytesPipe()
const fileSizeBytes = bytePipes.transform(file.size, 0)
- const videoQuotaUsedBytes = bytePipes.transform(this.videoQuotaUsed, 0)
+ const videoQuotaUsedBytes = bytePipes.transform(this.videoQuotaUsed(), 0)
const videoQuotaBytes = bytePipes.transform(user.videoQuota, 0)
this.notifier.error(
diff --git a/client/src/app/+my-account/my-account-import-export/user-import-export.service.ts b/client/src/app/+my-account/my-account-import-export/user-import-export.service.ts
index e20ba2a4ef..77e5f3367e 100644
--- a/client/src/app/+my-account/my-account-import-export/user-import-export.service.ts
+++ b/client/src/app/+my-account/my-account-import-export/user-import-export.service.ts
@@ -1,6 +1,6 @@
import { catchError, map } from 'rxjs/operators'
import { HttpClient } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { RestExtractor, ServerService } from '@app/core'
import { environment } from 'src/environments/environment'
import { HttpStatusCode, ResultList, UserExport, UserImport } from '@peertube/peertube-models'
@@ -9,15 +9,13 @@ import { peertubeTranslate } from '@peertube/peertube-core-utils'
@Injectable()
export class UserImportExportService {
+ private authHttp = inject(HttpClient)
+ private restExtractor = inject(RestExtractor)
+ private server = inject(ServerService)
+
static BASE_USER_EXPORTS_URL = environment.apiUrl + '/api/v1/users/'
static BASE_USER_IMPORTS_URL = environment.apiUrl + '/api/v1/users/'
- constructor (
- private authHttp: HttpClient,
- private restExtractor: RestExtractor,
- private server: ServerService
- ) { }
-
// ---------------------------------------------------------------------------
listUserExports (options: {
diff --git a/client/src/app/+my-account/my-account-notifications/my-account-notifications.component.ts b/client/src/app/+my-account/my-account-notifications/my-account-notifications.component.ts
index 7f7a17c8cc..8059fe766c 100644
--- a/client/src/app/+my-account/my-account-notifications/my-account-notifications.component.ts
+++ b/client/src/app/+my-account/my-account-notifications/my-account-notifications.component.ts
@@ -1,4 +1,4 @@
-import { Component, ViewChild } from '@angular/core'
+import { Component, viewChild } from '@angular/core'
import { UserNotificationsComponent } from '@app/shared/standalone-notifications/user-notifications.component'
import { NgIf } from '@angular/common'
import { FormsModule } from '@angular/forms'
@@ -13,7 +13,7 @@ type NotificationSortType = 'createdAt' | 'read'
imports: [ RouterLink, GlobalIconComponent, FormsModule, NgIf, UserNotificationsComponent ]
})
export class MyAccountNotificationsComponent {
- @ViewChild('userNotification', { static: true }) userNotification: UserNotificationsComponent
+ readonly userNotification = viewChild<UserNotificationsComponent>('userNotification')
_notificationSortType: NotificationSortType = 'createdAt'
@@ -28,14 +28,14 @@ export class MyAccountNotificationsComponent {
}
markAllAsRead () {
- this.userNotification.markAllAsRead()
+ this.userNotification().markAllAsRead()
}
hasUnreadNotifications () {
- return this.userNotification.notifications.filter(n => n.read === false).length !== 0
+ return this.userNotification().notifications.filter(n => n.read === false).length !== 0
}
onChangeSortColumn () {
- this.userNotification.changeSortColumn(this.notificationSortType)
+ this.userNotification().changeSortColumn(this.notificationSortType)
}
}
diff --git a/client/src/app/+my-account/my-account-settings/my-account-change-email/my-account-change-email.component.ts b/client/src/app/+my-account/my-account-settings/my-account-change-email/my-account-change-email.component.ts
index 9d24e2f3c2..956c910c2a 100644
--- a/client/src/app/+my-account/my-account-settings/my-account-change-email/my-account-change-email.component.ts
+++ b/client/src/app/+my-account/my-account-settings/my-account-change-email/my-account-change-email.component.ts
@@ -1,5 +1,5 @@
import { NgClass, NgIf } from '@angular/common'
-import { Component, OnInit } from '@angular/core'
+import { Component, OnInit, inject } from '@angular/core'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { AuthService, ServerService, UserService } from '@app/core'
import { USER_EMAIL_VALIDATOR, USER_PASSWORD_VALIDATOR } from '@app/shared/form-validators/user-validators'
@@ -18,19 +18,15 @@ import { InputTextComponent } from '../../../shared/shared-forms/input-text.comp
imports: [ NgIf, FormsModule, ReactiveFormsModule, NgClass, InputTextComponent, AlertComponent ]
})
export class MyAccountChangeEmailComponent extends FormReactive implements OnInit {
+ protected formReactiveService = inject(FormReactiveService)
+ private authService = inject(AuthService)
+ private userService = inject(UserService)
+ private serverService = inject(ServerService)
+
error: string
success: string
user: User
- constructor (
- protected formReactiveService: FormReactiveService,
- private authService: AuthService,
- private userService: UserService,
- private serverService: ServerService
- ) {
- super()
- }
-
ngOnInit () {
this.buildForm({
'new-email': USER_EMAIL_VALIDATOR,
diff --git a/client/src/app/+my-account/my-account-settings/my-account-change-password/my-account-change-password.component.ts b/client/src/app/+my-account/my-account-settings/my-account-change-password/my-account-change-password.component.ts
index 00bdf01a20..69f0928ec1 100644
--- a/client/src/app/+my-account/my-account-settings/my-account-change-password/my-account-change-password.component.ts
+++ b/client/src/app/+my-account/my-account-settings/my-account-change-password/my-account-change-password.component.ts
@@ -1,5 +1,5 @@
import { NgIf } from '@angular/common'
-import { Component, OnInit } from '@angular/core'
+import { Component, OnInit, inject } from '@angular/core'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { AuthService, Notifier, UserService } from '@app/core'
import {
@@ -21,18 +21,14 @@ import { InputTextComponent } from '../../../shared/shared-forms/input-text.comp
imports: [ NgIf, FormsModule, ReactiveFormsModule, InputTextComponent, AlertComponent ]
})
export class MyAccountChangePasswordComponent extends FormReactive implements OnInit {
+ protected formReactiveService = inject(FormReactiveService)
+ private notifier = inject(Notifier)
+ private authService = inject(AuthService)
+ private userService = inject(UserService)
+
error: string
user: User
- constructor (
- protected formReactiveService: FormReactiveService,
- private notifier: Notifier,
- private authService: AuthService,
- private userService: UserService
- ) {
- super()
- }
-
ngOnInit () {
this.buildForm({
'current-password': USER_EXISTING_PASSWORD_VALIDATOR,
@@ -45,8 +41,8 @@ export class MyAccountChangePasswordComponent extends FormReactive implements On
const confirmPasswordControl = this.form.get('new-confirmed-password')
confirmPasswordControl.valueChanges
- .pipe(filter(v => v !== this.form.value['new-password']))
- .subscribe(() => confirmPasswordControl.setErrors({ matchPassword: true }))
+ .pipe(filter(v => v !== this.form.value['new-password']))
+ .subscribe(() => confirmPasswordControl.setErrors({ matchPassword: true }))
}
changePassword () {
diff --git a/client/src/app/+my-account/my-account-settings/my-account-danger-zone/my-account-danger-zone.component.ts b/client/src/app/+my-account/my-account-settings/my-account-danger-zone/my-account-danger-zone.component.ts
index 9541495eaf..444f9a0671 100644
--- a/client/src/app/+my-account/my-account-settings/my-account-danger-zone/my-account-danger-zone.component.ts
+++ b/client/src/app/+my-account/my-account-settings/my-account-danger-zone/my-account-danger-zone.component.ts
@@ -1,4 +1,4 @@
-import { Component, Input } from '@angular/core'
+import { Component, inject, input } from '@angular/core'
import { AuthService, ConfirmService, Notifier, RedirectService, User, UserService } from '@app/core'
@Component({
@@ -7,27 +7,24 @@ import { AuthService, ConfirmService, Notifier, RedirectService, User, UserServi
standalone: true
})
export class MyAccountDangerZoneComponent {
- @Input() user: User
+ private authService = inject(AuthService)
+ private notifier = inject(Notifier)
+ private userService = inject(UserService)
+ private confirmService = inject(ConfirmService)
+ private redirectService = inject(RedirectService)
- constructor (
- private authService: AuthService,
- private notifier: Notifier,
- private userService: UserService,
- private confirmService: ConfirmService,
- private redirectService: RedirectService
- ) { }
+ readonly user = input<User>(undefined)
async deleteMe () {
const res = await this.confirmService.confirmWithExpectedInput(
$localize`Are you sure you want to delete your account?` +
'<br /><br />' +
// eslint-disable-next-line max-len
- $localize`This will delete all your data, including channels, videos, comments and you won't be able to create another user on this instance with "${this.user.username}" username.` +
+ $localize`This will delete all your data, including channels, videos, comments and you won't be able to create another user on this instance with "${this.user().username}" username.` +
'<br /><br />' +
$localize`Content cached by other servers and other third-parties might make longer to be deleted.`,
-
$localize`Type your username to confirm`,
- this.user.username,
+ this.user().username,
$localize`Delete your account`,
$localize`Delete my account`
)
diff --git a/client/src/app/+my-account/my-account-settings/my-account-email-preferences/my-account-email-preferences.component.html b/client/src/app/+my-account/my-account-settings/my-account-email-preferences/my-account-email-preferences.component.html
index 33f941abc9..5eeaa117e3 100644
--- a/client/src/app/+my-account/my-account-settings/my-account-email-preferences/my-account-email-preferences.component.html
+++ b/client/src/app/+my-account/my-account-settings/my-account-email-preferences/my-account-email-preferences.component.html
@@ -7,7 +7,7 @@
>
<ng-container ngProjectAs="description">
<p class="mb-0">
- @if (user.emailVerified) {
+ @if (user().emailVerified) {
<ng-container i18n>Necessary to claim podcast RSS feeds.</ng-container>
} @else {
<ng-container i18n>⚠️ Your email cannot be used in podcast RSS feeds because it has not yet been verified.</ng-container>
diff --git a/client/src/app/+my-account/my-account-settings/my-account-email-preferences/my-account-email-preferences.component.ts b/client/src/app/+my-account/my-account-settings/my-account-email-preferences/my-account-email-preferences.component.ts
index a4be0e4b0d..33fd7a40e8 100644
--- a/client/src/app/+my-account/my-account-settings/my-account-email-preferences/my-account-email-preferences.component.ts
+++ b/client/src/app/+my-account/my-account-settings/my-account-email-preferences/my-account-email-preferences.component.ts
@@ -1,4 +1,4 @@
-import { Component, Input, OnInit } from '@angular/core'
+import { Component, OnInit, inject, input } from '@angular/core'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { Notifier, UserService } from '@app/core'
import { FormReactive } from '@app/shared/shared-forms/form-reactive'
@@ -13,22 +13,18 @@ import { PeertubeCheckboxComponent } from '../../../shared/shared-forms/peertube
imports: [ FormsModule, ReactiveFormsModule, PeertubeCheckboxComponent ]
})
export class MyAccountEmailPreferencesComponent extends FormReactive implements OnInit {
- @Input() user: User
-
- constructor (
- protected formReactiveService: FormReactiveService,
- private userService: UserService,
- private notifier: Notifier
- ) {
- super()
- }
+ protected formReactiveService = inject(FormReactiveService)
+ private userService = inject(UserService)
+ private notifier = inject(Notifier)
+
+ readonly user = input<User>(undefined)
ngOnInit () {
this.buildForm({
'email-public': null
})
- this.form.patchValue({ 'email-public': this.user.emailPublic })
+ this.form.patchValue({ 'email-public': this.user().emailPublic })
}
updateEmailPublic () {
@@ -42,7 +38,7 @@ export class MyAccountEmailPreferencesComponent extends FormReactive implements
if (details.emailPublic) this.notifier.success($localize`Email is now public`)
else this.notifier.success($localize`Email is now private`)
- this.user.emailPublic = details.emailPublic
+ this.user().emailPublic = details.emailPublic
},
error: err => this.notifier.error(err.message)
diff --git a/client/src/app/+my-account/my-account-settings/my-account-notification-preferences/my-account-notification-preferences.component.ts b/client/src/app/+my-account/my-account-settings/my-account-notification-preferences/my-account-notification-preferences.component.ts
index cb15780f13..f9622ff66e 100644
--- a/client/src/app/+my-account/my-account-settings/my-account-notification-preferences/my-account-notification-preferences.component.ts
+++ b/client/src/app/+my-account/my-account-settings/my-account-notification-preferences/my-account-notification-preferences.component.ts
@@ -1,5 +1,5 @@
import { NgFor, NgIf } from '@angular/common'
-import { Component, Input, OnInit } from '@angular/core'
+import { Component, OnInit, inject, input } from '@angular/core'
import { FormsModule } from '@angular/forms'
import { Notifier, ServerService, User } from '@app/core'
import { UserNotificationService } from '@app/shared/shared-main/users/user-notification.service'
@@ -15,22 +15,22 @@ import { InputSwitchComponent } from '../../../shared/shared-forms/input-switch.
imports: [ NgIf, NgFor, InputSwitchComponent, FormsModule ]
})
export class MyAccountNotificationPreferencesComponent implements OnInit {
- @Input() user: User
+ private userNotificationService = inject(UserNotificationService)
+ private serverService = inject(ServerService)
+ private notifier = inject(Notifier)
+
+ readonly user = input<User>(undefined)
notificationSettingGroups: { label: string, keys: (keyof UserNotificationSetting)[] }[] = []
- emailNotifications: { [ id in keyof UserNotificationSetting ]?: boolean } = {}
- webNotifications: { [ id in keyof UserNotificationSetting ]?: boolean } = {}
- labelNotifications: { [ id in keyof UserNotificationSetting ]?: string } = {}
- rightNotifications: { [ id in keyof Partial<UserNotificationSetting> ]?: UserRightType } = {}
+ emailNotifications: { [id in keyof UserNotificationSetting]?: boolean } = {}
+ webNotifications: { [id in keyof UserNotificationSetting]?: boolean } = {}
+ labelNotifications: { [id in keyof UserNotificationSetting]?: string } = {}
+ rightNotifications: { [id in keyof Partial<UserNotificationSetting>]?: UserRightType } = {}
emailEnabled = false
private savePreferences = debounce(this.savePreferencesImpl.bind(this), 500)
- constructor (
- private userNotificationService: UserNotificationService,
- private serverService: ServerService,
- private notifier: Notifier
- ) {
+ constructor () {
this.notificationSettingGroups = [
{
label: $localize`Social`,
@@ -118,7 +118,7 @@ export class MyAccountNotificationPreferencesComponent implements OnInit {
const rightToHave = this.rightNotifications[field]
if (!rightToHave) return true // No rights needed
- return this.user.hasRight(rightToHave)
+ return this.user().hasRight(rightToHave)
}
hasNotificationsInGroup (group: { keys: (keyof UserNotificationSetting)[] }) {
@@ -134,21 +134,21 @@ export class MyAccountNotificationPreferencesComponent implements OnInit {
}
updateEmailSetting (field: keyof UserNotificationSetting, value: boolean) {
- if (value === true) this.user.notificationSettings[field] |= UserNotificationSettingValue.EMAIL
- else this.user.notificationSettings[field] &= ~UserNotificationSettingValue.EMAIL
+ if (value === true) this.user().notificationSettings[field] |= UserNotificationSettingValue.EMAIL
+ else this.user().notificationSettings[field] &= ~UserNotificationSettingValue.EMAIL
this.savePreferences()
}
updateWebSetting (field: keyof UserNotificationSetting, value: boolean) {
- if (value === true) this.user.notificationSettings[field] |= UserNotificationSettingValue.WEB
- else this.user.notificationSettings[field] &= ~UserNotificationSettingValue.WEB
+ if (value === true) this.user().notificationSettings[field] |= UserNotificationSettingValue.WEB
+ else this.user().notificationSettings[field] &= ~UserNotificationSettingValue.WEB
this.savePreferences()
}
private savePreferencesImpl () {
- this.userNotificationService.updateNotificationSettings(this.user.notificationSettings)
+ this.userNotificationService.updateNotificationSettings(this.user().notificationSettings)
.subscribe({
next: () => {
this.notifier.success($localize`Preferences saved`, undefined, 2000)
@@ -159,8 +159,8 @@ export class MyAccountNotificationPreferencesComponent implements OnInit {
}
private loadNotificationSettings () {
- for (const key of objectKeysTyped(this.user.notificationSettings)) {
- const value = this.user.notificationSettings[key]
+ for (const key of objectKeysTyped(this.user().notificationSettings)) {
+ const value = this.user().notificationSettings[key]
this.emailNotifications[key] = !!(value & UserNotificationSettingValue.EMAIL)
this.webNotifications[key] = !!(value & UserNotificationSettingValue.WEB)
diff --git a/client/src/app/+my-account/my-account-settings/my-account-profile/my-account-profile.component.html b/client/src/app/+my-account/my-account-settings/my-account-profile/my-account-profile.component.html
index de5563b612..7a5e0a52d7 100644
--- a/client/src/app/+my-account/my-account-settings/my-account-profile/my-account-profile.component.html
+++ b/client/src/app/+my-account/my-account-settings/my-account-profile/my-account-profile.component.html
@@ -9,7 +9,7 @@
formControlName="username" readonly
>
<div class="form-group-description" i18n>
- People can find you using &#64;{{ user.username }}&#64;{{ instanceHost }}
+ People can find you using &#64;{{ user().username }}&#64;{{ instanceHost }}
</div>
</div>
diff --git a/client/src/app/+my-account/my-account-settings/my-account-profile/my-account-profile.component.ts b/client/src/app/+my-account/my-account-settings/my-account-profile/my-account-profile.component.ts
index 875087b754..38ddd0bacd 100644
--- a/client/src/app/+my-account/my-account-settings/my-account-profile/my-account-profile.component.ts
+++ b/client/src/app/+my-account/my-account-settings/my-account-profile/my-account-profile.component.ts
@@ -1,5 +1,5 @@
import { NgClass, NgIf } from '@angular/common'
-import { Component, Input, OnInit } from '@angular/core'
+import { Component, OnInit, inject, input } from '@angular/core'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { Notifier, User, UserService } from '@app/core'
import { USER_DESCRIPTION_VALIDATOR, USER_DISPLAY_NAME_REQUIRED_VALIDATOR } from '@app/shared/form-validators/user-validators'
@@ -16,17 +16,13 @@ import { AlertComponent } from '@app/shared/shared-main/common/alert.component'
imports: [ NgIf, FormsModule, ReactiveFormsModule, NgClass, AlertComponent, HelpComponent, MarkdownTextareaComponent ]
})
export class MyAccountProfileComponent extends FormReactive implements OnInit {
- @Input() user: User = null
+ protected formReactiveService = inject(FormReactiveService)
+ private notifier = inject(Notifier)
+ private userService = inject(UserService)
- error: string = null
+ readonly user = input<User>(null)
- constructor (
- protected formReactiveService: FormReactiveService,
- private notifier: Notifier,
- private userService: UserService
- ) {
- super()
- }
+ error: string = null
ngOnInit () {
this.buildForm({
@@ -37,9 +33,9 @@ export class MyAccountProfileComponent extends FormReactive implements OnInit {
this.form.controls['username'].disable()
this.form.patchValue({
- 'username': this.user.username,
- 'display-name': this.user.account.displayName,
- 'description': this.user.account.description
+ 'username': this.user().username,
+ 'display-name': this.user().account.displayName,
+ 'description': this.user().account.description
})
}
@@ -54,15 +50,16 @@ export class MyAccountProfileComponent extends FormReactive implements OnInit {
this.error = null
this.userService.updateMyProfile({ displayName, description })
- .subscribe({
- next: () => {
- this.user.account.displayName = displayName
- this.user.account.description = description
+ .subscribe({
+ next: () => {
+ const user = this.user()
+ user.account.displayName = displayName
+ user.account.description = description
- this.notifier.success($localize`Profile updated.`)
- },
+ this.notifier.success($localize`Profile updated.`)
+ },
- error: err => this.error = err.message
- })
+ error: err => this.error = err.message
+ })
}
}
diff --git a/client/src/app/+my-account/my-account-settings/my-account-settings.component.ts b/client/src/app/+my-account/my-account-settings/my-account-settings.component.ts
index 9bac9eb0c2..fb02777fd2 100644
--- a/client/src/app/+my-account/my-account-settings/my-account-settings.component.ts
+++ b/client/src/app/+my-account/my-account-settings/my-account-settings.component.ts
@@ -1,6 +1,6 @@
import { ViewportScroller, NgIf } from '@angular/common'
import { HttpErrorResponse } from '@angular/common/http'
-import { AfterViewChecked, Component, OnInit } from '@angular/core'
+import { AfterViewChecked, Component, OnInit, inject } from '@angular/core'
import { AuthService, Notifier, User, UserService } from '@app/core'
import { genericUploadErrorHandler } from '@app/helpers'
import { shallowCopy } from '@peertube/peertube-core-utils'
@@ -38,17 +38,15 @@ import { ActorAvatarEditComponent } from '../../shared/shared-actor-image-edit/a
]
})
export class MyAccountSettingsComponent implements OnInit, AfterViewChecked {
+ private viewportScroller = inject(ViewportScroller)
+ private userService = inject(UserService)
+ private authService = inject(AuthService)
+ private notifier = inject(Notifier)
+
user: User
private lastScrollHash: string
- constructor (
- private viewportScroller: ViewportScroller,
- private userService: UserService,
- private authService: AuthService,
- private notifier: Notifier
- ) {}
-
get userInformationLoaded () {
return this.authService.userInformationLoaded
}
@@ -77,11 +75,12 @@ export class MyAccountSettingsComponent implements OnInit, AfterViewChecked {
this.user.account = shallowCopy(this.user.account)
},
- error: (err: HttpErrorResponse) => genericUploadErrorHandler({
- err,
- name: $localize`avatar`,
- notifier: this.notifier
- })
+ error: (err: HttpErrorResponse) =>
+ genericUploadErrorHandler({
+ err,
+ name: $localize`avatar`,
+ notifier: this.notifier
+ })
})
}
diff --git a/client/src/app/+my-account/my-account-settings/my-account-two-factor/my-account-two-factor-button.component.ts b/client/src/app/+my-account/my-account-settings/my-account-two-factor/my-account-two-factor-button.component.ts
index de75460905..e6d4fa245c 100644
--- a/client/src/app/+my-account/my-account-settings/my-account-two-factor/my-account-two-factor-button.component.ts
+++ b/client/src/app/+my-account/my-account-settings/my-account-two-factor/my-account-two-factor-button.component.ts
@@ -1,5 +1,5 @@
import { NgIf } from '@angular/common'
-import { Component, Input, OnInit } from '@angular/core'
+import { Component, OnInit, inject, input } from '@angular/core'
import { AuthService, ConfirmService, Notifier, User } from '@app/core'
import { TwoFactorService } from '@app/shared/shared-users/two-factor.service'
import { ButtonComponent } from '../../../shared/shared-main/buttons/button.component'
@@ -10,20 +10,17 @@ import { ButtonComponent } from '../../../shared/shared-main/buttons/button.comp
imports: [ NgIf, ButtonComponent ]
})
export class MyAccountTwoFactorButtonComponent implements OnInit {
- @Input() user: User
+ private notifier = inject(Notifier)
+ private twoFactorService = inject(TwoFactorService)
+ private confirmService = inject(ConfirmService)
+ private auth = inject(AuthService)
- twoFactorEnabled = false
+ readonly user = input<User>(undefined)
- constructor (
- private notifier: Notifier,
- private twoFactorService: TwoFactorService,
- private confirmService: ConfirmService,
- private auth: AuthService
- ) {
- }
+ twoFactorEnabled = false
ngOnInit () {
- this.twoFactorEnabled = this.user.twoFactorEnabled
+ this.twoFactorEnabled = this.user().twoFactorEnabled
}
async disableTwoFactor () {
@@ -32,7 +29,7 @@ export class MyAccountTwoFactorButtonComponent implements OnInit {
const { confirmed, password } = await this.confirmService.confirmWithPassword({ message, title: $localize`Disable two factor` })
if (confirmed === false) return
- this.twoFactorService.disableTwoFactor({ userId: this.user.id, currentPassword: password })
+ this.twoFactorService.disableTwoFactor({ userId: this.user().id, currentPassword: password })
.subscribe({
next: () => {
this.twoFactorEnabled = false
diff --git a/client/src/app/+my-account/my-account-settings/my-account-two-factor/my-account-two-factor.component.ts b/client/src/app/+my-account/my-account-settings/my-account-two-factor/my-account-two-factor.component.ts
index 9e3adda233..a292d015c4 100644
--- a/client/src/app/+my-account/my-account-settings/my-account-two-factor/my-account-two-factor.component.ts
+++ b/client/src/app/+my-account/my-account-settings/my-account-two-factor/my-account-two-factor.component.ts
@@ -1,5 +1,5 @@
import { NgIf } from '@angular/common'
-import { Component, OnInit } from '@angular/core'
+import { Component, OnInit, inject } from '@angular/core'
import { FormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms'
import { Router } from '@angular/router'
import { AuthService, Notifier, User } from '@app/core'
@@ -16,6 +16,12 @@ import { InputTextComponent } from '../../../shared/shared-forms/input-text.comp
imports: [ NgIf, FormsModule, ReactiveFormsModule, InputTextComponent, QRCodeComponent ]
})
export class MyAccountTwoFactorComponent implements OnInit {
+ private notifier = inject(Notifier)
+ private twoFactorService = inject(TwoFactorService)
+ private formReactiveService = inject(FormReactiveService)
+ private auth = inject(AuthService)
+ private router = inject(Router)
+
twoFactorAlreadyEnabled: boolean
step: 'request' | 'confirm' | 'confirmed' = 'request'
@@ -34,15 +40,6 @@ export class MyAccountTwoFactorComponent implements OnInit {
private user: User
private requestToken: string
- constructor (
- private notifier: Notifier,
- private twoFactorService: TwoFactorService,
- private formReactiveService: FormReactiveService,
- private auth: AuthService,
- private router: Router
- ) {
- }
-
ngOnInit () {
this.buildPasswordForm()
this.buildOTPForm()
diff --git a/client/src/app/+my-account/my-account.component.ts b/client/src/app/+my-account/my-account.component.ts
index 82f2c96f6f..a05bd2aaaf 100644
--- a/client/src/app/+my-account/my-account.component.ts
+++ b/client/src/app/+my-account/my-account.component.ts
@@ -1,4 +1,4 @@
-import { Component, OnInit } from '@angular/core'
+import { Component, OnInit, inject } from '@angular/core'
import { RouterOutlet } from '@angular/router'
import { AuthUser, PluginService } from '@app/core'
import { HorizontalMenuComponent, HorizontalMenuEntry } from '@app/shared/shared-main/menu/horizontal-menu.component'
@@ -8,13 +8,11 @@ import { HorizontalMenuComponent, HorizontalMenuEntry } from '@app/shared/shared
imports: [ HorizontalMenuComponent, RouterOutlet ]
})
export class MyAccountComponent implements OnInit {
+ private pluginService = inject(PluginService)
+
menuEntries: HorizontalMenuEntry[] = []
user: AuthUser
- constructor (
- private pluginService: PluginService
- ) { }
-
ngOnInit (): void {
this.pluginService.ensurePluginsAreLoaded('my-account')
.then(() => this.buildMenu())
diff --git a/client/src/app/+my-library/+my-video-channels/my-video-channels.component.ts b/client/src/app/+my-library/+my-video-channels/my-video-channels.component.ts
index e765f65d5e..e2f05315e1 100644
--- a/client/src/app/+my-library/+my-video-channels/my-video-channels.component.ts
+++ b/client/src/app/+my-library/+my-video-channels/my-video-channels.component.ts
@@ -1,5 +1,5 @@
import { NgFor, NgIf } from '@angular/common'
-import { Component } from '@angular/core'
+import { Component, inject } from '@angular/core'
import { RouterLink } from '@angular/router'
import {
AuthService,
@@ -28,7 +28,7 @@ import { DeferLoadingDirective } from '../../shared/shared-main/common/defer-loa
import { InfiniteScrollerDirective } from '../../shared/shared-main/common/infinite-scroller.directive'
import { NumberFormatterPipe } from '../../shared/shared-main/common/number-formatter.pipe'
-type CustomChartData = (ChartData & { startDate: string, total: number })
+type CustomChartData = ChartData & { startDate: string, total: number }
@Component({
templateUrl: './my-video-channels.component.html',
@@ -50,6 +50,12 @@ type CustomChartData = (ChartData & { startDate: string, total: number })
]
})
export class MyVideoChannelsComponent {
+ private authService = inject(AuthService)
+ private notifier = inject(Notifier)
+ private confirmService = inject(ConfirmService)
+ private videoChannelService = inject(VideoChannelService)
+ private screenService = inject(ScreenService)
+
videoChannels: VideoChannel[] = []
videoChannelsChartData: CustomChartData[]
@@ -68,14 +74,6 @@ export class MyVideoChannelsComponent {
private pagesDone = new Set<number>()
- constructor (
- private authService: AuthService,
- private notifier: Notifier,
- private confirmService: ConfirmService,
- private videoChannelService: VideoChannelService,
- private screenService: ScreenService
- ) {}
-
get isInSmallView () {
return this.screenService.isInSmallView()
}
@@ -93,17 +91,14 @@ export class MyVideoChannelsComponent {
async deleteVideoChannel (videoChannel: VideoChannel) {
const res = await this.confirmService.confirmWithExpectedInput(
$localize`Do you really want to delete ${videoChannel.displayName}?` +
- `<br />` +
- formatICU(
- // eslint-disable-next-line max-len
- $localize`It will delete {count, plural, =1 {1 video} other {{count} videos}} uploaded in this channel, and you will not be able to create another channel or account with the same name (${videoChannel.name})!`,
- { count: videoChannel.videosCount }
- ),
-
+ `<br />` +
+ formatICU(
+ // eslint-disable-next-line max-len
+ $localize`It will delete {count, plural, =1 {1 video} other {{count} videos}} uploaded in this channel, and you will not be able to create another channel or account with the same name (${videoChannel.name})!`,
+ { count: videoChannel.videosCount }
+ ),
$localize`Please type the name of the video channel (${videoChannel.name}) to confirm`,
-
videoChannel.name,
-
$localize`Delete`
)
if (res === false) return
diff --git a/client/src/app/+my-library/comments-on-my-videos/comments-on-my-videos.component.ts b/client/src/app/+my-library/comments-on-my-videos/comments-on-my-videos.component.ts
index df3d7176cd..17841cbf2d 100644
--- a/client/src/app/+my-library/comments-on-my-videos/comments-on-my-videos.component.ts
+++ b/client/src/app/+my-library/comments-on-my-videos/comments-on-my-videos.component.ts
@@ -1,11 +1,10 @@
import { Component } from '@angular/core'
-import { GlobalIconComponent } from '../../shared/shared-icons/global-icon.component'
+
import { VideoCommentListAdminOwnerComponent } from '../../shared/shared-video-comment/video-comment-list-admin-owner.component'
@Component({
templateUrl: './comments-on-my-videos.component.html',
imports: [
- GlobalIconComponent,
VideoCommentListAdminOwnerComponent
]
})
diff --git a/client/src/app/+my-library/my-auto-tag-policies/automatic-tag.service.ts b/client/src/app/+my-library/my-auto-tag-policies/automatic-tag.service.ts
index 7e435e6a99..b15cd611b9 100644
--- a/client/src/app/+my-library/my-auto-tag-policies/automatic-tag.service.ts
+++ b/client/src/app/+my-library/my-auto-tag-policies/automatic-tag.service.ts
@@ -1,5 +1,5 @@
import { HttpClient } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { RestExtractor } from '@app/core'
import { AutomaticTagAvailable, CommentAutomaticTagPolicies } from '@peertube/peertube-models'
import { catchError } from 'rxjs/operators'
@@ -7,12 +7,10 @@ import { environment } from 'src/environments/environment'
@Injectable({ providedIn: 'root' })
export class AutomaticTagService {
- private static BASE_AUTOMATIC_TAGS_URL = environment.apiUrl + '/api/v1/automatic-tags/'
+ private authHttp = inject(HttpClient)
+ private restExtractor = inject(RestExtractor)
- constructor (
- private authHttp: HttpClient,
- private restExtractor: RestExtractor
- ) {}
+ private static BASE_AUTOMATIC_TAGS_URL = environment.apiUrl + '/api/v1/automatic-tags/'
listAvailable (options: {
accountName: string
@@ -41,5 +39,4 @@ export class AutomaticTagService {
return this.authHttp.put(url, { review: options.review })
.pipe(catchError(res => this.restExtractor.handleError(res)))
}
-
}
diff --git a/client/src/app/+my-library/my-auto-tag-policies/my-auto-tag-policies.component.ts b/client/src/app/+my-library/my-auto-tag-policies/my-auto-tag-policies.component.ts
index 52aef8bddd..4984ee02f3 100644
--- a/client/src/app/+my-library/my-auto-tag-policies/my-auto-tag-policies.component.ts
+++ b/client/src/app/+my-library/my-auto-tag-policies/my-auto-tag-policies.component.ts
@@ -1,8 +1,8 @@
-import { Component, OnInit } from '@angular/core'
+import { Component, OnInit, inject } from '@angular/core'
import { FormsModule } from '@angular/forms'
import { AuthService, Notifier } from '@app/core'
import { PeertubeCheckboxComponent } from '@app/shared/shared-forms/peertube-checkbox.component'
-import { GlobalIconComponent } from '@app/shared/shared-icons/global-icon.component'
+
import { AutomaticTagAvailableType } from '@peertube/peertube-models'
import { forkJoin } from 'rxjs'
import { AutomaticTagService } from './automatic-tag.service'
@@ -10,21 +10,16 @@ import { AutomaticTagService } from './automatic-tag.service'
@Component({
templateUrl: './my-auto-tag-policies.component.html',
imports: [
- GlobalIconComponent,
FormsModule,
PeertubeCheckboxComponent
]
})
export class MyAutoTagPoliciesComponent implements OnInit {
- tags: { name: string, review: boolean, type: AutomaticTagAvailableType }[] = []
-
- constructor (
- private authService: AuthService,
- private autoTagsService: AutomaticTagService,
- private notifier: Notifier
- ) {
+ private authService = inject(AuthService)
+ private autoTagsService = inject(AutomaticTagService)
+ private notifier = inject(Notifier)
- }
+ tags: { name: string, review: boolean, type: AutomaticTagAvailableType }[] = []
ngOnInit () {
this.loadAvailableTags()
diff --git a/client/src/app/+my-library/my-follows/my-followers.component.ts b/client/src/app/+my-library/my-follows/my-followers.component.ts
index 4c69df466f..19325b3b0c 100644
--- a/client/src/app/+my-library/my-follows/my-followers.component.ts
+++ b/client/src/app/+my-library/my-follows/my-followers.component.ts
@@ -1,5 +1,5 @@
import { NgFor, NgIf } from '@angular/common'
-import { Component, OnInit } from '@angular/core'
+import { Component, OnInit, inject } from '@angular/core'
import { ActivatedRoute } from '@angular/router'
import { AuthService, ComponentPagination, Notifier, resetCurrentPage } from '@app/core'
import { formatICU } from '@app/helpers'
@@ -17,6 +17,11 @@ import { InfiniteScrollerDirective } from '../../shared/shared-main/common/infin
imports: [ GlobalIconComponent, NgIf, AdvancedInputFilterComponent, InfiniteScrollerDirective, NgFor, ActorAvatarComponent ]
})
export class MyFollowersComponent implements OnInit {
+ private route = inject(ActivatedRoute)
+ private auth = inject(AuthService)
+ private userSubscriptionService = inject(UserSubscriptionService)
+ private notifier = inject(Notifier)
+
follows: ActorFollow[] = []
pagination: ComponentPagination = {
@@ -30,13 +35,6 @@ export class MyFollowersComponent implements OnInit {
inputFilters: AdvancedInputFilter[]
- constructor (
- private route: ActivatedRoute,
- private auth: AuthService,
- private userSubscriptionService: UserSubscriptionService,
- private notifier: Notifier
- ) {}
-
ngOnInit () {
if (this.route.snapshot.queryParams['search']) {
this.search = this.route.snapshot.queryParams['search']
diff --git a/client/src/app/+my-library/my-follows/my-subscriptions.component.ts b/client/src/app/+my-library/my-follows/my-subscriptions.component.ts
index 779d5759e5..1228cbb2eb 100644
--- a/client/src/app/+my-library/my-follows/my-subscriptions.component.ts
+++ b/client/src/app/+my-library/my-follows/my-subscriptions.component.ts
@@ -1,5 +1,5 @@
import { NgFor, NgIf } from '@angular/common'
-import { Component } from '@angular/core'
+import { Component, inject } from '@angular/core'
import { RouterLink } from '@angular/router'
import { ComponentPagination, Notifier, resetCurrentPage } from '@app/core'
import { formatICU } from '@app/helpers'
@@ -8,7 +8,7 @@ import { UserSubscriptionService } from '@app/shared/shared-user-subscription/us
import { Subject } from 'rxjs'
import { ActorAvatarComponent } from '../../shared/shared-actor-image/actor-avatar.component'
import { AdvancedInputFilterComponent } from '../../shared/shared-forms/advanced-input-filter.component'
-import { GlobalIconComponent } from '../../shared/shared-icons/global-icon.component'
+
import { InfiniteScrollerDirective } from '../../shared/shared-main/common/infinite-scroller.directive'
import { SubscribeButtonComponent } from '../../shared/shared-user-subscription/subscribe-button.component'
@@ -16,7 +16,6 @@ import { SubscribeButtonComponent } from '../../shared/shared-user-subscription/
templateUrl: './my-subscriptions.component.html',
styleUrls: [ './my-subscriptions.component.scss' ],
imports: [
- GlobalIconComponent,
NgIf,
AdvancedInputFilterComponent,
InfiniteScrollerDirective,
@@ -27,6 +26,9 @@ import { SubscribeButtonComponent } from '../../shared/shared-user-subscription/
]
})
export class MySubscriptionsComponent {
+ private userSubscriptionService = inject(UserSubscriptionService)
+ private notifier = inject(Notifier)
+
videoChannels: VideoChannel[] = []
pagination: ComponentPagination = {
@@ -39,11 +41,6 @@ export class MySubscriptionsComponent {
search: string
- constructor (
- private userSubscriptionService: UserSubscriptionService,
- private notifier: Notifier
- ) {}
-
onNearOfBottom () {
// Last page
if (this.pagination.totalItems <= (this.pagination.currentPage * this.pagination.itemsPerPage)) return
@@ -68,17 +65,17 @@ export class MySubscriptionsComponent {
private loadSubscriptions (more = true) {
this.userSubscriptionService.listSubscriptions({ pagination: this.pagination, search: this.search })
- .subscribe({
- next: res => {
- this.videoChannels = more
- ? this.videoChannels.concat(res.data)
- : res.data
- this.pagination.totalItems = res.total
+ .subscribe({
+ next: res => {
+ this.videoChannels = more
+ ? this.videoChannels.concat(res.data)
+ : res.data
+ this.pagination.totalItems = res.total
- this.onDataSubject.next(res.data)
- },
+ this.onDataSubject.next(res.data)
+ },
- error: err => this.notifier.error(err.message)
- })
+ error: err => this.notifier.error(err.message)
+ })
}
}
diff --git a/client/src/app/+my-library/my-history/my-history.component.ts b/client/src/app/+my-library/my-history/my-history.component.ts
index c30e4e31d6..087411e9aa 100644
--- a/client/src/app/+my-library/my-history/my-history.component.ts
+++ b/client/src/app/+my-library/my-history/my-history.component.ts
@@ -1,4 +1,4 @@
-import { Component, OnInit, ViewChild } from '@angular/core'
+import { Component, OnInit, inject, viewChild } from '@angular/core'
import { FormsModule } from '@angular/forms'
import {
AuthService,
@@ -36,7 +36,13 @@ import { PeerTubeTemplateDirective } from '../../shared/shared-main/common/peert
]
})
export class MyHistoryComponent implements OnInit, DisableForReuseHook {
- @ViewChild('videosSelection', { static: true }) videosSelection: VideosSelectionComponent
+ private authService = inject(AuthService)
+ private userService = inject(UserService)
+ private notifier = inject(Notifier)
+ private confirmService = inject(ConfirmService)
+ private userHistoryService = inject(UserHistoryService)
+
+ readonly videosSelection = viewChild<VideosSelectionComponent>('videosSelection')
titlePage: string
pagination: ComponentPagination = {
@@ -66,13 +72,7 @@ export class MyHistoryComponent implements OnInit, DisableForReuseHook {
disabled = false
- constructor (
- private authService: AuthService,
- private userService: UserService,
- private notifier: Notifier,
- private confirmService: ConfirmService,
- private userHistoryService: UserHistoryService
- ) {
+ constructor () {
this.titlePage = $localize`My watch history`
}
@@ -92,7 +92,7 @@ export class MyHistoryComponent implements OnInit, DisableForReuseHook {
}
reloadData () {
- this.videosSelection.reloadVideos()
+ this.videosSelection().reloadVideos()
}
onSearch (search: string) {
@@ -151,15 +151,15 @@ export class MyHistoryComponent implements OnInit, DisableForReuseHook {
if (res !== true) return
this.userHistoryService.clearAll()
- .subscribe({
- next: () => {
- this.notifier.success($localize`Video history deleted`)
+ .subscribe({
+ next: () => {
+ this.notifier.success($localize`Video history deleted`)
- this.reloadData()
- },
+ this.reloadData()
+ },
- error: err => this.notifier.error(err.message)
- })
+ error: err => this.notifier.error(err.message)
+ })
}
getNoResultMessage () {
diff --git a/client/src/app/+my-library/my-ownership/my-accept-ownership/my-accept-ownership.component.ts b/client/src/app/+my-library/my-ownership/my-accept-ownership/my-accept-ownership.component.ts
index 882989ac0d..5d6af8bd7d 100644
--- a/client/src/app/+my-library/my-ownership/my-accept-ownership/my-accept-ownership.component.ts
+++ b/client/src/app/+my-library/my-ownership/my-accept-ownership/my-accept-ownership.component.ts
@@ -1,5 +1,5 @@
import { SelectChannelItem } from 'src/types/select-options-item.model'
-import { Component, ElementRef, EventEmitter, OnInit, Output, ViewChild } from '@angular/core'
+import { Component, ElementRef, OnInit, inject, output, viewChild } from '@angular/core'
import { AuthService, Notifier } from '@app/core'
import { listUserChannelsForSelect } from '@app/helpers'
import { OWNERSHIP_CHANGE_CHANNEL_VALIDATOR } from '@app/shared/form-validators/video-ownership-change-validators'
@@ -20,25 +20,21 @@ import { VideoOwnershipService } from '@app/shared/shared-main/video/video-owner
imports: [ GlobalIconComponent, FormsModule, ReactiveFormsModule, SelectChannelComponent, NgIf ]
})
export class MyAcceptOwnershipComponent extends FormReactive implements OnInit {
- @Output() accepted = new EventEmitter<void>()
+ protected formReactiveService = inject(FormReactiveService)
+ private videoOwnershipService = inject(VideoOwnershipService)
+ private notifier = inject(Notifier)
+ private authService = inject(AuthService)
+ private modalService = inject(NgbModal)
- @ViewChild('modal', { static: true }) modal: ElementRef
+ readonly accepted = output()
+
+ readonly modal = viewChild<ElementRef>('modal')
videoChangeOwnership: VideoChangeOwnership | undefined = undefined
videoChannels: SelectChannelItem[]
error: string = null
- constructor (
- protected formReactiveService: FormReactiveService,
- private videoOwnershipService: VideoOwnershipService,
- private notifier: Notifier,
- private authService: AuthService,
- private modalService: NgbModal
- ) {
- super()
- }
-
ngOnInit () {
this.videoChannels = []
@@ -58,7 +54,7 @@ export class MyAcceptOwnershipComponent extends FormReactive implements OnInit {
this.videoChangeOwnership = videoChangeOwnership
this.modalService
- .open(this.modal, { centered: true })
+ .open(this.modal(), { centered: true })
.result
.then(() => this.acceptOwnership())
.catch(() => {
diff --git a/client/src/app/+my-library/my-ownership/my-ownership.component.ts b/client/src/app/+my-library/my-ownership/my-ownership.component.ts
index 219fa928ef..2fccabbf0f 100644
--- a/client/src/app/+my-library/my-ownership/my-ownership.component.ts
+++ b/client/src/app/+my-library/my-ownership/my-ownership.component.ts
@@ -1,5 +1,5 @@
import { NgClass, NgIf } from '@angular/common'
-import { Component, OnInit, ViewChild } from '@angular/core'
+import { Component, OnInit, inject, viewChild } from '@angular/core'
import { Notifier, RestPagination, RestTable } from '@app/core'
import { Account } from '@app/shared/shared-main/account/account.model'
import { PTDatePipe } from '@app/shared/shared-main/common/date.pipe'
@@ -31,19 +31,15 @@ import { MyAcceptOwnershipComponent } from './my-accept-ownership/my-accept-owne
]
})
export class MyOwnershipComponent extends RestTable implements OnInit {
+ private notifier = inject(Notifier)
+ private videoOwnershipService = inject(VideoOwnershipService)
+
videoChangeOwnerships: VideoChangeOwnership[] = []
totalRecords = 0
sort: SortMeta = { field: 'createdAt', order: -1 }
pagination: RestPagination = { count: this.rowsPerPage, start: 0 }
- @ViewChild('myAcceptOwnershipComponent', { static: true }) myAccountAcceptOwnershipComponent: MyAcceptOwnershipComponent
-
- constructor (
- private notifier: Notifier,
- private videoOwnershipService: VideoOwnershipService
- ) {
- super()
- }
+ readonly myAccountAcceptOwnershipComponent = viewChild<MyAcceptOwnershipComponent>('myAcceptOwnershipComponent')
ngOnInit () {
this.initialize()
@@ -65,7 +61,7 @@ export class MyOwnershipComponent extends RestTable implements OnInit {
}
openAcceptModal (videoChangeOwnership: VideoChangeOwnership) {
- this.myAccountAcceptOwnershipComponent.show(videoChangeOwnership)
+ this.myAccountAcceptOwnershipComponent().show(videoChangeOwnership)
}
accepted () {
diff --git a/client/src/app/+my-library/my-video-channel-syncs/my-video-channel-syncs.component.ts b/client/src/app/+my-library/my-video-channel-syncs/my-video-channel-syncs.component.ts
index 44b9e3a824..11e062686d 100644
--- a/client/src/app/+my-library/my-video-channel-syncs/my-video-channel-syncs.component.ts
+++ b/client/src/app/+my-library/my-video-channel-syncs/my-video-channel-syncs.component.ts
@@ -1,5 +1,5 @@
import { NgClass, NgIf } from '@angular/common'
-import { Component, OnInit } from '@angular/core'
+import { Component, OnInit, inject } from '@angular/core'
import { RouterLink } from '@angular/router'
import { AuthService, Notifier, RestPagination, RestTable, ServerService } from '@app/core'
import { VideoChannelSyncService } from '@app/shared/shared-main/channel/video-channel-sync.service'
@@ -34,6 +34,12 @@ import { ActionDropdownComponent, DropdownAction } from '../../shared/shared-mai
]
})
export class MyVideoChannelSyncsComponent extends RestTable implements OnInit {
+ private videoChannelsSyncService = inject(VideoChannelSyncService)
+ private serverService = inject(ServerService)
+ private notifier = inject(Notifier)
+ private authService = inject(AuthService)
+ private videoChannelService = inject(VideoChannelService)
+
error: string
channelSyncs: VideoChannelSync[] = []
@@ -52,16 +58,6 @@ export class MyVideoChannelSyncsComponent extends RestTable implements OnInit {
private serverConfig: HTMLServerConfig
- constructor (
- private videoChannelsSyncService: VideoChannelSyncService,
- private serverService: ServerService,
- private notifier: Notifier,
- private authService: AuthService,
- private videoChannelService: VideoChannelService
- ) {
- super()
- }
-
ngOnInit () {
this.serverConfig = this.serverService.getHTMLConfig()
this.initialize()
diff --git a/client/src/app/+my-library/my-video-channel-syncs/video-channel-sync-edit/video-channel-sync-edit.component.ts b/client/src/app/+my-library/my-video-channel-syncs/video-channel-sync-edit/video-channel-sync-edit.component.ts
index eaea989a5d..cd805b2a98 100644
--- a/client/src/app/+my-library/my-video-channel-syncs/video-channel-sync-edit/video-channel-sync-edit.component.ts
+++ b/client/src/app/+my-library/my-video-channel-syncs/video-channel-sync-edit/video-channel-sync-edit.component.ts
@@ -1,5 +1,5 @@
import { NgClass, NgIf } from '@angular/common'
-import { Component, OnInit } from '@angular/core'
+import { Component, OnInit, inject } from '@angular/core'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { Router } from '@angular/router'
import { AuthService, Notifier } from '@app/core'
@@ -23,21 +23,17 @@ import { REQUIRED_VALIDATOR } from '@app/shared/form-validators/common-validator
imports: [ NgIf, FormsModule, ReactiveFormsModule, NgClass, SelectChannelComponent, AlertComponent ]
})
export class VideoChannelSyncEditComponent extends FormReactive implements OnInit {
+ protected formReactiveService = inject(FormReactiveService)
+ private authService = inject(AuthService)
+ private router = inject(Router)
+ private notifier = inject(Notifier)
+ private videoChannelSyncService = inject(VideoChannelSyncService)
+ private videoChannelService = inject(VideoChannelService)
+
error: string
userVideoChannels: SelectChannelItem[] = []
existingVideosStrategy: string
- constructor (
- protected formReactiveService: FormReactiveService,
- private authService: AuthService,
- private router: Router,
- private notifier: Notifier,
- private videoChannelSyncService: VideoChannelSyncService,
- private videoChannelService: VideoChannelService
- ) {
- super()
- }
-
ngOnInit () {
this.buildForm({
externalChannelUrl: VIDEO_CHANNEL_EXTERNAL_URL_VALIDATOR,
diff --git a/client/src/app/+my-library/my-video-imports/my-video-imports.component.ts b/client/src/app/+my-library/my-video-imports/my-video-imports.component.ts
index 5c0a9e354f..7588a3728b 100644
--- a/client/src/app/+my-library/my-video-imports/my-video-imports.component.ts
+++ b/client/src/app/+my-library/my-video-imports/my-video-imports.component.ts
@@ -1,5 +1,5 @@
import { NgClass, NgIf } from '@angular/common'
-import { Component, OnInit } from '@angular/core'
+import { Component, OnInit, inject } from '@angular/core'
import { Notifier, RestPagination, RestTable } from '@app/core'
import { PTDatePipe } from '@app/shared/shared-main/common/date.pipe'
import { VideoImportService } from '@app/shared/shared-main/video/video-import.service'
@@ -34,18 +34,14 @@ import { TableExpanderIconComponent } from '../../shared/shared-tables/table-exp
]
})
export class MyVideoImportsComponent extends RestTable implements OnInit {
+ private notifier = inject(Notifier)
+ private videoImportService = inject(VideoImportService)
+
videoImports: VideoImport[] = []
totalRecords = 0
sort: SortMeta = { field: 'createdAt', order: 1 }
pagination: RestPagination = { count: this.rowsPerPage, start: 0 }
- constructor (
- private notifier: Notifier,
- private videoImportService: VideoImportService
- ) {
- super()
- }
-
ngOnInit () {
this.initialize()
}
@@ -117,13 +113,13 @@ export class MyVideoImportsComponent extends RestTable implements OnInit {
protected reloadDataInternal () {
this.videoImportService.getMyVideoImports(this.pagination, this.sort, this.search)
- .subscribe({
- next: resultList => {
- this.videoImports = resultList.data
- this.totalRecords = resultList.total
- },
-
- error: err => this.notifier.error(err.message)
- })
+ .subscribe({
+ next: resultList => {
+ this.videoImports = resultList.data
+ this.totalRecords = resultList.total
+ },
+
+ error: err => this.notifier.error(err.message)
+ })
}
}
diff --git a/client/src/app/+my-library/my-video-playlists/my-video-playlist-create.component.ts b/client/src/app/+my-library/my-video-playlists/my-video-playlist-create.component.ts
index 80428e3cd4..4fe3a123fa 100644
--- a/client/src/app/+my-library/my-video-playlists/my-video-playlist-create.component.ts
+++ b/client/src/app/+my-library/my-video-playlists/my-video-playlist-create.component.ts
@@ -1,5 +1,5 @@
import { NgClass, NgIf } from '@angular/common'
-import { Component, OnInit } from '@angular/core'
+import { Component, OnInit, inject } from '@angular/core'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { Router, RouterLink } from '@angular/router'
import { AuthService, Notifier, ServerService } from '@app/core'
@@ -40,18 +40,14 @@ import { MyVideoPlaylistEdit } from './my-video-playlist-edit'
]
})
export class MyVideoPlaylistCreateComponent extends MyVideoPlaylistEdit implements OnInit {
- error: string
+ protected formReactiveService = inject(FormReactiveService)
+ private authService = inject(AuthService)
+ private notifier = inject(Notifier)
+ private router = inject(Router)
+ private videoPlaylistService = inject(VideoPlaylistService)
+ private serverService = inject(ServerService)
- constructor (
- protected formReactiveService: FormReactiveService,
- private authService: AuthService,
- private notifier: Notifier,
- private router: Router,
- private videoPlaylistService: VideoPlaylistService,
- private serverService: ServerService
- ) {
- super()
- }
+ error: string
ngOnInit () {
this.buildForm({
@@ -70,13 +66,13 @@ export class MyVideoPlaylistCreateComponent extends MyVideoPlaylistEdit implemen
.subscribe(channels => this.userVideoChannels = channels)
this.serverService.getVideoPlaylistPrivacies()
- .subscribe(videoPlaylistPrivacies => {
- this.videoPlaylistPrivacies = videoPlaylistPrivacies
+ .subscribe(videoPlaylistPrivacies => {
+ this.videoPlaylistPrivacies = videoPlaylistPrivacies
- this.form.patchValue({
- privacy: VideoPlaylistPrivacy.PRIVATE
- })
+ this.form.patchValue({
+ privacy: VideoPlaylistPrivacy.PRIVATE
})
+ })
}
formValidated () {
diff --git a/client/src/app/+my-library/my-video-playlists/my-video-playlist-elements.component.ts b/client/src/app/+my-library/my-video-playlists/my-video-playlist-elements.component.ts
index 0ffb09401a..256e264d7d 100644
--- a/client/src/app/+my-library/my-video-playlists/my-video-playlist-elements.component.ts
+++ b/client/src/app/+my-library/my-video-playlists/my-video-playlist-elements.component.ts
@@ -1,6 +1,6 @@
import { CdkDrag, CdkDragDrop, CdkDropList } from '@angular/cdk/drag-drop'
import { NgFor, NgIf } from '@angular/common'
-import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core'
+import { Component, OnDestroy, OnInit, inject, viewChild } from '@angular/core'
import { ActivatedRoute, Router } from '@angular/router'
import { ComponentPagination, ConfirmService, HooksService, Notifier, ScreenService, updatePaginationOnDelete } from '@app/core'
import { ButtonComponent } from '@app/shared/shared-main/buttons/button.component'
@@ -10,7 +10,7 @@ import { VideoPlaylist } from '@app/shared/shared-video-playlist/video-playlist.
import { VideoPlaylistService } from '@app/shared/shared-video-playlist/video-playlist.service'
import { VideoPlaylistType } from '@peertube/peertube-models'
import { Subject, Subscription } from 'rxjs'
-import { GlobalIconComponent } from '../../shared/shared-icons/global-icon.component'
+
import { ActionDropdownComponent, DropdownAction } from '../../shared/shared-main/buttons/action-dropdown.component'
import { InfiniteScrollerDirective } from '../../shared/shared-main/common/infinite-scroller.directive'
import { VideoPlaylistElementMiniatureComponent } from '../../shared/shared-video-playlist/video-playlist-element-miniature.component'
@@ -23,7 +23,6 @@ import { VideoPlaylistMiniatureComponent } from '../../shared/shared-video-playl
NgIf,
ButtonComponent,
VideoPlaylistMiniatureComponent,
- GlobalIconComponent,
ActionDropdownComponent,
InfiniteScrollerDirective,
CdkDropList,
@@ -34,7 +33,15 @@ import { VideoPlaylistMiniatureComponent } from '../../shared/shared-video-playl
]
})
export class MyVideoPlaylistElementsComponent implements OnInit, OnDestroy {
- @ViewChild('videoShareModal') videoShareModal: VideoShareComponent
+ private hooks = inject(HooksService)
+ private notifier = inject(Notifier)
+ private router = inject(Router)
+ private confirmService = inject(ConfirmService)
+ private route = inject(ActivatedRoute)
+ private screenService = inject(ScreenService)
+ private videoPlaylistService = inject(VideoPlaylistService)
+
+ readonly videoShareModal = viewChild<VideoShareComponent>('videoShareModal')
playlistElements: VideoPlaylistElement[] = []
playlist: VideoPlaylist
@@ -52,16 +59,6 @@ export class MyVideoPlaylistElementsComponent implements OnInit, OnDestroy {
private videoPlaylistId: string | number
private paramsSub: Subscription
- constructor (
- private hooks: HooksService,
- private notifier: Notifier,
- private router: Router,
- private confirmService: ConfirmService,
- private route: ActivatedRoute,
- private screenService: ScreenService,
- private videoPlaylistService: VideoPlaylistService
- ) {}
-
ngOnInit () {
this.playlistActions = [
[
@@ -141,7 +138,7 @@ export class MyVideoPlaylistElementsComponent implements OnInit, OnDestroy {
}
showShareModal () {
- this.videoShareModal.show()
+ this.videoShareModal().show()
}
async deleteVideoPlaylist (videoPlaylist: VideoPlaylist) {
diff --git a/client/src/app/+my-library/my-video-playlists/my-video-playlist-update.component.ts b/client/src/app/+my-library/my-video-playlists/my-video-playlist-update.component.ts
index 633e1d7a11..aa59fa4970 100644
--- a/client/src/app/+my-library/my-video-playlists/my-video-playlist-update.component.ts
+++ b/client/src/app/+my-library/my-video-playlists/my-video-playlist-update.component.ts
@@ -1,5 +1,5 @@
import { NgClass, NgIf } from '@angular/common'
-import { Component, OnDestroy, OnInit } from '@angular/core'
+import { Component, OnDestroy, OnInit, inject } from '@angular/core'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { ActivatedRoute, Router, RouterLink } from '@angular/router'
import { AuthService, Notifier, ServerService } from '@app/core'
@@ -42,22 +42,18 @@ import { MyVideoPlaylistEdit } from './my-video-playlist-edit'
]
})
export class MyVideoPlaylistUpdateComponent extends MyVideoPlaylistEdit implements OnInit, OnDestroy {
+ protected formReactiveService = inject(FormReactiveService)
+ private authService = inject(AuthService)
+ private notifier = inject(Notifier)
+ private router = inject(Router)
+ private route = inject(ActivatedRoute)
+ private videoPlaylistService = inject(VideoPlaylistService)
+ private serverService = inject(ServerService)
+
error: string
private paramsSub: Subscription
- constructor (
- protected formReactiveService: FormReactiveService,
- private authService: AuthService,
- private notifier: Notifier,
- private router: Router,
- private route: ActivatedRoute,
- private videoPlaylistService: VideoPlaylistService,
- private serverService: ServerService
- ) {
- super()
- }
-
ngOnInit () {
this.buildForm({
displayName: VIDEO_PLAYLIST_DISPLAY_NAME_VALIDATOR,
@@ -75,27 +71,27 @@ export class MyVideoPlaylistUpdateComponent extends MyVideoPlaylistEdit implemen
.subscribe(channels => this.userVideoChannels = channels)
this.paramsSub = this.route.params
- .pipe(
- map(routeParams => routeParams['videoPlaylistId']),
- switchMap(videoPlaylistId => {
- return forkJoin([
- this.videoPlaylistService.getVideoPlaylist(videoPlaylistId),
- this.serverService.getVideoPlaylistPrivacies()
- ])
- })
- )
- .subscribe({
- next: ([ videoPlaylistToUpdate, videoPlaylistPrivacies ]) => {
- this.videoPlaylistToUpdate = videoPlaylistToUpdate
- this.videoPlaylistPrivacies = videoPlaylistPrivacies
-
- this.hydrateFormFromPlaylist()
- },
-
- error: err => {
- this.error = err.message
- }
- })
+ .pipe(
+ map(routeParams => routeParams['videoPlaylistId']),
+ switchMap(videoPlaylistId => {
+ return forkJoin([
+ this.videoPlaylistService.getVideoPlaylist(videoPlaylistId),
+ this.serverService.getVideoPlaylistPrivacies()
+ ])
+ })
+ )
+ .subscribe({
+ next: ([ videoPlaylistToUpdate, videoPlaylistPrivacies ]) => {
+ this.videoPlaylistToUpdate = videoPlaylistToUpdate
+ this.videoPlaylistPrivacies = videoPlaylistPrivacies
+
+ this.hydrateFormFromPlaylist()
+ },
+
+ error: err => {
+ this.error = err.message
+ }
+ })
}
ngOnDestroy () {
diff --git a/client/src/app/+my-library/my-video-playlists/my-video-playlists.component.ts b/client/src/app/+my-library/my-video-playlists/my-video-playlists.component.ts
index 9a3b02aa4f..6a88fe9b87 100644
--- a/client/src/app/+my-library/my-video-playlists/my-video-playlists.component.ts
+++ b/client/src/app/+my-library/my-video-playlists/my-video-playlists.component.ts
@@ -1,5 +1,5 @@
import { NgFor, NgIf } from '@angular/common'
-import { Component } from '@angular/core'
+import { Component, inject } from '@angular/core'
import { RouterLink } from '@angular/router'
import { AuthService, ComponentPagination, ConfirmService, Notifier, resetCurrentPage, updatePaginationOnDelete } from '@app/core'
import { formatICU } from '@app/helpers'
@@ -31,6 +31,11 @@ import { VideoPlaylistMiniatureComponent } from '../../shared/shared-video-playl
]
})
export class MyVideoPlaylistsComponent {
+ private authService = inject(AuthService)
+ private notifier = inject(Notifier)
+ private confirmService = inject(ConfirmService)
+ private videoPlaylistService = inject(VideoPlaylistService)
+
videoPlaylists: VideoPlaylist[] = []
pagination: ComponentPagination = {
@@ -43,13 +48,6 @@ export class MyVideoPlaylistsComponent {
search: string
- constructor (
- private authService: AuthService,
- private notifier: Notifier,
- private confirmService: ConfirmService,
- private videoPlaylistService: VideoPlaylistService
- ) {}
-
async deleteVideoPlaylist (videoPlaylist: VideoPlaylist) {
const res = await this.confirmService.confirm(
$localize`Do you really want to delete ${videoPlaylist.displayName}?`,
@@ -98,17 +96,17 @@ export class MyVideoPlaylistsComponent {
private loadVideoPlaylists (reset = false) {
this.authService.userInformationLoaded
- .pipe(mergeMap(() => {
- const user = this.authService.getUser()
+ .pipe(mergeMap(() => {
+ const user = this.authService.getUser()
- return this.videoPlaylistService.listAccountPlaylists(user.account, this.pagination, '-updatedAt', this.search)
- })).subscribe(res => {
- if (reset) this.videoPlaylists = []
+ return this.videoPlaylistService.listAccountPlaylists(user.account, this.pagination, '-updatedAt', this.search)
+ })).subscribe(res => {
+ if (reset) this.videoPlaylists = []
- this.videoPlaylists = this.videoPlaylists.concat(res.data)
- this.pagination.totalItems = res.total
+ this.videoPlaylists = this.videoPlaylists.concat(res.data)
+ this.pagination.totalItems = res.total
- this.onDataSubject.next(res.data)
- })
+ this.onDataSubject.next(res.data)
+ })
}
}
diff --git a/client/src/app/+my-library/my-video-space.component.ts b/client/src/app/+my-library/my-video-space.component.ts
index c0c6278fe1..d88bd90a5a 100644
--- a/client/src/app/+my-library/my-video-space.component.ts
+++ b/client/src/app/+my-library/my-video-space.component.ts
@@ -1,4 +1,4 @@
-import { Component, OnInit } from '@angular/core'
+import { Component, OnInit, inject } from '@angular/core'
import { RouterOutlet } from '@angular/router'
import { ServerService } from '@app/core'
import { HorizontalMenuComponent, HorizontalMenuEntry } from '@app/shared/shared-main/menu/horizontal-menu.component'
@@ -9,14 +9,12 @@ import { HTMLServerConfig } from '@peertube/peertube-models'
imports: [ RouterOutlet, HorizontalMenuComponent ]
})
export class MyVideoSpaceComponent implements OnInit {
+ private serverService = inject(ServerService)
+
menuEntries: HorizontalMenuEntry[] = []
private serverConfig: HTMLServerConfig
- constructor (
- private serverService: ServerService
- ) { }
-
ngOnInit (): void {
this.serverConfig = this.serverService.getHTMLConfig()
@@ -37,7 +35,7 @@ export class MyVideoSpaceComponent implements OnInit {
children: [
{
label: $localize`Manage`,
- routerLink:'/my-library/video-channels'
+ routerLink: '/my-library/video-channels'
},
{
label: $localize`Followers`,
diff --git a/client/src/app/+my-library/my-videos/modals/video-change-ownership.component.ts b/client/src/app/+my-library/my-videos/modals/video-change-ownership.component.ts
index 4ee48748af..316b9eb16a 100644
--- a/client/src/app/+my-library/my-videos/modals/video-change-ownership.component.ts
+++ b/client/src/app/+my-library/my-videos/modals/video-change-ownership.component.ts
@@ -1,4 +1,4 @@
-import { Component, ElementRef, OnInit, ViewChild } from '@angular/core'
+import { Component, ElementRef, OnInit, inject, viewChild } from '@angular/core'
import { Notifier, UserService } from '@app/core'
import { OWNERSHIP_CHANGE_USERNAME_VALIDATOR } from '@app/shared/form-validators/video-ownership-change-validators'
import { FormReactive } from '@app/shared/shared-forms/form-reactive'
@@ -18,7 +18,13 @@ import { Video } from '@app/shared/shared-main/video/video.model'
imports: [ GlobalIconComponent, FormsModule, ReactiveFormsModule, AutoCompleteModule, NgIf ]
})
export class VideoChangeOwnershipComponent extends FormReactive implements OnInit {
- @ViewChild('modal', { static: true }) modal: ElementRef
+ protected formReactiveService = inject(FormReactiveService)
+ private videoOwnershipService = inject(VideoOwnershipService)
+ private notifier = inject(Notifier)
+ private userService = inject(UserService)
+ private modalService = inject(NgbModal)
+
+ readonly modal = viewChild<ElementRef>('modal')
usernamePropositions: string[]
@@ -26,16 +32,6 @@ export class VideoChangeOwnershipComponent extends FormReactive implements OnIni
private video: Video | undefined = undefined
- constructor (
- protected formReactiveService: FormReactiveService,
- private videoOwnershipService: VideoOwnershipService,
- private notifier: Notifier,
- private userService: UserService,
- private modalService: NgbModal
- ) {
- super()
- }
-
ngOnInit () {
this.buildForm({
username: OWNERSHIP_CHANGE_USERNAME_VALIDATOR
@@ -46,10 +42,10 @@ export class VideoChangeOwnershipComponent extends FormReactive implements OnIni
show (video: Video) {
this.video = video
this.modalService
- .open(this.modal, { centered: true })
+ .open(this.modal(), { centered: true })
.result
.then(() => this.changeOwnership())
- .catch((_) => _) // Called when closing (cancel) the modal without validating, do nothing
+ .catch(_ => _) // Called when closing (cancel) the modal without validating, do nothing
}
search (event: { query: string }) {
diff --git a/client/src/app/+my-library/my-videos/my-videos.component.ts b/client/src/app/+my-library/my-videos/my-videos.component.ts
index a2757d00fe..835a9d433f 100644
--- a/client/src/app/+my-library/my-videos/my-videos.component.ts
+++ b/client/src/app/+my-library/my-videos/my-videos.component.ts
@@ -1,7 +1,7 @@
import { NgIf } from '@angular/common'
-import { Component, OnInit, ViewChild } from '@angular/core'
+import { Component, OnInit, inject, viewChild } from '@angular/core'
import { FormsModule } from '@angular/forms'
-import { ActivatedRoute, Router, RouterLink } from '@angular/router'
+import { ActivatedRoute, Router } from '@angular/router'
import {
AuthService,
ComponentPagination,
@@ -27,7 +27,7 @@ import { uniqBy } from 'lodash-es'
import { concat, Observable } from 'rxjs'
import { tap, toArray } from 'rxjs/operators'
import { AdvancedInputFilter, AdvancedInputFilterComponent } from '../../shared/shared-forms/advanced-input-filter.component'
-import { GlobalIconComponent } from '../../shared/shared-icons/global-icon.component'
+
import { EditButtonComponent } from '../../shared/shared-main/buttons/edit-button.component'
import { PeerTubeTemplateDirective } from '../../shared/shared-main/common/peertube-template.directive'
import {
@@ -40,10 +40,8 @@ import { VideoChangeOwnershipComponent } from './modals/video-change-ownership.c
templateUrl: './my-videos.component.html',
styleUrls: [ './my-videos.component.scss' ],
imports: [
- GlobalIconComponent,
DeleteButtonComponent,
NgIf,
- RouterLink,
AdvancedInputFilterComponent,
FormsModule,
VideosSelectionComponent,
@@ -54,9 +52,19 @@ import { VideoChangeOwnershipComponent } from './modals/video-change-ownership.c
]
})
export class MyVideosComponent implements OnInit, DisableForReuseHook {
- @ViewChild('videosSelection', { static: true }) videosSelection: VideosSelectionComponent
- @ViewChild('videoChangeOwnershipModal', { static: true }) videoChangeOwnershipModal: VideoChangeOwnershipComponent
- @ViewChild('liveStreamInformationModal', { static: true }) liveStreamInformationModal: LiveStreamInformationComponent
+ protected router = inject(Router)
+ protected serverService = inject(ServerService)
+ protected route = inject(ActivatedRoute)
+ protected authService = inject(AuthService)
+ protected notifier = inject(Notifier)
+ protected screenService = inject(ScreenService)
+ private confirmService = inject(ConfirmService)
+ private videoService = inject(VideoService)
+ private playlistService = inject(VideoPlaylistService)
+
+ readonly videosSelection = viewChild<VideosSelectionComponent>('videosSelection')
+ readonly videoChangeOwnershipModal = viewChild<VideoChangeOwnershipComponent>('videoChangeOwnershipModal')
+ readonly liveStreamInformationModal = viewChild<LiveStreamInformationComponent>('liveStreamInformationModal')
videosContainedInPlaylists: VideosExistInPlaylists = {}
titlePage: string
@@ -109,17 +117,7 @@ export class MyVideosComponent implements OnInit, DisableForReuseHook {
private search: string
private userChannels: VideoChannel[] = []
- constructor (
- protected router: Router,
- protected serverService: ServerService,
- protected route: ActivatedRoute,
- protected authService: AuthService,
- protected notifier: Notifier,
- protected screenService: ScreenService,
- private confirmService: ConfirmService,
- private videoService: VideoService,
- private playlistService: VideoPlaylistService
- ) {
+ constructor () {
this.titlePage = $localize`My videos`
}
@@ -168,11 +166,11 @@ export class MyVideosComponent implements OnInit, DisableForReuseHook {
}
reloadData () {
- this.videosSelection.reloadVideos()
+ this.videosSelection().reloadVideos()
}
onChangeSortColumn () {
- this.videosSelection.reloadVideos()
+ this.videosSelection().reloadVideos()
}
disableForReuse () {
@@ -209,8 +207,8 @@ export class MyVideosComponent implements OnInit, DisableForReuseHook {
async deleteSelectedVideos () {
const toDeleteVideosIds = Object.entries(this.selection)
- .filter(([ _k, v ]) => v === true)
- .map(([ k, _v ]) => parseInt(k, 10))
+ .filter(([ _k, v ]) => v === true)
+ .map(([ k, _v ]) => parseInt(k, 10))
const res = await this.confirmService.confirm(
formatICU(
@@ -224,7 +222,7 @@ export class MyVideosComponent implements OnInit, DisableForReuseHook {
const observables: Observable<any>[] = []
for (const videoId of toDeleteVideosIds) {
const o = this.videoService.removeVideo(videoId)
- .pipe(tap(() => this.removeVideoFromArray(videoId)))
+ .pipe(tap(() => this.removeVideoFromArray(videoId)))
observables.push(o)
}
@@ -252,7 +250,7 @@ export class MyVideosComponent implements OnInit, DisableForReuseHook {
}
changeOwnership (video: Video) {
- this.videoChangeOwnershipModal.show(video)
+ this.videoChangeOwnershipModal().show(video)
}
getTotalTitle () {
diff --git a/client/src/app/+my-library/my-watched-words-list/my-watched-words-list.component.ts b/client/src/app/+my-library/my-watched-words-list/my-watched-words-list.component.ts
index 256d74298e..437e63330f 100644
--- a/client/src/app/+my-library/my-watched-words-list/my-watched-words-list.component.ts
+++ b/client/src/app/+my-library/my-watched-words-list/my-watched-words-list.component.ts
@@ -1,16 +1,14 @@
import { Component } from '@angular/core'
import { RouterLink } from '@angular/router'
-import { GlobalIconComponent } from '@app/shared/shared-icons/global-icon.component'
+
import { WatchedWordsListAdminOwnerComponent } from '@app/shared/standalone-watched-words/watched-words-list-admin-owner.component'
@Component({
templateUrl: './my-watched-words-list.component.html',
imports: [
- GlobalIconComponent,
WatchedWordsListAdminOwnerComponent,
RouterLink
]
})
export class MyWatchedWordsListComponent {
-
}
diff --git a/client/src/app/+remote-interaction/remote-interaction.component.ts b/client/src/app/+remote-interaction/remote-interaction.component.ts
index e5df7b4146..c84e5c8897 100644
--- a/client/src/app/+remote-interaction/remote-interaction.component.ts
+++ b/client/src/app/+remote-interaction/remote-interaction.component.ts
@@ -1,5 +1,5 @@
import { NgIf } from '@angular/common'
-import { Component, OnInit } from '@angular/core'
+import { Component, OnInit, inject } from '@angular/core'
import { ActivatedRoute, Router } from '@angular/router'
import { VideoChannel } from '@app/shared/shared-main/channel/video-channel.model'
import { AlertComponent } from '@app/shared/shared-main/common/alert.component'
@@ -13,13 +13,11 @@ import { forkJoin } from 'rxjs'
imports: [ NgIf, AlertComponent ]
})
export class RemoteInteractionComponent implements OnInit {
- error = ''
+ private route = inject(ActivatedRoute)
+ private router = inject(Router)
+ private search = inject(SearchService)
- constructor (
- private route: ActivatedRoute,
- private router: Router,
- private search: SearchService
- ) { }
+ error = ''
ngOnInit () {
const uri = this.route.snapshot.queryParams['uri']
@@ -55,5 +53,4 @@ export class RemoteInteractionComponent implements OnInit {
this.router.navigateByUrl(redirectUrl)
})
}
-
}
diff --git a/client/src/app/+reset-password/reset-password.component.ts b/client/src/app/+reset-password/reset-password.component.ts
index 9fc47c37e6..1f0a286f8c 100644
--- a/client/src/app/+reset-password/reset-password.component.ts
+++ b/client/src/app/+reset-password/reset-password.component.ts
@@ -1,4 +1,4 @@
-import { Component, OnInit } from '@angular/core'
+import { Component, OnInit, inject } from '@angular/core'
import { ActivatedRoute, Router } from '@angular/router'
import { Notifier, UserService } from '@app/core'
import { RESET_PASSWORD_CONFIRM_VALIDATOR } from '@app/shared/form-validators/reset-password-validators'
@@ -14,19 +14,15 @@ import { FormsModule, ReactiveFormsModule } from '@angular/forms'
imports: [ FormsModule, ReactiveFormsModule, InputTextComponent ]
})
export class ResetPasswordComponent extends FormReactive implements OnInit {
+ protected formReactiveService = inject(FormReactiveService)
+ private userService = inject(UserService)
+ private notifier = inject(Notifier)
+ private router = inject(Router)
+ private route = inject(ActivatedRoute)
+
private userId: number
private verificationString: string
- constructor (
- protected formReactiveService: FormReactiveService,
- private userService: UserService,
- private notifier: Notifier,
- private router: Router,
- private route: ActivatedRoute
- ) {
- super()
- }
-
ngOnInit () {
this.buildForm({
'password': USER_PASSWORD_VALIDATOR,
diff --git a/client/src/app/+search/search-filters.component.html b/client/src/app/+search/search-filters.component.html
index f54c845f46..e97a177b18 100644
--- a/client/src/app/+search/search-filters.component.html
+++ b/client/src/app/+search/search-filters.component.html
@@ -5,13 +5,13 @@
<fieldset class="form-group" role="radiogroup">
<div class="radio-label label-container">
<label for="sort" i18n>Sort</label>
- <button type="button" i18n class="reset-button reset-button-small" (click)="resetField('sort', '-match')" *ngIf="advancedSearch.sort !== '-match'">
+ <button type="button" i18n class="reset-button reset-button-small" (click)="resetField('sort', '-match')" *ngIf="advancedSearch().sort !== '-match'">
Reset
</button>
</div>
<div class="peertube-radio-container" *ngFor="let sort of sorts">
- <input type="radio" name="sort" [id]="sort.id" [value]="sort.id" [(ngModel)]="advancedSearch.sort">
+ <input type="radio" name="sort" [id]="sort.id" [value]="sort.id" [(ngModel)]="advancedSearch().sort">
<label [for]="sort.id" class="radio">{{ sort.label }}</label>
</div>
</fieldset>
@@ -19,18 +19,18 @@
<div class="form-group" role="radiogroup">
<div class="radio-label label-container">
<label for="isLive" i18n>Display only</label>
- <button type="button" i18n class="reset-button reset-button-small" (click)="resetField('isLive')" *ngIf="advancedSearch.isLive !== undefined">
+ <button type="button" i18n class="reset-button reset-button-small" (click)="resetField('isLive')" *ngIf="advancedSearch().isLive !== undefined">
Reset
</button>
</div>
<div class="peertube-radio-container">
- <input type="radio" name="isLive" id="isLiveTrue" value="true" [(ngModel)]="advancedSearch.isLive">
+ <input type="radio" name="isLive" id="isLiveTrue" value="true" [(ngModel)]="advancedSearch().isLive">
<label i18n for="isLiveTrue" class="radio">Live videos</label>
</div>
<div class="peertube-radio-container">
- <input type="radio" name="isLive" id="isLiveFalse" value="false" [(ngModel)]="advancedSearch.isLive">
+ <input type="radio" name="isLive" id="isLiveFalse" value="false" [(ngModel)]="advancedSearch().isLive">
<label i18n for="isLiveFalse" class="radio">VOD videos</label>
</div>
</div>
@@ -38,18 +38,18 @@
<div class="form-group" role="radiogroup">
<div class="radio-label label-container">
<label for="sensitiveContent" i18n>Display sensitive content</label>
- <button type="button" i18n class="reset-button reset-button-small" (click)="resetField('nsfw')" *ngIf="advancedSearch.nsfw !== undefined">
+ <button type="button" i18n class="reset-button reset-button-small" (click)="resetField('nsfw')" *ngIf="advancedSearch().nsfw !== undefined">
Reset
</button>
</div>
<div class="peertube-radio-container">
- <input type="radio" name="sensitiveContent" id="sensitiveContentYes" value="both" [(ngModel)]="advancedSearch.nsfw">
+ <input type="radio" name="sensitiveContent" id="sensitiveContentYes" value="both" [(ngModel)]="advancedSearch().nsfw">
<label i18n for="sensitiveContentYes" class="radio">Yes</label>
</div>
<div class="peertube-radio-container">
- <input type="radio" name="sensitiveContent" id="sensitiveContentNo" value="false" [(ngModel)]="advancedSearch.nsfw">
+ <input type="radio" name="sensitiveContent" id="sensitiveContentNo" value="false" [(ngModel)]="advancedSearch().nsfw">
<label i18n for="sensitiveContentNo" class="radio">No</label>
</div>
</div>
@@ -119,11 +119,11 @@
<div class="form-group">
<label i18n for="category">Category</label>
- <button type="button" i18n class="reset-button reset-button-small" (click)="resetField('categoryOneOf')" *ngIf="advancedSearch.categoryOneOf !== undefined">
+ <button type="button" i18n class="reset-button reset-button-small" (click)="resetField('categoryOneOf')" *ngIf="advancedSearch().categoryOneOf !== undefined">
Reset
</button>
<div class="peertube-select-container">
- <select id="category" name="category" [(ngModel)]="advancedSearch.categoryOneOf" class="form-control">
+ <select id="category" name="category" [(ngModel)]="advancedSearch().categoryOneOf" class="form-control">
<option [ngValue]="undefined" i18n>Display all categories</option>
<option *ngFor="let category of videoCategories" [value]="category.id">{{ category.label }}</option>
</select>
@@ -132,11 +132,11 @@
<div class="form-group">
<label i18n for="licence">Licence</label>
- <button type="button" i18n class="reset-button reset-button-small" (click)="resetField('licenceOneOf')" *ngIf="advancedSearch.licenceOneOf !== undefined">
+ <button type="button" i18n class="reset-button reset-button-small" (click)="resetField('licenceOneOf')" *ngIf="advancedSearch().licenceOneOf !== undefined">
Reset
</button>
<div class="peertube-select-container">
- <select id="licence" name="licence" [(ngModel)]="advancedSearch.licenceOneOf" class="form-control">
+ <select id="licence" name="licence" [(ngModel)]="advancedSearch().licenceOneOf" class="form-control">
<option [ngValue]="undefined" i18n>Display all licenses</option>
<option *ngFor="let licence of videoLicences" [value]="licence.id">{{ licence.label }}</option>
</select>
@@ -145,11 +145,11 @@
<div class="form-group">
<label i18n for="language">Language</label>
- <button type="button" i18n class="reset-button reset-button-small" (click)="resetField('languageOneOf')" *ngIf="advancedSearch.languageOneOf !== undefined">
+ <button type="button" i18n class="reset-button reset-button-small" (click)="resetField('languageOneOf')" *ngIf="advancedSearch().languageOneOf !== undefined">
Reset
</button>
<div class="peertube-select-container">
- <select id="language" name="language" [(ngModel)]="advancedSearch.languageOneOf" class="form-control">
+ <select id="language" name="language" [(ngModel)]="advancedSearch().languageOneOf" class="form-control">
<option [ngValue]="undefined" i18n>Display all languages</option>
<option *ngFor="let language of videoLanguages" [value]="language.id">{{ language.label }}</option>
</select>
@@ -160,48 +160,48 @@
<div class="col-lg-4 col-md-6 col-xs-12">
<div class="form-group">
<label i18n for="tagsAllOf">All of these tags</label>
- <button type="button" i18n class="reset-button reset-button-small" (click)="resetField('tagsAllOf')" *ngIf="advancedSearch.tagsAllOf">
+ <button type="button" i18n class="reset-button reset-button-small" (click)="resetField('tagsAllOf')" *ngIf="advancedSearch().tagsAllOf">
Reset
</button>
- <my-select-tags name="tagsAllOf" inputId="tagsAllOf" [(ngModel)]="advancedSearch.tagsAllOf"></my-select-tags>
+ <my-select-tags name="tagsAllOf" inputId="tagsAllOf" [(ngModel)]="advancedSearch().tagsAllOf"></my-select-tags>
</div>
<div class="form-group">
<label i18n for="tagsOneOf">One of these tags</label>
- <button type="button" i18n class="reset-button reset-button-small" (click)="resetField('tagsOneOf')" *ngIf="advancedSearch.tagsOneOf">
+ <button type="button" i18n class="reset-button reset-button-small" (click)="resetField('tagsOneOf')" *ngIf="advancedSearch().tagsOneOf">
Reset
</button>
- <my-select-tags name="tagsOneOf" inputId="tagsOneOf" [(ngModel)]="advancedSearch.tagsOneOf"></my-select-tags>
+ <my-select-tags name="tagsOneOf" inputId="tagsOneOf" [(ngModel)]="advancedSearch().tagsOneOf"></my-select-tags>
</div>
<div class="form-group">
<label i18n for="host">PeerTube instance host</label>
<input (change)="onDurationOrPublishedUpdated()" (keydown.enter)="$event.preventDefault()" type="text" id="host" name="host"
- placeholder="example.com" [(ngModel)]="advancedSearch.host" class="form-control"
+ placeholder="example.com" [(ngModel)]="advancedSearch().host" class="form-control"
>
</div>
<div class="form-group" role="radiogroup">
<div class="radio-label label-container">
<label for="resultType" i18n>Result types</label>
- <button type="button" i18n class="reset-button reset-button-small" (click)="resetField('resultType')" *ngIf="advancedSearch.resultType !== undefined">
+ <button type="button" i18n class="reset-button reset-button-small" (click)="resetField('resultType')" *ngIf="advancedSearch().resultType !== undefined">
Reset
</button>
</div>
<div class="peertube-radio-container">
- <input type="radio" name="resultType" id="resultTypeVideos" value="videos" [(ngModel)]="advancedSearch.resultType">
+ <input type="radio" name="resultType" id="resultTypeVideos" value="videos" [(ngModel)]="advancedSearch().resultType">
<label i18n for="resultTypeVideos" class="radio">Videos</label>
</div>
<div class="peertube-radio-container">
- <input type="radio" name="resultType" id="resultTypeChannels" value="channels" [(ngModel)]="advancedSearch.resultType">
+ <input type="radio" name="resultType" id="resultTypeChannels" value="channels" [(ngModel)]="advancedSearch().resultType">
<label i18n for="resultTypeChannels" class="radio">Channels</label>
</div>
<div class="peertube-radio-container">
- <input type="radio" name="resultType" id="resultTypePlaylists" value="playlists" [(ngModel)]="advancedSearch.resultType">
+ <input type="radio" name="resultType" id="resultTypePlaylists" value="playlists" [(ngModel)]="advancedSearch().resultType">
<label i18n for="resultTypePlaylists" class="radio">Playlists</label>
</div>
@@ -213,12 +213,12 @@
</div>
<div class="peertube-radio-container">
- <input type="radio" name="searchTarget" id="searchTargetLocal" value="local" [(ngModel)]="advancedSearch.searchTarget">
+ <input type="radio" name="searchTarget" id="searchTargetLocal" value="local" [(ngModel)]="advancedSearch().searchTarget">
<label i18n for="searchTargetLocal" class="radio">Instance</label>
</div>
<div class="peertube-radio-container">
- <input type="radio" name="searchTarget" id="searchTargetSearchIndex" value="search-index" [(ngModel)]="advancedSearch.searchTarget">
+ <input type="radio" name="searchTarget" id="searchTargetSearchIndex" value="search-index" [(ngModel)]="advancedSearch().searchTarget">
<label i18n for="searchTargetSearchIndex" class="radio">Vidiverse</label>
</div>
</div>
@@ -226,7 +226,7 @@
</div>
<div class="submit-button">
- <button type="button" i18n class="reset-button me-3" (click)="reset()" *ngIf="advancedSearch.size()">
+ <button type="button" i18n class="reset-button me-3" (click)="reset()" *ngIf="advancedSearch().size()">
Reset
</button>
diff --git a/client/src/app/+search/search-filters.component.ts b/client/src/app/+search/search-filters.component.ts
index e75d044e70..ba1bcb6e7b 100644
--- a/client/src/app/+search/search-filters.component.ts
+++ b/client/src/app/+search/search-filters.component.ts
@@ -1,4 +1,4 @@
-import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'
+import { Component, OnInit, inject, input, output } from '@angular/core'
import { ServerService } from '@app/core'
import { HTMLServerConfig, VideoConstant } from '@peertube/peertube-models'
import { SelectTagsComponent } from '../shared/shared-forms/select/select-tags.component'
@@ -15,9 +15,10 @@ type FormOption = { id: string, label: string }
imports: [ FormsModule, NgIf, NgFor, SelectTagsComponent ]
})
export class SearchFiltersComponent implements OnInit {
- @Input() advancedSearch: AdvancedSearch = new AdvancedSearch()
+ private serverService = inject(ServerService)
- @Output() filtered = new EventEmitter<AdvancedSearch>()
+ advancedSearch = input<AdvancedSearch>(new AdvancedSearch())
+ filtered = output<AdvancedSearch>()
videoCategories: VideoConstant<number>[] = []
videoLicences: VideoConstant<number>[] = []
@@ -35,9 +36,7 @@ export class SearchFiltersComponent implements OnInit {
private serverConfig: HTMLServerConfig
- constructor (
- private serverService: ServerService
- ) {
+ constructor () {
this.publishedDateRanges = [
{
id: 'today',
@@ -108,11 +107,11 @@ export class SearchFiltersComponent implements OnInit {
formUpdated () {
this.onDurationOrPublishedUpdated()
- this.filtered.emit(this.advancedSearch)
+ this.filtered.emit(this.advancedSearch())
}
reset () {
- this.advancedSearch.reset()
+ this.advancedSearch().reset()
this.resetOriginalPublicationYears()
@@ -123,7 +122,7 @@ export class SearchFiltersComponent implements OnInit {
}
resetField (fieldName: keyof AdvancedSearch, value?: any) {
- (this.advancedSearch as any)[fieldName] = value
+ ;(this.advancedSearch() as any)[fieldName] = value
}
resetLocalField (fieldName: keyof SearchFiltersComponent, value?: any) {
@@ -140,33 +139,37 @@ export class SearchFiltersComponent implements OnInit {
}
private loadOriginallyPublishedAtYears () {
- this.originallyPublishedStartYear = this.advancedSearch.originallyPublishedStartDate
- ? new Date(this.advancedSearch.originallyPublishedStartDate).getFullYear().toString()
+ const advancedSearch = this.advancedSearch()
+ this.originallyPublishedStartYear = advancedSearch.originallyPublishedStartDate
+ ? new Date(advancedSearch.originallyPublishedStartDate).getFullYear().toString()
: undefined
- this.originallyPublishedEndYear = this.advancedSearch.originallyPublishedEndDate
- ? new Date(this.advancedSearch.originallyPublishedEndDate).getFullYear().toString()
+ const advancedSearchValue = this.advancedSearch()
+ this.originallyPublishedEndYear = advancedSearchValue.originallyPublishedEndDate
+ ? new Date(advancedSearchValue.originallyPublishedEndDate).getFullYear().toString()
: undefined
}
private loadFromDurationRange () {
- if (this.advancedSearch.durationMin || this.advancedSearch.durationMax) {
+ const advancedSearch = this.advancedSearch()
+ if (advancedSearch.durationMin || advancedSearch.durationMax) {
const fourMinutes = 60 * 4
const tenMinutes = 60 * 10
- if (this.advancedSearch.durationMin === fourMinutes && this.advancedSearch.durationMax === tenMinutes) {
+ if (advancedSearch.durationMin === fourMinutes && advancedSearch.durationMax === tenMinutes) {
this.durationRange = 'medium'
- } else if (this.advancedSearch.durationMax === fourMinutes) {
+ } else if (advancedSearch.durationMax === fourMinutes) {
this.durationRange = 'short'
- } else if (this.advancedSearch.durationMin === tenMinutes) {
+ } else if (advancedSearch.durationMin === tenMinutes) {
this.durationRange = 'long'
}
}
}
private loadFromPublishedRange () {
- if (this.advancedSearch.startDate) {
- const date = new Date(this.advancedSearch.startDate)
+ const advancedSearch = this.advancedSearch()
+ if (advancedSearch.startDate) {
+ const date = new Date(advancedSearch.startDate)
const now = new Date()
const diff = Math.abs(date.getTime() - now.getTime())
@@ -186,14 +189,15 @@ export class SearchFiltersComponent implements OnInit {
baseDate.setHours(0, 0, 0, 0)
baseDate.setMonth(0, 1)
+ const advancedSearch = this.advancedSearch()
if (this.originallyPublishedStartYear) {
const year = parseInt(this.originallyPublishedStartYear, 10)
const start = new Date(baseDate)
start.setFullYear(year)
- this.advancedSearch.originallyPublishedStartDate = start.toISOString()
+ advancedSearch.originallyPublishedStartDate = start.toISOString()
} else {
- this.advancedSearch.originallyPublishedStartDate = undefined
+ advancedSearch.originallyPublishedStartDate = undefined
}
if (this.originallyPublishedEndYear) {
@@ -201,36 +205,40 @@ export class SearchFiltersComponent implements OnInit {
const end = new Date(baseDate)
end.setFullYear(year)
- this.advancedSearch.originallyPublishedEndDate = end.toISOString()
+ advancedSearch.originallyPublishedEndDate = end.toISOString()
} else {
- this.advancedSearch.originallyPublishedEndDate = undefined
+ advancedSearch.originallyPublishedEndDate = undefined
}
}
private updateModelFromDurationRange () {
if (!this.durationRange) {
- this.advancedSearch.durationMin = undefined
- this.advancedSearch.durationMax = undefined
+ const advancedSearch = this.advancedSearch()
+ advancedSearch.durationMin = undefined
+ advancedSearch.durationMax = undefined
return
}
const fourMinutes = 60 * 4
const tenMinutes = 60 * 10
+ const advancedSearch = this.advancedSearch()
+ const advancedSearchValue = this.advancedSearch()
+ const advancedSearchVal = this.advancedSearch()
switch (this.durationRange) {
case 'short':
- this.advancedSearch.durationMin = undefined
- this.advancedSearch.durationMax = fourMinutes
+ advancedSearch.durationMin = undefined
+ advancedSearch.durationMax = fourMinutes
break
case 'medium':
- this.advancedSearch.durationMin = fourMinutes
- this.advancedSearch.durationMax = tenMinutes
+ advancedSearchValue.durationMin = fourMinutes
+ advancedSearchValue.durationMax = tenMinutes
break
case 'long':
- this.advancedSearch.durationMin = tenMinutes
- this.advancedSearch.durationMax = undefined
+ advancedSearchVal.durationMin = tenMinutes
+ advancedSearchVal.durationMax = undefined
break
}
}
@@ -256,6 +264,6 @@ export class SearchFiltersComponent implements OnInit {
break
}
- this.advancedSearch.startDate = date.toISOString()
+ this.advancedSearch().startDate = date.toISOString()
}
}
diff --git a/client/src/app/+search/search.component.ts b/client/src/app/+search/search.component.ts
index 46bfe2eb2a..ffaca09b50 100644
--- a/client/src/app/+search/search.component.ts
+++ b/client/src/app/+search/search.component.ts
@@ -1,5 +1,5 @@
import { NgFor, NgIf, NgTemplateOutlet } from '@angular/common'
-import { Component, OnDestroy, OnInit } from '@angular/core'
+import { Component, OnDestroy, OnInit, inject } from '@angular/core'
import { ActivatedRoute, Router, RouterLink } from '@angular/router'
import { AuthService, HooksService, MetaService, Notifier, ServerService, User, UserService } from '@app/core'
import { immutableAssign, SimpleMemoize } from '@app/helpers'
@@ -45,6 +45,16 @@ import { SearchFiltersComponent } from './search-filters.component'
]
})
export class SearchComponent implements OnInit, OnDestroy {
+ private route = inject(ActivatedRoute)
+ private router = inject(Router)
+ private metaService = inject(MetaService)
+ private notifier = inject(Notifier)
+ private searchService = inject(SearchService)
+ private authService = inject(AuthService)
+ private userService = inject(UserService)
+ private hooks = inject(HooksService)
+ private serverService = inject(ServerService)
+
error: string
results: (Video | VideoChannel | VideoPlaylist)[] = []
@@ -86,18 +96,6 @@ export class SearchComponent implements OnInit, OnDestroy {
private serverConfig: HTMLServerConfig
- constructor (
- private route: ActivatedRoute,
- private router: Router,
- private metaService: MetaService,
- private notifier: Notifier,
- private searchService: SearchService,
- private authService: AuthService,
- private userService: UserService,
- private hooks: HooksService,
- private serverService: ServerService
- ) { }
-
ngOnInit () {
this.serverConfig = this.serverService.getHTMLConfig()
diff --git a/client/src/app/+search/shared/channel-lazy-load.resolver.ts b/client/src/app/+search/shared/channel-lazy-load.resolver.ts
index 58a09aa1fc..3950d8fdda 100644
--- a/client/src/app/+search/shared/channel-lazy-load.resolver.ts
+++ b/client/src/app/+search/shared/channel-lazy-load.resolver.ts
@@ -1,4 +1,4 @@
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { Router } from '@angular/router'
import { AbstractLazyLoadResolver } from './abstract-lazy-load.resolver'
import { VideoChannel } from '@app/shared/shared-main/channel/video-channel.model'
@@ -6,13 +6,8 @@ import { SearchService } from '@app/shared/shared-search/search.service'
@Injectable()
export class ChannelLazyLoadResolver extends AbstractLazyLoadResolver<VideoChannel> {
-
- constructor (
- protected router: Router,
- private searchService: SearchService
- ) {
- super()
- }
+ protected router = inject(Router)
+ private searchService = inject(SearchService)
protected finder (url: string) {
return this.searchService.searchVideoChannels({ search: url })
diff --git a/client/src/app/+search/shared/playlist-lazy-load.resolver.ts b/client/src/app/+search/shared/playlist-lazy-load.resolver.ts
index dec0be5f89..c14fb272f6 100644
--- a/client/src/app/+search/shared/playlist-lazy-load.resolver.ts
+++ b/client/src/app/+search/shared/playlist-lazy-load.resolver.ts
@@ -1,4 +1,4 @@
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { Router } from '@angular/router'
import { AbstractLazyLoadResolver } from './abstract-lazy-load.resolver'
import { VideoPlaylist } from '@app/shared/shared-video-playlist/video-playlist.model'
@@ -6,13 +6,8 @@ import { SearchService } from '@app/shared/shared-search/search.service'
@Injectable()
export class PlaylistLazyLoadResolver extends AbstractLazyLoadResolver<VideoPlaylist> {
-
- constructor (
- protected router: Router,
- private searchService: SearchService
- ) {
- super()
- }
+ protected router = inject(Router)
+ private searchService = inject(SearchService)
protected finder (url: string) {
return this.searchService.searchVideoPlaylists({ search: url })
diff --git a/client/src/app/+search/shared/video-lazy-load.resolver.ts b/client/src/app/+search/shared/video-lazy-load.resolver.ts
index 2a844bdd2f..2a6e74e33a 100644
--- a/client/src/app/+search/shared/video-lazy-load.resolver.ts
+++ b/client/src/app/+search/shared/video-lazy-load.resolver.ts
@@ -1,4 +1,4 @@
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { Router } from '@angular/router'
import { AbstractLazyLoadResolver } from './abstract-lazy-load.resolver'
import { Video } from '@app/shared/shared-main/video/video.model'
@@ -6,13 +6,8 @@ import { SearchService } from '@app/shared/shared-search/search.service'
@Injectable()
export class VideoLazyLoadResolver extends AbstractLazyLoadResolver<Video> {
-
- constructor (
- protected router: Router,
- private searchService: SearchService
- ) {
- super()
- }
+ protected router = inject(Router)
+ private searchService = inject(SearchService)
protected finder (url: string) {
return this.searchService.searchVideos({ search: url })
diff --git a/client/src/app/+signup/+register/register.component.ts b/client/src/app/+signup/+register/register.component.ts
index ab7eace4c6..a6fe825eba 100644
--- a/client/src/app/+signup/+register/register.component.ts
+++ b/client/src/app/+signup/+register/register.component.ts
@@ -1,6 +1,6 @@
import { CdkStep, CdkStepperNext, CdkStepperPrevious } from '@angular/cdk/stepper'
import { NgIf } from '@angular/common'
-import { Component, OnInit, ViewChild } from '@angular/core'
+import { Component, OnInit, inject, viewChild } from '@angular/core'
import { FormGroup } from '@angular/forms'
import { ActivatedRoute, RouterLink } from '@angular/router'
import { AuthService, ServerService } from '@app/core'
@@ -43,8 +43,14 @@ import { RegisterStepUserComponent } from './steps/register-step-user.component'
]
})
export class RegisterComponent implements OnInit {
- @ViewChild('lastStep') lastStep: CdkStep
- @ViewChild('instanceAboutAccordion') instanceAboutAccordion: InstanceAboutAccordionComponent
+ private route = inject(ActivatedRoute)
+ private authService = inject(AuthService)
+ private signupService = inject(SignupService)
+ private server = inject(ServerService)
+ private hooks = inject(HooksService)
+
+ readonly lastStep = viewChild<CdkStep>('lastStep')
+ readonly instanceAboutAccordion = viewChild<InstanceAboutAccordionComponent>('instanceAboutAccordion')
signupError: string
signupSuccess = false
@@ -78,14 +84,6 @@ export class RegisterComponent implements OnInit {
private serverConfig: ServerConfig
- constructor (
- private route: ActivatedRoute,
- private authService: AuthService,
- private signupService: SignupService,
- private server: ServerService,
- private hooks: HooksService
- ) { }
-
get requiresEmailVerification () {
return this.serverConfig.signup.requiresEmailVerification
}
@@ -152,11 +150,11 @@ export class RegisterComponent implements OnInit {
}
onTermsClick () {
- this.instanceAboutAccordion.expandTerms()
+ this.instanceAboutAccordion().expandTerms()
}
onCodeOfConductClick () {
- this.instanceAboutAccordion.expandCodeOfConduct()
+ this.instanceAboutAccordion().expandCodeOfConduct()
}
onInstanceAboutAccordionInit (instanceAboutAccordion: InstanceAboutAccordionComponent) {
@@ -165,7 +163,7 @@ export class RegisterComponent implements OnInit {
skipChannelCreation () {
this.formStepChannel.reset()
- this.lastStep.select()
+ this.lastStep().select()
this.signup()
}
diff --git a/client/src/app/+signup/+register/steps/register-step-about.component.html b/client/src/app/+signup/+register/steps/register-step-about.component.html
index 1cc8f532e3..47e85d512b 100644
--- a/client/src/app/+signup/+register/steps/register-step-about.component.html
+++ b/client/src/app/+signup/+register/steps/register-step-about.component.html
@@ -1,6 +1,6 @@
<my-instance-banner class="d-block mb-4" rounded="true"></my-instance-banner>
-<my-alert *ngIf="requiresApproval" type="primary" class="text-center">
+<my-alert *ngIf="requiresApproval()" type="primary" class="text-center">
<p>
<ng-container i18n>Moderators of {{ instanceName }} will have to approve your registration request once you have finished to fill the form.</ng-container>
@@ -21,7 +21,7 @@
<li i18n><strong>Comment</strong> videos</li>
<li i18n><strong>Subscribe</strong> to channels to be notified of new videos</li>
<li i18n>Have access to your <strong>watch history</strong></li>
- <li *ngIf="!videoUploadDisabled" i18n>Create your channel to <strong>publish videos</strong></li>
+ <li *ngIf="!videoUploadDisabled()" i18n>Create your channel to <strong>publish videos</strong></li>
</ul>
</div>
diff --git a/client/src/app/+signup/+register/steps/register-step-about.component.ts b/client/src/app/+signup/+register/steps/register-step-about.component.ts
index 3e59ec4c82..ef049bf513 100644
--- a/client/src/app/+signup/+register/steps/register-step-about.component.ts
+++ b/client/src/app/+signup/+register/steps/register-step-about.component.ts
@@ -1,5 +1,5 @@
import { NgIf } from '@angular/common'
-import { Component, Input } from '@angular/core'
+import { Component, inject, input } from '@angular/core'
import { ServerService } from '@app/core'
import { AlertComponent } from '@app/shared/shared-main/common/alert.component'
import { ServerStats } from '@peertube/peertube-models'
@@ -13,19 +13,17 @@ import { DaysDurationFormatterPipe } from '../../../shared/shared-main/date/days
imports: [ InstanceBannerComponent, NgIf, DaysDurationFormatterPipe, AlertComponent ]
})
export class RegisterStepAboutComponent {
- @Input() requiresApproval: boolean
- @Input() videoUploadDisabled: boolean
- @Input() serverStats: ServerStats
+ private serverService = inject(ServerService)
- constructor (private serverService: ServerService) {
-
- }
+ readonly requiresApproval = input<boolean>(undefined)
+ readonly videoUploadDisabled = input<boolean>(undefined)
+ readonly serverStats = input<ServerStats>(undefined)
get instanceName () {
return this.serverService.getHTMLConfig().instance.name
}
get averageResponseTime () {
- return this.serverStats?.averageRegistrationRequestResponseTimeMs
+ return this.serverStats()?.averageRegistrationRequestResponseTimeMs
}
}
diff --git a/client/src/app/+signup/+register/steps/register-step-channel.component.html b/client/src/app/+signup/+register/steps/register-step-channel.component.html
index 70e54d61e0..73e0db1d4f 100644
--- a/client/src/app/+signup/+register/steps/register-step-channel.component.html
+++ b/client/src/app/+signup/+register/steps/register-step-channel.component.html
@@ -1,6 +1,6 @@
<div class="mb-5">
<p i18n>
- You want to <strong>publish videos</strong> on {{ instanceName }}? Then you need to create your first <strong>channel</strong>.
+ You want to <strong>publish videos</strong> on {{ instanceName() }}? Then you need to create your first <strong>channel</strong>.
</p>
<p i18n>
@@ -8,8 +8,8 @@
to publish your piano concerts and another one "Ecology" in which you publish your videos talking about ecology.
</p>
- <p i18n *ngIf="videoQuota !== -1">
- {{ instanceName }} administrators allow you to publish up to <strong>{{ videoQuota | bytes: 0 }} of videos</strong> on their website.
+ <p i18n *ngIf="videoQuota() !== -1">
+ {{ instanceName() }} administrators allow you to publish up to <strong>{{ videoQuota() | bytes: 0 }} of videos</strong> on their website.
</p>
</div>
diff --git a/client/src/app/+signup/+register/steps/register-step-channel.component.ts b/client/src/app/+signup/+register/steps/register-step-channel.component.ts
index 953c62e273..a2e78c7b7a 100644
--- a/client/src/app/+signup/+register/steps/register-step-channel.component.ts
+++ b/client/src/app/+signup/+register/steps/register-step-channel.component.ts
@@ -1,6 +1,6 @@
import { concat, of } from 'rxjs'
import { pairwise } from 'rxjs/operators'
-import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'
+import { Component, OnInit, inject, input, output } from '@angular/core'
import { FormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms'
import { SignupService } from '@app/+signup/shared/signup.service'
import { VIDEO_CHANNEL_DISPLAY_NAME_VALIDATOR, VIDEO_CHANNEL_NAME_VALIDATOR } from '@app/shared/form-validators/video-channel-validators'
@@ -16,18 +16,14 @@ import { NgIf, NgClass } from '@angular/common'
imports: [ NgIf, FormsModule, ReactiveFormsModule, NgClass, BytesPipe ]
})
export class RegisterStepChannelComponent extends FormReactive implements OnInit {
- @Input() username: string
- @Input() instanceName: string
- @Input() videoQuota: number
+ protected formReactiveService = inject(FormReactiveService)
+ private signupService = inject(SignupService)
- @Output() formBuilt = new EventEmitter<FormGroup>()
+ readonly username = input<string>(undefined)
+ readonly instanceName = input<string>(undefined)
+ readonly videoQuota = input<number>(undefined)
- constructor (
- protected formReactiveService: FormReactiveService,
- private signupService: SignupService
- ) {
- super()
- }
+ readonly formBuilt = output<FormGroup>()
get instanceHost () {
return window.location.host
@@ -45,11 +41,12 @@ export class RegisterStepChannelComponent extends FormReactive implements OnInit
of(''),
this.form.get('displayName').valueChanges
).pipe(pairwise())
- .subscribe(([ oldValue, newValue ]) => this.onDisplayNameChange(oldValue, newValue))
+ .subscribe(([ oldValue, newValue ]) => this.onDisplayNameChange(oldValue, newValue))
}
isSameThanUsername () {
- return this.username && this.username === this.form.value['name']
+ const username = this.username()
+ return username && username === this.form.value['name']
}
private onDisplayNameChange (oldDisplayName: string, newDisplayName: string) {
diff --git a/client/src/app/+signup/+register/steps/register-step-terms.component.html b/client/src/app/+signup/+register/steps/register-step-terms.component.html
index f661099ccd..d6b1683daf 100644
--- a/client/src/app/+signup/+register/steps/register-step-terms.component.html
+++ b/client/src/app/+signup/+register/steps/register-step-terms.component.html
@@ -1,7 +1,7 @@
<form [formGroup]="form">
- <div *ngIf="requiresApproval" class="form-group">
- <label i18n for="registrationReason">Why do you want to join {{ instanceName }}?</label>
+ <div *ngIf="requiresApproval()" class="form-group">
+ <label i18n for="registrationReason">Why do you want to join {{ instanceName() }}?</label>
<textarea
id="registrationReason" formControlName="registrationReason" class="form-control" rows="4"
@@ -15,10 +15,10 @@
<my-peertube-checkbox inputName="terms" formControlName="terms">
<ng-template ptTemplate="label">
<ng-container i18n>
- I am at least {{ minimumAge }} years old and agree
+ I am at least {{ minimumAge() }} years old and agree
to the <a class="link-primary" (click)="onTermsClick($event)" href='#'>Terms</a>
- <ng-container *ngIf="hasCodeOfConduct"> and to the <a class="link-primary" (click)="onCodeOfConductClick($event)" href='#'>Code of Conduct</a></ng-container>
- of {{ instanceName }}
+ <ng-container *ngIf="hasCodeOfConduct()"> and to the <a class="link-primary" (click)="onCodeOfConductClick($event)" href='#'>Code of Conduct</a></ng-container>
+ of {{ instanceName() }}
</ng-container>
</ng-template>
</my-peertube-checkbox>
diff --git a/client/src/app/+signup/+register/steps/register-step-terms.component.ts b/client/src/app/+signup/+register/steps/register-step-terms.component.ts
index 284aa78214..4ae83e4633 100644
--- a/client/src/app/+signup/+register/steps/register-step-terms.component.ts
+++ b/client/src/app/+signup/+register/steps/register-step-terms.component.ts
@@ -1,4 +1,4 @@
-import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'
+import { Component, OnInit, inject, input, output } from '@angular/core'
import { FormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms'
import { FormReactive } from '@app/shared/shared-forms/form-reactive'
import { FormReactiveService } from '@app/shared/shared-forms/form-reactive.service'
@@ -14,20 +14,16 @@ import { NgIf, NgClass } from '@angular/common'
imports: [ FormsModule, ReactiveFormsModule, NgIf, NgClass, PeertubeCheckboxComponent, PeerTubeTemplateDirective ]
})
export class RegisterStepTermsComponent extends FormReactive implements OnInit {
- @Input() hasCodeOfConduct = false
- @Input() requiresApproval: boolean
- @Input() minimumAge = 16
- @Input() instanceName: string
-
- @Output() formBuilt = new EventEmitter<FormGroup>()
- @Output() termsClick = new EventEmitter<void>()
- @Output() codeOfConductClick = new EventEmitter<void>()
-
- constructor (
- protected formReactiveService: FormReactiveService
- ) {
- super()
- }
+ protected formReactiveService = inject(FormReactiveService)
+
+ readonly hasCodeOfConduct = input(false)
+ readonly requiresApproval = input<boolean>(undefined)
+ readonly minimumAge = input(16)
+ readonly instanceName = input<string>(undefined)
+
+ readonly formBuilt = output<FormGroup>()
+ readonly termsClick = output()
+ readonly codeOfConductClick = output()
get instanceHost () {
return window.location.host
@@ -37,7 +33,7 @@ export class RegisterStepTermsComponent extends FormReactive implements OnInit {
this.buildForm({
terms: REGISTER_TERMS_VALIDATOR,
- registrationReason: this.requiresApproval
+ registrationReason: this.requiresApproval()
? REGISTER_REASON_VALIDATOR
: null
})
diff --git a/client/src/app/+signup/+register/steps/register-step-user.component.html b/client/src/app/+signup/+register/steps/register-step-user.component.html
index 11811af827..922eb26055 100644
--- a/client/src/app/+signup/+register/steps/register-step-user.component.html
+++ b/client/src/app/+signup/+register/steps/register-step-user.component.html
@@ -1,4 +1,4 @@
-<my-alert type="primary" i18n *ngIf="videoUploadDisabled">
+<my-alert type="primary" i18n *ngIf="videoUploadDisabled()">
Video uploads are disabled on this instance, hence your account won't be able to upload videos.
</my-alert>
@@ -47,7 +47,7 @@
<div class="col-md-12 col-xl-6 form-group">
<label for="email" i18n>Email</label>
- <div *ngIf="requiresEmailVerification" class="form-group-description" i18n>
+ <div *ngIf="requiresEmailVerification()" class="form-group-description" i18n>
This email address will be used to validate your account.
</div>
diff --git a/client/src/app/+signup/+register/steps/register-step-user.component.ts b/client/src/app/+signup/+register/steps/register-step-user.component.ts
index 3818f0f2c9..647ddbbf3f 100644
--- a/client/src/app/+signup/+register/steps/register-step-user.component.ts
+++ b/client/src/app/+signup/+register/steps/register-step-user.component.ts
@@ -1,5 +1,5 @@
import { NgClass, NgIf } from '@angular/common'
-import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'
+import { Component, OnInit, inject, input, output } from '@angular/core'
import { FormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms'
import { SignupService } from '@app/+signup/shared/signup.service'
import {
@@ -22,17 +22,13 @@ import { InputTextComponent } from '../../../shared/shared-forms/input-text.comp
imports: [ NgIf, FormsModule, ReactiveFormsModule, NgClass, InputTextComponent, AlertComponent ]
})
export class RegisterStepUserComponent extends FormReactive implements OnInit {
- @Input() videoUploadDisabled = false
- @Input() requiresEmailVerification = false
+ protected formReactiveService = inject(FormReactiveService)
+ private signupService = inject(SignupService)
- @Output() formBuilt = new EventEmitter<FormGroup>()
+ readonly videoUploadDisabled = input(false)
+ readonly requiresEmailVerification = input(false)
- constructor (
- protected formReactiveService: FormReactiveService,
- private signupService: SignupService
- ) {
- super()
- }
+ readonly formBuilt = output<FormGroup>()
get instanceHost () {
return window.location.host
@@ -52,7 +48,7 @@ export class RegisterStepUserComponent extends FormReactive implements OnInit {
of(''),
this.form.get('displayName').valueChanges
).pipe(pairwise())
- .subscribe(([ oldValue, newValue ]) => this.onDisplayNameChange(oldValue, newValue))
+ .subscribe(([ oldValue, newValue ]) => this.onDisplayNameChange(oldValue, newValue))
}
getMinPasswordLengthMessage () {
diff --git a/client/src/app/+signup/+verify-account/verify-account-ask-send-email/verify-account-ask-send-email.component.ts b/client/src/app/+signup/+verify-account/verify-account-ask-send-email/verify-account-ask-send-email.component.ts
index 169f0ae36c..127f612841 100644
--- a/client/src/app/+signup/+verify-account/verify-account-ask-send-email/verify-account-ask-send-email.component.ts
+++ b/client/src/app/+signup/+verify-account/verify-account-ask-send-email/verify-account-ask-send-email.component.ts
@@ -1,4 +1,4 @@
-import { Component, OnInit } from '@angular/core'
+import { Component, OnInit, inject } from '@angular/core'
import { SignupService } from '@app/+signup/shared/signup.service'
import { Notifier, RedirectService, ServerService } from '@app/core'
import { USER_EMAIL_VALIDATOR } from '@app/shared/form-validators/user-validators'
@@ -13,23 +13,18 @@ import { NgIf, NgClass } from '@angular/common'
styleUrls: [ './verify-account-ask-send-email.component.scss' ],
imports: [ NgIf, FormsModule, ReactiveFormsModule, NgClass ]
})
-
export class VerifyAccountAskSendEmailComponent extends FormReactive implements OnInit {
- requiresEmailVerification = false
+ protected formReactiveService = inject(FormReactiveService)
+ private signupService = inject(SignupService)
+ private serverService = inject(ServerService)
+ private notifier = inject(Notifier)
+ private redirectService = inject(RedirectService)
- constructor (
- protected formReactiveService: FormReactiveService,
- private signupService: SignupService,
- private serverService: ServerService,
- private notifier: Notifier,
- private redirectService: RedirectService
- ) {
- super()
- }
+ requiresEmailVerification = false
ngOnInit () {
this.serverService.getConfig()
- .subscribe(config => this.requiresEmailVerification = config.signup.requiresEmailVerification)
+ .subscribe(config => this.requiresEmailVerification = config.signup.requiresEmailVerification)
this.buildForm({
'verify-email-email': USER_EMAIL_VALIDATOR
diff --git a/client/src/app/+signup/+verify-account/verify-account-email/verify-account-email.component.ts b/client/src/app/+signup/+verify-account/verify-account-email/verify-account-email.component.ts
index f36956f0db..feb8db713c 100644
--- a/client/src/app/+signup/+verify-account/verify-account-email/verify-account-email.component.ts
+++ b/client/src/app/+signup/+verify-account/verify-account-email/verify-account-email.component.ts
@@ -1,5 +1,5 @@
import { NgIf } from '@angular/common'
-import { Component, OnInit } from '@angular/core'
+import { Component, OnInit, inject } from '@angular/core'
import { ActivatedRoute, RouterLink } from '@angular/router'
import { SignupService } from '@app/+signup/shared/signup.service'
import { AuthService, Notifier, ServerService } from '@app/core'
@@ -11,8 +11,13 @@ import { SignupSuccessAfterEmailComponent } from '../../shared/signup-success-af
templateUrl: './verify-account-email.component.html',
imports: [ NgIf, SignupSuccessAfterEmailComponent, RouterLink, AlertComponent ]
})
-
export class VerifyAccountEmailComponent implements OnInit {
+ private signupService = inject(SignupService)
+ private server = inject(ServerService)
+ private authService = inject(AuthService)
+ private notifier = inject(Notifier)
+ private route = inject(ActivatedRoute)
+
success = false
failed = false
isPendingEmail = false
@@ -24,15 +29,6 @@ export class VerifyAccountEmailComponent implements OnInit {
private registrationId: number
private verificationString: string
- constructor (
- private signupService: SignupService,
- private server: ServerService,
- private authService: AuthService,
- private notifier: Notifier,
- private route: ActivatedRoute
- ) {
- }
-
get instanceName () {
return this.server.getHTMLConfig().instance.name
}
diff --git a/client/src/app/+signup/shared/signup-mascot.component.ts b/client/src/app/+signup/shared/signup-mascot.component.ts
index 86efb43fd0..cd7dc5d7af 100644
--- a/client/src/app/+signup/shared/signup-mascot.component.ts
+++ b/client/src/app/+signup/shared/signup-mascot.component.ts
@@ -1,4 +1,4 @@
-import { ChangeDetectionStrategy, Component, Input } from '@angular/core'
+import { ChangeDetectionStrategy, Component, inject, input } from '@angular/core'
import { DomSanitizer } from '@angular/platform-browser'
const images = {
@@ -19,13 +19,11 @@ export type MascotImageName = keyof typeof images
standalone: true
})
export class SignupMascotComponent {
- @Input() imageName: MascotImageName
+ private sanitize = inject(DomSanitizer)
- constructor (private sanitize: DomSanitizer) {
-
- }
+ readonly imageName = input<MascotImageName>(undefined)
get html () {
- return this.sanitize.bypassSecurityTrustHtml(images[this.imageName])
+ return this.sanitize.bypassSecurityTrustHtml(images[this.imageName()])
}
}
diff --git a/client/src/app/+signup/shared/signup-step-title.component.html b/client/src/app/+signup/shared/signup-step-title.component.html
index 9cf4c4826c..18bc4505fb 100644
--- a/client/src/app/+signup/shared/signup-step-title.component.html
+++ b/client/src/app/+signup/shared/signup-step-title.component.html
@@ -1,5 +1,5 @@
<div class="step-content-title">
- <my-signup-mascot [imageName]="mascotImageName"></my-signup-mascot>
+ <my-signup-mascot [imageName]="mascotImageName()"></my-signup-mascot>
<h2>
<ng-content></ng-content>
diff --git a/client/src/app/+signup/shared/signup-step-title.component.ts b/client/src/app/+signup/shared/signup-step-title.component.ts
index 9cbbe15e89..80139de4e0 100644
--- a/client/src/app/+signup/shared/signup-step-title.component.ts
+++ b/client/src/app/+signup/shared/signup-step-title.component.ts
@@ -1,4 +1,4 @@
-import { Component, Input } from '@angular/core'
+import { Component, input } from '@angular/core'
import { MascotImageName, SignupMascotComponent } from './signup-mascot.component'
@Component({
@@ -8,6 +8,5 @@ import { MascotImageName, SignupMascotComponent } from './signup-mascot.componen
imports: [ SignupMascotComponent ]
})
export class SignupStepTitleComponent {
- @Input() mascotImageName: MascotImageName
-
+ readonly mascotImageName = input<MascotImageName>(undefined)
}
diff --git a/client/src/app/+signup/shared/signup-success-after-email.component.html b/client/src/app/+signup/shared/signup-success-after-email.component.html
index 851624c865..ef6010740c 100644
--- a/client/src/app/+signup/shared/signup-success-after-email.component.html
+++ b/client/src/app/+signup/shared/signup-success-after-email.component.html
@@ -3,7 +3,7 @@
</my-signup-step-title>
<my-alert type="primary">
- <ng-container *ngIf="requiresApproval">
+ <ng-container *ngIf="requiresApproval()">
<p i18n>Your email has been verified and your account request has been sent!</p>
<p i18n>
@@ -11,7 +11,7 @@
</p>
</ng-container>
- <ng-container *ngIf="!requiresApproval">
+ <ng-container *ngIf="!requiresApproval()">
<p i18n>Your email has been verified and your account has been created!</p>
<p i18n>
diff --git a/client/src/app/+signup/shared/signup-success-after-email.component.ts b/client/src/app/+signup/shared/signup-success-after-email.component.ts
index 2e9096df9f..2f82a51ddc 100644
--- a/client/src/app/+signup/shared/signup-success-after-email.component.ts
+++ b/client/src/app/+signup/shared/signup-success-after-email.component.ts
@@ -1,5 +1,5 @@
import { NgIf } from '@angular/common'
-import { Component, Input } from '@angular/core'
+import { Component, input } from '@angular/core'
import { AlertComponent } from '@app/shared/shared-main/common/alert.component'
import { SignupStepTitleComponent } from './signup-step-title.component'
@@ -10,5 +10,5 @@ import { SignupStepTitleComponent } from './signup-step-title.component'
imports: [ SignupStepTitleComponent, NgIf, AlertComponent ]
})
export class SignupSuccessAfterEmailComponent {
- @Input() requiresApproval: boolean
+ readonly requiresApproval = input<boolean>(undefined)
}
diff --git a/client/src/app/+signup/shared/signup-success-before-email.component.html b/client/src/app/+signup/shared/signup-success-before-email.component.html
index 2983a32912..52a18f0a1d 100644
--- a/client/src/app/+signup/shared/signup-success-before-email.component.html
+++ b/client/src/app/+signup/shared/signup-success-before-email.component.html
@@ -1,34 +1,34 @@
<my-signup-step-title mascotImageName="success">
- <ng-container *ngIf="requiresApproval">
+ <ng-container *ngIf="requiresApproval()">
<strong i18n>Account request sent</strong>
</ng-container>
- <ng-container *ngIf="!requiresApproval" i18n>
+ <ng-container *ngIf="!requiresApproval()" i18n>
<strong>Welcome</strong>
- <div>on {{ instanceName }}</div>
+ <div>on {{ instanceName() }}</div>
</ng-container>
</my-signup-step-title>
<my-alert type="primary">
- <p *ngIf="requiresApproval" i18n>Your account request has been sent!</p>
- <p *ngIf="!requiresApproval" i18n>Your account has been created!</p>
+ <p *ngIf="requiresApproval()" i18n>Your account request has been sent!</p>
+ <p *ngIf="!requiresApproval()" i18n>Your account has been created!</p>
- <ng-container *ngIf="requiresEmailVerification">
- <p i18n *ngIf="requiresApproval">
+ <ng-container *ngIf="requiresEmailVerification()">
+ <p i18n *ngIf="requiresApproval()">
<strong>Check your email</strong> to validate your account and complete your registration request.
</p>
- <p i18n *ngIf="!requiresApproval">
+ <p i18n *ngIf="!requiresApproval()">
<strong>Check your email</strong> to validate your account and complete your registration.
</p>
</ng-container>
- <ng-container *ngIf="!requiresEmailVerification">
- <p i18n *ngIf="requiresApproval">
+ <ng-container *ngIf="!requiresEmailVerification()">
+ <p i18n *ngIf="requiresApproval()">
A moderator will check your registration request soon and you'll receive an email when it is accepted or rejected.
</p>
- <p *ngIf="!requiresApproval" i18n>
+ <p *ngIf="!requiresApproval()" i18n>
If you need help using PeerTube, you can have a look at the <a class="link-primary" href="https://docs.joinpeertube.org/use/setup-account" target="_blank" rel="noopener noreferrer">documentation</a>.
</p>
</ng-container>
diff --git a/client/src/app/+signup/shared/signup-success-before-email.component.ts b/client/src/app/+signup/shared/signup-success-before-email.component.ts
index 334af1ebce..bd911c2a99 100644
--- a/client/src/app/+signup/shared/signup-success-before-email.component.ts
+++ b/client/src/app/+signup/shared/signup-success-before-email.component.ts
@@ -1,5 +1,5 @@
import { NgIf } from '@angular/common'
-import { Component, Input } from '@angular/core'
+import { Component, input } from '@angular/core'
import { AlertComponent } from '@app/shared/shared-main/common/alert.component'
import { SignupStepTitleComponent } from './signup-step-title.component'
@@ -10,7 +10,7 @@ import { SignupStepTitleComponent } from './signup-step-title.component'
imports: [ SignupStepTitleComponent, NgIf, AlertComponent ]
})
export class SignupSuccessBeforeEmailComponent {
- @Input() requiresApproval: boolean
- @Input() requiresEmailVerification: boolean
- @Input() instanceName: string
+ readonly requiresApproval = input<boolean>(undefined)
+ readonly requiresEmailVerification = input<boolean>(undefined)
+ readonly instanceName = input<string>(undefined)
}
diff --git a/client/src/app/+signup/shared/signup.service.ts b/client/src/app/+signup/shared/signup.service.ts
index 7c331437e0..48b01fee95 100644
--- a/client/src/app/+signup/shared/signup.service.ts
+++ b/client/src/app/+signup/shared/signup.service.ts
@@ -1,29 +1,26 @@
import { catchError, tap } from 'rxjs/operators'
import { HttpClient } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { RestExtractor, UserService } from '@app/core'
import { UserRegister, UserRegistrationRequest } from '@peertube/peertube-models'
@Injectable()
export class SignupService {
-
- constructor (
- private authHttp: HttpClient,
- private restExtractor: RestExtractor,
- private userService: UserService
- ) { }
+ private authHttp = inject(HttpClient)
+ private restExtractor = inject(RestExtractor)
+ private userService = inject(UserService)
directSignup (userCreate: UserRegister) {
return this.authHttp.post(UserService.BASE_USERS_URL + 'register', userCreate)
- .pipe(
- tap(() => this.userService.setSignupInThisSession(true)),
- catchError(err => this.restExtractor.handleError(err))
- )
+ .pipe(
+ tap(() => this.userService.setSignupInThisSession(true)),
+ catchError(err => this.restExtractor.handleError(err))
+ )
}
requestSignup (userCreate: UserRegistrationRequest) {
return this.authHttp.post(UserService.BASE_USERS_URL + 'registrations/request', userCreate)
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
// ---------------------------------------------------------------------------
@@ -42,7 +39,7 @@ export class SignupService {
}
return this.authHttp.post(url, body)
- .pipe(catchError(res => this.restExtractor.handleError(res)))
+ .pipe(catchError(res => this.restExtractor.handleError(res)))
}
verifyRegistrationEmail (options: {
@@ -55,14 +52,14 @@ export class SignupService {
const body = { verificationString }
return this.authHttp.post(url, body)
- .pipe(catchError(res => this.restExtractor.handleError(res)))
+ .pipe(catchError(res => this.restExtractor.handleError(res)))
}
askSendVerifyEmail (email: string) {
const url = UserService.BASE_USERS_URL + 'ask-send-verify-email'
return this.authHttp.post(url, { email })
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
// ---------------------------------------------------------------------------
diff --git a/client/src/app/+stats/video/video-stats.component.ts b/client/src/app/+stats/video/video-stats.component.ts
index e1cd7c4317..f1bf58506f 100644
--- a/client/src/app/+stats/video/video-stats.component.ts
+++ b/client/src/app/+stats/video/video-stats.component.ts
@@ -2,7 +2,7 @@ import { ChartConfiguration, ChartData, ChartOptions, PluginOptionsByType, Scale
import zoomPlugin from 'chartjs-plugin-zoom'
import { Observable, of } from 'rxjs'
import { SelectOptionsItem } from 'src/types'
-import { Component, Inject, LOCALE_ID, OnInit } from '@angular/core'
+import { Component, LOCALE_ID, OnInit, inject } from '@angular/core'
import { ActivatedRoute } from '@angular/router'
import { Notifier, PeerTubeRouterService } from '@app/core'
import { secondsToTime } from '@peertube/peertube-core-utils'
@@ -74,12 +74,20 @@ ChartJSDefaults.color = getComputedStyle(document.body).getPropertyValue('--fg')
]
})
export class VideoStatsComponent implements OnInit {
+ private localeId = inject(LOCALE_ID)
+ private route = inject(ActivatedRoute)
+ private notifier = inject(Notifier)
+ private statsService = inject(VideoStatsService)
+ private peertubeRouter = inject(PeerTubeRouterService)
+ private numberFormatter = inject(NumberFormatterPipe)
+ private liveService = inject(LiveVideoService)
+
// Cannot handle date filters
globalStatsCards: Card[] = []
// Can handle date filters
overallStatCards: Card[] = []
- chartOptions: { [ id in ActiveGraphId ]?: ChartConfiguration<'line' | 'bar'> } = {}
+ chartOptions: { [id in ActiveGraphId]?: ChartConfiguration<'line' | 'bar'> } = {}
chartHeight = '300px'
chartWidth: string = null
@@ -104,17 +112,7 @@ export class VideoStatsComponent implements OnInit {
private statsStartDate: Date
private statsEndDate: Date
- private chartIngestData: { [ id in ActiveGraphId ]?: ChartIngestData } = {}
-
- constructor (
- @Inject(LOCALE_ID) private localeId: string,
- private route: ActivatedRoute,
- private notifier: Notifier,
- private statsService: VideoStatsService,
- private peertubeRouter: PeerTubeRouterService,
- private numberFormatter: NumberFormatterPipe,
- private liveService: LiveVideoService
- ) {}
+ private chartIngestData: { [id in ActiveGraphId]?: ChartIngestData } = {}
ngOnInit () {
this.video = this.route.snapshot.data.video
@@ -356,7 +354,7 @@ export class VideoStatsComponent implements OnInit {
}
private loadChart () {
- const obsBuilders: { [ id in ActiveGraphId ]: Observable<ChartIngestData> } = {
+ const obsBuilders: { [id in ActiveGraphId]: Observable<ChartIngestData> } = {
retention: this.statsService.getRetentionStats(this.video.uuid),
aggregateWatchTime: this.statsService.getTimeserieStats({
@@ -390,7 +388,7 @@ export class VideoStatsComponent implements OnInit {
private buildChartOptions (graphId: ActiveGraphId): ChartConfiguration<'line' | 'bar'> {
const dataBuilders: {
- [ id in ActiveGraphId ]: (rawData: ChartIngestData) => ChartBuilderResult
+ [id in ActiveGraphId]: (rawData: ChartIngestData) => ChartBuilderResult
} = {
retention: (rawData: VideoStatsRetention) => this.buildRetentionChartOptions(rawData),
aggregateWatchTime: (rawData: VideoStatsTimeserie) => this.buildTimeserieChartOptions(rawData),
diff --git a/client/src/app/+stats/video/video-stats.service.ts b/client/src/app/+stats/video/video-stats.service.ts
index c8fb2f261e..9ba764c49c 100644
--- a/client/src/app/+stats/video/video-stats.service.ts
+++ b/client/src/app/+stats/video/video-stats.service.ts
@@ -1,7 +1,7 @@
import { catchError } from 'rxjs'
import { environment } from 'src/environments/environment'
import { HttpClient, HttpParams } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { RestExtractor } from '@app/core'
import { VideoStatsOverall, VideoStatsRetention, VideoStatsTimeserie, VideoStatsTimeserieMetric } from '@peertube/peertube-models'
import { VideoService } from '@app/shared/shared-main/video/video.service'
@@ -10,12 +10,10 @@ import { VideoService } from '@app/shared/shared-main/video/video.service'
providedIn: 'root'
})
export class VideoStatsService {
- static BASE_VIDEO_STATS_URL = environment.apiUrl + '/api/v1/videos/'
+ private authHttp = inject(HttpClient)
+ private restExtractor = inject(RestExtractor)
- constructor (
- private authHttp: HttpClient,
- private restExtractor: RestExtractor
- ) { }
+ static BASE_VIDEO_STATS_URL = environment.apiUrl + '/api/v1/videos/'
getOverallStats (options: {
videoId: string
diff --git a/client/src/app/+video-channels/video-channel-playlists/video-channel-playlists.component.ts b/client/src/app/+video-channels/video-channel-playlists/video-channel-playlists.component.ts
index 3a5749d37d..d9a7e1dcd2 100644
--- a/client/src/app/+video-channels/video-channel-playlists/video-channel-playlists.component.ts
+++ b/client/src/app/+video-channels/video-channel-playlists/video-channel-playlists.component.ts
@@ -1,5 +1,5 @@
import { NgFor, NgIf } from '@angular/common'
-import { AfterViewInit, Component, OnDestroy, OnInit } from '@angular/core'
+import { AfterViewInit, Component, OnDestroy, OnInit, inject } from '@angular/core'
import { ComponentPagination, hasMoreItems, HooksService, resetCurrentPage, ScreenService } from '@app/core'
import { VideoChannel } from '@app/shared/shared-main/channel/video-channel.model'
import { VideoChannelService } from '@app/shared/shared-main/channel/video-channel.service'
@@ -16,6 +16,11 @@ import { VideoPlaylistMiniatureComponent } from '../../shared/shared-video-playl
imports: [ NgIf, InfiniteScrollerDirective, NgFor, VideoPlaylistMiniatureComponent ]
})
export class VideoChannelPlaylistsComponent implements OnInit, AfterViewInit, OnDestroy {
+ private videoPlaylistService = inject(VideoPlaylistService)
+ private videoChannelService = inject(VideoChannelService)
+ private screenService = inject(ScreenService)
+ private hooks = inject(HooksService)
+
videoPlaylists: VideoPlaylist[] = []
pagination: ComponentPagination = {
@@ -29,13 +34,6 @@ export class VideoChannelPlaylistsComponent implements OnInit, AfterViewInit, On
private videoChannelSub: Subscription
private videoChannel: VideoChannel
- constructor (
- private videoPlaylistService: VideoPlaylistService,
- private videoChannelService: VideoChannelService,
- private screenService: ScreenService,
- private hooks: HooksService
- ) {}
-
ngOnInit () {
// Parent get the video channel for us
this.videoChannelSub = this.videoChannelService.videoChannelLoaded
diff --git a/client/src/app/+video-channels/video-channel-videos/video-channel-videos.component.ts b/client/src/app/+video-channels/video-channel-videos/video-channel-videos.component.ts
index c437461baa..7f6c20f6d3 100644
--- a/client/src/app/+video-channels/video-channel-videos/video-channel-videos.component.ts
+++ b/client/src/app/+video-channels/video-channel-videos/video-channel-videos.component.ts
@@ -1,5 +1,5 @@
import { NgIf } from '@angular/common'
-import { AfterViewInit, Component, OnDestroy, OnInit, ViewChild } from '@angular/core'
+import { AfterViewInit, Component, OnDestroy, OnInit, inject, viewChild } from '@angular/core'
import { ComponentPaginationLight, DisableForReuseHook, HooksService, ScreenService } from '@app/core'
import { VideoChannel } from '@app/shared/shared-main/channel/video-channel.model'
import { VideoChannelService } from '@app/shared/shared-main/channel/video-channel.service'
@@ -16,7 +16,12 @@ import { VideosListComponent } from '../../shared/shared-video-miniature/videos-
imports: [ NgIf, VideosListComponent ]
})
export class VideoChannelVideosComponent implements OnInit, AfterViewInit, OnDestroy, DisableForReuseHook {
- @ViewChild('videosList') videosList: VideosListComponent
+ private screenService = inject(ScreenService)
+ private videoChannelService = inject(VideoChannelService)
+ private videoService = inject(VideoService)
+ private hooks = inject(HooksService)
+
+ readonly videosList = viewChild<VideosListComponent>('videosList')
getVideosObservableFunction = this.getVideosObservable.bind(this)
getSyndicationItemsFunction = this.getSyndicationItems.bind(this)
@@ -40,20 +45,12 @@ export class VideoChannelVideosComponent implements OnInit, AfterViewInit, OnDes
private videoChannelSub: Subscription
private alreadyLoaded = false
- constructor (
- private screenService: ScreenService,
- private videoChannelService: VideoChannelService,
- private videoService: VideoService,
- private hooks: HooksService
- ) {
- }
-
ngOnInit () {
// Parent get the video channel for us
this.videoChannelSub = this.videoChannelService.videoChannelLoaded
.subscribe(videoChannel => {
this.videoChannel = videoChannel
- if (this.alreadyLoaded) this.videosList.reloadVideos()
+ if (this.alreadyLoaded) this.videosList().reloadVideos()
this.hooks.runAction('action:video-channel-videos.video-channel.loaded', 'video-channel', { videoChannel })
diff --git a/client/src/app/+video-channels/video-channels.component.ts b/client/src/app/+video-channels/video-channels.component.ts
index 22c7fa646e..bbe58c5796 100644
--- a/client/src/app/+video-channels/video-channels.component.ts
+++ b/client/src/app/+video-channels/video-channels.component.ts
@@ -1,5 +1,5 @@
import { NgClass, NgIf, NgTemplateOutlet } from '@angular/common'
-import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core'
+import { Component, OnDestroy, OnInit, inject, viewChild } from '@angular/core'
import { ActivatedRoute, RouterLink, RouterOutlet } from '@angular/router'
import { AuthService, Hotkey, HotkeysService, MarkdownService, MetaService, RestExtractor, ScreenService, ServerService } from '@app/core'
import { getOriginUrl } from '@app/helpers'
@@ -39,8 +39,20 @@ import { AccountBlockBadgesComponent } from '../shared/shared-moderation/account
]
})
export class VideoChannelsComponent implements OnInit, OnDestroy {
- @ViewChild('subscribeButton') subscribeButton: SubscribeButtonComponent
- @ViewChild('supportModal') supportModal: SupportModalComponent
+ private route = inject(ActivatedRoute)
+ private authService = inject(AuthService)
+ private videoChannelService = inject(VideoChannelService)
+ private videoService = inject(VideoService)
+ private restExtractor = inject(RestExtractor)
+ private hotkeysService = inject(HotkeysService)
+ private screenService = inject(ScreenService)
+ private markdown = inject(MarkdownService)
+ private blocklist = inject(BlocklistService)
+ private metaService = inject(MetaService)
+ private server = inject(ServerService)
+
+ readonly subscribeButton = viewChild<SubscribeButtonComponent>('subscribeButton')
+ readonly supportModal = viewChild<SupportModalComponent>('supportModal')
videoChannel: VideoChannel
ownerAccount: Account
@@ -55,30 +67,18 @@ export class VideoChannelsComponent implements OnInit, OnDestroy {
private routeSub: Subscription
- constructor (
- private route: ActivatedRoute,
- private authService: AuthService,
- private videoChannelService: VideoChannelService,
- private videoService: VideoService,
- private restExtractor: RestExtractor,
- private hotkeysService: HotkeysService,
- private screenService: ScreenService,
- private markdown: MarkdownService,
- private blocklist: BlocklistService,
- private metaService: MetaService,
- private server: ServerService
- ) { }
-
ngOnInit () {
this.routeSub = this.route.params
.pipe(
map(params => params['videoChannelName']),
distinctUntilChanged(),
switchMap(videoChannelName => this.videoChannelService.getVideoChannel(videoChannelName)),
- catchError(err => this.restExtractor.redirectTo404IfNotFound(err, 'other', [
- HttpStatusCode.BAD_REQUEST_400,
- HttpStatusCode.NOT_FOUND_404
- ]))
+ catchError(err =>
+ this.restExtractor.redirectTo404IfNotFound(err, 'other', [
+ HttpStatusCode.BAD_REQUEST_400,
+ HttpStatusCode.NOT_FOUND_404
+ ])
+ )
)
.subscribe(async videoChannel => {
this.metaService.setTitle(videoChannel.displayName)
@@ -106,8 +106,9 @@ export class VideoChannelsComponent implements OnInit, OnDestroy {
this.hotkeys = [
new Hotkey('Shift+s', () => {
- if (this.subscribeButton.isSubscribedToAll()) this.subscribeButton.unsubscribe()
- else this.subscribeButton.subscribe()
+ const subscribeButton = this.subscribeButton()
+ if (subscribeButton.isSubscribedToAll()) subscribeButton.unsubscribe()
+ else subscribeButton.subscribe()
return false
}, $localize`Subscribe to the account`)
@@ -167,7 +168,7 @@ export class VideoChannelsComponent implements OnInit, OnDestroy {
}
showSupportModal () {
- this.supportModal.show()
+ this.supportModal().show()
}
getAccountUrl () {
diff --git a/client/src/app/+video-studio/edit/video-studio-edit.component.ts b/client/src/app/+video-studio/edit/video-studio-edit.component.ts
index 063bcd6718..8b3fb553bc 100644
--- a/client/src/app/+video-studio/edit/video-studio-edit.component.ts
+++ b/client/src/app/+video-studio/edit/video-studio-edit.component.ts
@@ -1,4 +1,4 @@
-import { Component, OnInit } from '@angular/core'
+import { Component, OnInit, inject } from '@angular/core'
import { ActivatedRoute, Router } from '@angular/router'
import { ConfirmService, Notifier, ServerService } from '@app/core'
import { FormReactive } from '@app/shared/shared-forms/form-reactive'
@@ -34,23 +34,19 @@ import { GlobalIconComponent } from '@app/shared/shared-icons/global-icon.compon
]
})
export class VideoStudioEditComponent extends FormReactive implements OnInit {
+ protected formReactiveService = inject(FormReactiveService)
+ private serverService = inject(ServerService)
+ private notifier = inject(Notifier)
+ private router = inject(Router)
+ private route = inject(ActivatedRoute)
+ private videoStudioService = inject(VideoStudioService)
+ private loadingBar = inject(LoadingBarService)
+ private confirmService = inject(ConfirmService)
+
isRunningEdit = false
video: VideoDetails
- constructor (
- protected formReactiveService: FormReactiveService,
- private serverService: ServerService,
- private notifier: Notifier,
- private router: Router,
- private route: ActivatedRoute,
- private videoStudioService: VideoStudioService,
- private loadingBar: LoadingBarService,
- private confirmService: ConfirmService
- ) {
- super()
- }
-
ngOnInit () {
this.video = this.route.snapshot.data.video
@@ -94,8 +90,9 @@ export class VideoStudioEditComponent extends FormReactive implements OnInit {
const title = $localize`Are you sure you want to edit "${this.video.name}"?`
const listHTML = this.getTasksSummary().map(t => `<li>${t}</li>`).join('')
- // eslint-disable-next-line max-len
- const confirmHTML = $localize`The current video will be overwritten by this edited video and <strong>you won't be able to recover it</strong>.<br /><br />` +
+ const confirmHTML =
+ // eslint-disable-next-line max-len
+ $localize`The current video will be overwritten by this edited video and <strong>you won't be able to recover it</strong>.<br /><br />` +
$localize`As a reminder, the following tasks will be executed: <ol>${listHTML}</ol>`
if (await this.confirmService.confirm(confirmHTML, title) !== true) return
@@ -182,7 +179,6 @@ export class VideoStudioEditComponent extends FormReactive implements OnInit {
const cut = value['cut']
if (cut['start'] !== 0 || cut['end'] !== this.video.duration) {
-
const options: VideoStudioTaskCut['options'] = {}
if (cut['start'] !== 0) options.start = cut['start']
if (cut['end'] !== this.video.duration) options.end = cut['end']
@@ -222,5 +218,4 @@ export class VideoStudioEditComponent extends FormReactive implements OnInit {
return tasks
}
-
}
diff --git a/client/src/app/+video-studio/shared/video-studio.service.ts b/client/src/app/+video-studio/shared/video-studio.service.ts
index c7d6dd8485..b5c27935df 100644
--- a/client/src/app/+video-studio/shared/video-studio.service.ts
+++ b/client/src/app/+video-studio/shared/video-studio.service.ts
@@ -1,6 +1,6 @@
import { catchError } from 'rxjs'
import { HttpClient } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { RestExtractor } from '@app/core'
import { objectToFormData } from '@app/helpers'
import { VideoStudioCreateEdition, VideoStudioTask } from '@peertube/peertube-models'
@@ -8,11 +8,8 @@ import { VideoService } from '@app/shared/shared-main/video/video.service'
@Injectable()
export class VideoStudioService {
-
- constructor (
- private authHttp: HttpClient,
- private restExtractor: RestExtractor
- ) {}
+ private authHttp = inject(HttpClient)
+ private restExtractor = inject(RestExtractor)
editVideo (videoId: number | string, tasks: VideoStudioTask[]) {
const url = VideoService.BASE_VIDEO_URL + '/' + videoId + '/studio/edit'
diff --git a/client/src/app/+videos/+video-edit/shared/caption/video-caption-add-modal.component.ts b/client/src/app/+videos/+video-edit/shared/caption/video-caption-add-modal.component.ts
index 233eb120f8..d116a2e4ef 100644
--- a/client/src/app/+videos/+video-edit/shared/caption/video-caption-add-modal.component.ts
+++ b/client/src/app/+videos/+video-edit/shared/caption/video-caption-add-modal.component.ts
@@ -1,5 +1,5 @@
import { NgIf } from '@angular/common'
-import { Component, ElementRef, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core'
+import { Component, ElementRef, OnInit, inject, input, output, viewChild } from '@angular/core'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { ServerService } from '@app/core'
import { VIDEO_CAPTION_FILE_VALIDATOR, VIDEO_CAPTION_LANGUAGE_VALIDATOR } from '@app/shared/form-validators/video-captions-validators'
@@ -18,34 +18,29 @@ import { GlobalIconComponent } from '../../../../shared/shared-icons/global-icon
templateUrl: './video-caption-add-modal.component.html',
imports: [ FormsModule, ReactiveFormsModule, GlobalIconComponent, NgIf, ReactiveFileComponent, SelectOptionsComponent ]
})
-
export class VideoCaptionAddModalComponent extends FormReactive implements OnInit {
- @Input() existingCaptions: string[]
- @Input() serverConfig: HTMLServerConfig
+ protected formReactiveService = inject(FormReactiveService)
+ private modalService = inject(NgbModal)
+ private serverService = inject(ServerService)
+
+ readonly existingCaptions = input<string[]>(undefined)
+ readonly serverConfig = input<HTMLServerConfig>(undefined)
- @Output() captionAdded = new EventEmitter<VideoCaptionEdit>()
+ readonly captionAdded = output<VideoCaptionEdit>()
- @ViewChild('modal', { static: true }) modal: ElementRef
+ readonly modal = viewChild<ElementRef>('modal')
videoCaptionLanguages: VideoConstant<string>[] = []
private openedModal: NgbModalRef
private closingModal = false
- constructor (
- protected formReactiveService: FormReactiveService,
- private modalService: NgbModal,
- private serverService: ServerService
- ) {
- super()
- }
-
get videoCaptionExtensions () {
- return this.serverConfig.videoCaption.file.extensions
+ return this.serverConfig().videoCaption.file.extensions
}
get videoCaptionMaxSize () {
- return this.serverConfig.videoCaption.file.size.max
+ return this.serverConfig().videoCaption.file.size.max
}
getReactiveFileButtonTooltip () {
@@ -54,7 +49,7 @@ export class VideoCaptionAddModalComponent extends FormReactive implements OnIni
ngOnInit () {
this.serverService.getVideoLanguages()
- .subscribe(languages => this.videoCaptionLanguages = languages)
+ .subscribe(languages => this.videoCaptionLanguages = languages)
this.buildForm({
language: VIDEO_CAPTION_LANGUAGE_VALIDATOR,
@@ -65,7 +60,7 @@ export class VideoCaptionAddModalComponent extends FormReactive implements OnIni
show () {
this.closingModal = false
- this.openedModal = this.modalService.open(this.modal, { centered: true, keyboard: false })
+ this.openedModal = this.modalService.open(this.modal(), { centered: true, keyboard: false })
}
hide () {
@@ -79,7 +74,7 @@ export class VideoCaptionAddModalComponent extends FormReactive implements OnIni
const languageId = this.form.value['language']
- return languageId && this.existingCaptions.includes(languageId)
+ return languageId && this.existingCaptions().includes(languageId)
}
addCaption () {
diff --git a/client/src/app/+videos/+video-edit/shared/caption/video-caption-edit-modal-content.component.html b/client/src/app/+videos/+video-edit/shared/caption/video-caption-edit-modal-content.component.html
index 31fef6066a..c93ac7e2fe 100644
--- a/client/src/app/+videos/+video-edit/shared/caption/video-caption-edit-modal-content.component.html
+++ b/client/src/app/+videos/+video-edit/shared/caption/video-caption-edit-modal-content.component.html
@@ -1,5 +1,5 @@
<div class="modal-header">
- <h4 i18n class="modal-title">Edit caption "{{ videoCaption.language.label }}"</h4>
+ <h4 i18n class="modal-title">Edit caption "{{ videoCaption().language.label }}"</h4>
<button class="border-0 p-0" title="Close this modal" i18n-title (click)="hide()">
<my-global-icon iconName="cross"></my-global-icon>
@@ -10,9 +10,9 @@
<div class="row">
- <my-embed *ngIf="publishedVideo" #embed class="col-md-12 col-xl-6 mb-3" [video]="publishedVideo" enableAPI="true"></my-embed>
+ <my-embed *ngIf="publishedVideo()" #embed class="col-md-12 col-xl-6 mb-3" [video]="publishedVideo()" enableAPI="true"></my-embed>
- <div [ngClass]="publishedVideo ? 'col-xl-6 col-md-12' : ''">
+ <div [ngClass]="publishedVideo() ? 'col-xl-6 col-md-12' : ''">
<div class="d-flex justify-content-between align-items-center mb-3 ms-2">
<my-peertube-checkbox
@@ -52,11 +52,11 @@
<my-timestamp-input
class="me-1"
- inputName="segmentStart" enableBorder="true" [maxTimestamp]="publishedVideo.duration * 1000" mask="99:99:99.999"
+ inputName="segmentStart" enableBorder="true" [maxTimestamp]="publishedVideo().duration * 1000" mask="99:99:99.999"
[(ngModel)]="segment.startMs" [parser]="timestampParser" [formatter]="timestampFormatter"
></my-timestamp-input>
- <my-button *ngIf="publishedVideo" icon="clock-arrow-down" i18n-title title="Use video current time as start time" (click)="videoTimeForSegmentStart(segment)">
+ <my-button *ngIf="publishedVideo()" icon="clock-arrow-down" i18n-title title="Use video current time as start time" (click)="videoTimeForSegmentStart(segment)">
</my-button>
</div>
@@ -67,11 +67,11 @@
<my-timestamp-input
class="me-1"
- inputName="segmentEnd" enableBorder="true" [maxTimestamp]="publishedVideo.duration * 1000" mask="99:99:99.999"
+ inputName="segmentEnd" enableBorder="true" [maxTimestamp]="publishedVideo().duration * 1000" mask="99:99:99.999"
[(ngModel)]="segment.endMs" [parser]="timestampParser" [formatter]="timestampFormatter"
></my-timestamp-input>
- <my-button *ngIf="publishedVideo" icon="clock-arrow-down" i18n-title title="Use video current time as end time" (click)="videoTimeForSegmentEnd(segment)">
+ <my-button *ngIf="publishedVideo()" icon="clock-arrow-down" i18n-title title="Use video current time as end time" (click)="videoTimeForSegmentEnd(segment)">
</my-button>
</div>
</div>
diff --git a/client/src/app/+videos/+video-edit/shared/caption/video-caption-edit-modal-content.component.ts b/client/src/app/+videos/+video-edit/shared/caption/video-caption-edit-modal-content.component.ts
index 060f6e98db..f611457242 100644
--- a/client/src/app/+videos/+video-edit/shared/caption/video-caption-edit-modal-content.component.ts
+++ b/client/src/app/+videos/+video-edit/shared/caption/video-caption-edit-modal-content.component.ts
@@ -1,12 +1,12 @@
-import { NgClass, NgForOf, NgIf } from '@angular/common'
-import { AfterViewInit, ChangeDetectorRef, Component, ElementRef, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core'
+import { NgClass, NgIf } from '@angular/common'
+import { AfterViewInit, ChangeDetectorRef, Component, ElementRef, OnInit, inject, input, output, viewChild } from '@angular/core'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { VIDEO_CAPTION_FILE_CONTENT_VALIDATOR } from '@app/shared/form-validators/video-captions-validators'
import { FormReactive } from '@app/shared/shared-forms/form-reactive'
import { FormReactiveService } from '@app/shared/shared-forms/form-reactive.service'
import { PeertubeCheckboxComponent } from '@app/shared/shared-forms/peertube-checkbox.component'
import { TimestampInputComponent } from '@app/shared/shared-forms/timestamp-input.component'
-import { Nl2BrPipe } from '@app/shared/shared-main/common/nl2br.pipe'
+
import { VideoCaptionEdit, VideoCaptionWithPathEdit } from '@app/shared/shared-main/video-caption/video-caption-edit.model'
import { VideoCaptionService } from '@app/shared/shared-main/video-caption/video-caption.service'
import { EmbedComponent } from '@app/shared/shared-main/video/embed.component'
@@ -42,25 +42,30 @@ type Segment = {
GlobalIconComponent,
NgClass,
NgIf,
- NgForOf,
PeertubeCheckboxComponent,
EmbedComponent,
EditButtonComponent,
ButtonComponent,
TimestampInputComponent,
- DeleteButtonComponent,
- Nl2BrPipe
+ DeleteButtonComponent
]
})
export class VideoCaptionEditModalContentComponent extends FormReactive implements OnInit, AfterViewInit {
- @Input() videoCaption: VideoCaptionWithPathEdit
- @Input() serverConfig: HTMLServerConfig
- @Input() publishedVideo: Video
+ protected openedModal = inject(NgbActiveModal)
+ protected formReactiveService = inject(FormReactiveService)
+ private videoCaptionService = inject(VideoCaptionService)
+ private serverService = inject(ServerService)
+ private notifier = inject(Notifier)
+ private cd = inject(ChangeDetectorRef)
+
+ readonly videoCaption = input<VideoCaptionWithPathEdit>(undefined)
+ readonly serverConfig = input<HTMLServerConfig>(undefined)
+ readonly publishedVideo = input<Video>(undefined)
- @Output() captionEdited = new EventEmitter<VideoCaptionEdit>()
+ readonly captionEdited = output<VideoCaptionEdit>()
- @ViewChild('textarea', { static: true }) textarea: ElementRef
- @ViewChild('embed') embed: EmbedComponent
+ readonly textarea = viewChild<ElementRef>('textarea')
+ readonly embed = viewChild<EmbedComponent>('embed')
rawEdit = false
segments: Segment[] = []
@@ -78,17 +83,6 @@ export class VideoCaptionEditModalContentComponent extends FormReactive implemen
private player: PeerTubePlayer
- constructor (
- protected openedModal: NgbActiveModal,
- protected formReactiveService: FormReactiveService,
- private videoCaptionService: VideoCaptionService,
- private serverService: ServerService,
- private notifier: Notifier,
- private cd: ChangeDetectorRef
- ) {
- super()
- }
-
ngOnInit () {
this.serverService.getVideoLanguages().subscribe(languages => {
this.videoCaptionLanguages = languages
@@ -98,12 +92,13 @@ export class VideoCaptionEditModalContentComponent extends FormReactive implemen
this.loadCaptionContent()
- this.openedModal.update({ })
+ this.openedModal.update({})
}
ngAfterViewInit () {
- if (this.embed) {
- this.player = new PeerTubePlayer(this.embed.getIframe())
+ const embed = this.embed()
+ if (embed) {
+ this.player = new PeerTubePlayer(embed.getIframe())
this.player.addEventListener('playbackStatusUpdate', ({ position }) => {
this.activeSegment = undefined
@@ -128,14 +123,15 @@ export class VideoCaptionEditModalContentComponent extends FormReactive implemen
loadCaptionContent () {
this.rawEdit = false
- if (this.videoCaption.action === 'CREATE' || this.videoCaption.action === 'UPDATE') {
- const file = this.videoCaption.captionfile as File
+ const videoCaption = this.videoCaption()
+ if (videoCaption.action === 'CREATE' || videoCaption.action === 'UPDATE') {
+ const file = videoCaption.captionfile as File
file.text().then(content => this.loadSegments(content))
return
}
- const { fileUrl } = this.videoCaption
+ const { fileUrl } = videoCaption
if (!fileUrl) return
this.videoCaptionService.getCaptionContent({ fileUrl })
@@ -293,7 +289,7 @@ export class VideoCaptionEditModalContentComponent extends FormReactive implemen
}
private resetTextarea () {
- const el = this.textarea.nativeElement
+ const el = this.textarea().nativeElement
el.scrollTop = 0
el.selectionStart = 0
@@ -310,7 +306,7 @@ export class VideoCaptionEditModalContentComponent extends FormReactive implemen
return
}
- const languageId = this.videoCaption.language.id
+ const languageId = this.videoCaption().language.id
const languageObject = this.videoCaptionLanguages.find(l => l.id === languageId)
if (this.rawEdit) {
diff --git a/client/src/app/+videos/+video-edit/shared/i18n-primeng-calendar.service.ts b/client/src/app/+videos/+video-edit/shared/i18n-primeng-calendar.service.ts
index 40f25674e9..f85a434062 100644
--- a/client/src/app/+videos/+video-edit/shared/i18n-primeng-calendar.service.ts
+++ b/client/src/app/+videos/+video-edit/shared/i18n-primeng-calendar.service.ts
@@ -1,10 +1,11 @@
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { PrimeNGConfig } from 'primeng/api'
@Injectable()
export class I18nPrimengCalendarService {
+ private config = inject(PrimeNGConfig)
- constructor (private config: PrimeNGConfig) {
+ constructor () {
this.config.setTranslation({
dayNames: [
$localize`Sunday`,
diff --git a/client/src/app/+videos/+video-edit/shared/thumbnail-manager/thumbnail-manager.component.html b/client/src/app/+videos/+video-edit/shared/thumbnail-manager/thumbnail-manager.component.html
index 1c7d1e1e61..baee978342 100644
--- a/client/src/app/+videos/+video-edit/shared/thumbnail-manager/thumbnail-manager.component.html
+++ b/client/src/app/+videos/+video-edit/shared/thumbnail-manager/thumbnail-manager.component.html
@@ -1,7 +1,7 @@
<div class="root">
- @if (video && selectingFromVideo) {
- <my-embed #embed [video]="video" enableAPI="true" mute="true" autoplay="true"></my-embed>
+ @if (video() && selectingFromVideo) {
+ <my-embed #embed [video]="video()" enableAPI="true" mute="true" autoplay="true"></my-embed>
} @else {
<div class="preview-container">
@if (imageSrc) {
diff --git a/client/src/app/+videos/+video-edit/shared/thumbnail-manager/thumbnail-manager.component.ts b/client/src/app/+videos/+video-edit/shared/thumbnail-manager/thumbnail-manager.component.ts
index 33a5f4bf06..ea1098de00 100644
--- a/client/src/app/+videos/+video-edit/shared/thumbnail-manager/thumbnail-manager.component.ts
+++ b/client/src/app/+videos/+video-edit/shared/thumbnail-manager/thumbnail-manager.component.ts
@@ -1,11 +1,5 @@
import { CommonModule } from '@angular/common'
-import {
- Component,
- Input,
- OnInit,
- ViewChild,
- forwardRef
-} from '@angular/core'
+import { Component, OnInit, forwardRef, inject, input, viewChild } from '@angular/core'
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'
import {
ServerService
@@ -31,9 +25,11 @@ import { PeerTubePlayer } from '../../../../../standalone/embed-player-api/playe
]
})
export class ThumbnailManagerComponent implements OnInit, ControlValueAccessor {
- @ViewChild('embed') embed: EmbedComponent
+ private serverService = inject(ServerService)
+
+ readonly embed = viewChild<EmbedComponent>('embed')
- @Input() video: EmbedVideoInput & Pick<Video, 'isLive' | 'state'>
+ readonly video = input<EmbedVideoInput & Pick<Video, 'isLive' | 'state'>>(undefined)
imageSrc: string
allowedExtensionsMessage = ''
@@ -47,9 +43,7 @@ export class ThumbnailManagerComponent implements OnInit, ControlValueAccessor {
player: PeerTubePlayer
- constructor (
- private serverService: ServerService
- ) {
+ constructor () {
this.bytesPipe = new BytesPipe()
this.maxSizeText = $localize`max size`
}
@@ -71,7 +65,8 @@ export class ThumbnailManagerComponent implements OnInit, ControlValueAccessor {
}
canSelectFromVideo () {
- return this.video && !this.video.isLive && this.video.state.id === VideoState.PUBLISHED
+ const video = this.video()
+ return video && !video.isLive && video.state.id === VideoState.PUBLISHED
}
getReactiveFileButtonTooltip () {
@@ -91,7 +86,9 @@ export class ThumbnailManagerComponent implements OnInit, ControlValueAccessor {
this.updatePreview()
}
- propagateChange = (_: any) => { /* empty */ }
+ propagateChange = (_: any) => {
+ // empty
+ }
writeValue (file: any) {
this.imageFile = file
@@ -120,7 +117,7 @@ export class ThumbnailManagerComponent implements OnInit, ControlValueAccessor {
this.selectingFromVideo = true
setTimeout(() => {
- this.player = new PeerTubePlayer(this.embed.getIframe())
+ this.player = new PeerTubePlayer(this.embed().getIframe())
})
}
diff --git a/client/src/app/+videos/+video-edit/shared/video-edit.component.html b/client/src/app/+videos/+video-edit/shared/video-edit.component.html
index 6902b29aad..55fc076f58 100644
--- a/client/src/app/+videos/+video-edit/shared/video-edit.component.html
+++ b/client/src/app/+videos/+video-edit/shared/video-edit.component.html
@@ -1,9 +1,9 @@
-<div class="video-edit" [formGroup]="form">
+<div class="video-edit" [formGroup]="form()">
<div ngbNav #nav="ngbNav" class="nav-tabs">
<ng-template #pluginSettingTemplate let-pluginSetting>
<div class="form-group" [hidden]="isPluginFieldHidden(pluginSetting)">
- <my-dynamic-form-field [form]="pluginDataFormGroup" [formErrors]="formErrors['pluginData']" [setting]="pluginSetting.commonOptions"></my-dynamic-form-field>
+ <my-dynamic-form-field [form]="pluginDataFormGroup" [formErrors]="formErrors()['pluginData']" [setting]="pluginSetting.commonOptions"></my-dynamic-form-field>
</div>
</ng-template>
@@ -16,8 +16,8 @@
<div class="form-group">
<label i18n for="name">Title</label>
<input type="text" id="name" class="form-control" formControlName="name" />
- <div *ngIf="formErrors.name" class="form-error" role="alert">
- {{ formErrors.name }}
+ <div *ngIf="formErrors().name" class="form-error" role="alert">
+ {{ formErrors().name }}
</div>
</div>
@@ -35,8 +35,8 @@
</my-help>
<my-select-tags inputId="label-tags" formControlName="tags" class="d-block w-100"></my-select-tags>
- <div *ngIf="formErrors.tags" class="form-error" role="alert">
- {{ formErrors.tags }}
+ <div *ngIf="formErrors().tags" class="form-error" role="alert">
+ {{ formErrors().tags }}
</div>
</div>
@@ -55,8 +55,8 @@
<my-markdown-textarea
inputId="description"
- formControlName="description" [markdownVideo]="publishedVideo"
- [formError]="formErrors.description" truncateTo3Lines="true" withEmoji="true"
+ formControlName="description" [markdownVideo]="publishedVideo()"
+ [formError]="formErrors().description" truncateTo3Lines="true" withEmoji="true"
></my-markdown-textarea>
</div>
</div>
@@ -64,15 +64,15 @@
<div class="col-video-edit">
<div class="form-group">
<label i18n for="channel">Channel</label>
- <my-select-channel class="d-block" inputId="channel" [items]="userVideoChannels" formControlName="channelId"></my-select-channel>
+ <my-select-channel class="d-block" inputId="channel" [items]="userVideoChannels()" formControlName="channelId"></my-select-channel>
</div>
<div class="form-group">
<label i18n for="category">Category</label>
<my-select-options inputId="category" [items]="videoCategories" formControlName="category" clearable="true"></my-select-options>
- <div *ngIf="formErrors.category" class="form-error" role="alert">
- {{ formErrors.category }}
+ <div *ngIf="formErrors().category" class="form-error" role="alert">
+ {{ formErrors().category }}
</div>
</div>
@@ -89,8 +89,8 @@
<my-select-options inputId="licence" [items]="videoLicences" formControlName="licence" clearable="true"></my-select-options>
- <div *ngIf="formErrors.licence" class="form-error" role="alert">
- {{ formErrors.licence }}
+ <div *ngIf="formErrors().licence" class="form-error" role="alert">
+ {{ formErrors().licence }}
</div>
</div>
@@ -101,8 +101,8 @@
clearable="true" filter="true" virtualScroll="true"
></my-select-options>
- <div *ngIf="formErrors.language" class="form-error" role="alert">
- {{ formErrors.language }}
+ <div *ngIf="formErrors().language" class="form-error" role="alert">
+ {{ formErrors().language }}
</div>
</div>
@@ -110,14 +110,14 @@
<label i18n for="privacy">Privacy</label>
<my-select-options inputId="privacy" [items]="videoPrivacies" formControlName="privacy"></my-select-options>
- <div *ngIf="formErrors.privacy" class="form-error" role="alert">
- {{ formErrors.privacy }}
+ <div *ngIf="formErrors().privacy" class="form-error" role="alert">
+ {{ formErrors().privacy }}
</div>
</div>
<div *ngIf="passwordProtectionSelected" class="form-group">
<label i18n for="videoPassword">Password</label>
- <my-input-text formControlName="videoPassword" inputId="videoPassword" [withCopy]="true" [formError]="formErrors['videoPassword']"></my-input-text>
+ <my-input-text formControlName="videoPassword" inputId="videoPassword" [withCopy]="true" [formError]="formErrors()['videoPassword']"></my-input-text>
</div>
<div *ngIf="schedulePublicationSelected" class="form-group">
@@ -129,8 +129,8 @@
>
</p-calendar>
- <div *ngIf="formErrors.schedulePublicationAt" class="form-error" role="alert">
- {{ formErrors.schedulePublicationAt }}
+ <div *ngIf="formErrors().schedulePublicationAt" class="form-error" role="alert">
+ {{ formErrors().schedulePublicationAt }}
</div>
</div>
@@ -144,7 +144,7 @@
</ng-template>
</my-peertube-checkbox>
- <my-peertube-checkbox *ngIf="!hideWaitTranscoding" inputName="waitTranscoding" formControlName="waitTranscoding" helpPlacement="bottom-right">
+ <my-peertube-checkbox *ngIf="!hideWaitTranscoding()" inputName="waitTranscoding" formControlName="waitTranscoding" helpPlacement="bottom-right">
<ng-template ptTemplate="label">
<ng-container i18n>Publish after transcoding</ng-container>
</ng-template>
@@ -164,16 +164,16 @@
</ng-template>
</ng-container>
- <ng-container ngbNavItem *ngIf="!liveVideo">
+ <ng-container ngbNavItem *ngIf="!liveVideo()">
<a ngbNavLink i18n>Captions</a>
<ng-template ngbNavContent>
<div class="captions">
- <my-alert type="primary" *ngIf="displayTranscriptionInfo && isTranscriptionEnabled() && !hasCaptions()" i18n>
+ <my-alert type="primary" *ngIf="displayTranscriptionInfo() && isTranscriptionEnabled() && !hasCaptions()" i18n>
Subtitles will be automatically generated from your video.
</my-alert>
- <div class="form-group" *ngFor="let videoCaption of videoCaptions">
+ <div class="form-group" *ngFor="let videoCaption of videoCaptions()">
<div class="caption-entry">
@@ -220,7 +220,7 @@
</div>
</div>
- <div i18n class="no-caption" *ngIf="videoCaptions?.length === 0">
+ <div i18n class="no-caption" *ngIf="videoCaptions()?.length === 0">
No captions for now.
</div>
@@ -235,7 +235,7 @@
</ng-template>
</ng-container>
- <ng-container ngbNavItem *ngIf="!liveVideo">
+ <ng-container ngbNavItem *ngIf="!liveVideo()">
<a ngbNavLink i18n>Chapters</a>
<ng-template ngbNavContent>
@@ -263,18 +263,18 @@
<my-timestamp-input
class="d-block" enableBorder="true" [inputName]="'timecode[' + i + ']'"
- [maxTimestamp]="publishedVideo?.duration" formControlName="timecode"
+ [maxTimestamp]="publishedVideo()?.duration" formControlName="timecode"
></my-timestamp-input>
<div>
<input
- [ngClass]="{ 'input-error': formErrors.chapters[i].title }"
+ [ngClass]="{ 'input-error': formErrors().chapters[i].title }"
type="text" [id]="'title[' + i + ']'" [name]="'title[' + i + ']'" formControlName="title"
/>
- <div [ngClass]="{ 'opacity-0': !formErrors.chapters[i].title }" class="form-error" role="alert">
+ <div [ngClass]="{ 'opacity-0': !formErrors().chapters[i].title }" class="form-error" role="alert">
<span class="opacity-0">t</span> <!-- Ensure we have reserve a correct height -->
- {{ formErrors.chapters[i].title }}
+ {{ formErrors().chapters[i].title }}
</div>
</div>
@@ -287,12 +287,12 @@
</div>
</div>
- <my-embed *ngIf="publishedVideo" class="col-md-12 col-xl-6" [video]="publishedVideo"></my-embed>
+ <my-embed *ngIf="publishedVideo()" class="col-md-12 col-xl-6" [video]="publishedVideo()"></my-embed>
</div>
</ng-template>
</ng-container>
- <ng-container ngbNavItem *ngIf="liveVideo">
+ <ng-container ngbNavItem *ngIf="liveVideo()">
<a ngbNavLink i18n>Live settings</a>
<ng-template ngbNavContent>
@@ -302,19 +302,19 @@
<my-live-documentation-link></my-live-documentation-link>
</my-alert>
- <div *ngIf="liveVideo.rtmpUrl" class="form-group">
+ <div *ngIf="liveVideo().rtmpUrl" class="form-group">
<label for="liveVideoRTMPUrl" i18n>Live RTMP Url</label>
- <my-input-text inputId="liveVideoRTMPUrl" [value]="liveVideo.rtmpUrl" [withToggle]="false" [withCopy]="true" [show]="true" [readonly]="true"></my-input-text>
+ <my-input-text inputId="liveVideoRTMPUrl" [value]="liveVideo().rtmpUrl" [withToggle]="false" [withCopy]="true" [show]="true" [readonly]="true"></my-input-text>
</div>
- <div *ngIf="liveVideo.rtmpsUrl" class="form-group">
+ <div *ngIf="liveVideo().rtmpsUrl" class="form-group">
<label for="liveVideoRTMPSUrl" i18n>Live RTMPS Url</label>
- <my-input-text inputId="liveVideoRTMPSUrl" [value]="liveVideo.rtmpsUrl" [withToggle]="false" [withCopy]="true" [show]="true" [readonly]="true"></my-input-text>
+ <my-input-text inputId="liveVideoRTMPSUrl" [value]="liveVideo().rtmpsUrl" [withToggle]="false" [withCopy]="true" [show]="true" [readonly]="true"></my-input-text>
</div>
<div class="form-group">
<label for="liveVideoStreamKey" i18n>Live stream key</label>
- <my-input-text inputId="liveVideoStreamKey" [value]="liveVideo.streamKey" [withCopy]="true" [readonly]="true"></my-input-text>
+ <my-input-text inputId="liveVideoStreamKey" [value]="liveVideo().streamKey" [withCopy]="true" [readonly]="true"></my-input-text>
<div class="form-group-description" i18n>⚠️ Never share your stream key with anyone.</div>
</div>
@@ -360,8 +360,8 @@
<label i18n for="latencyMode">Latency mode</label>
<my-select-options inputId="latencyMode" [items]="latencyModes" formControlName="latencyMode" clearable="true"></my-select-options>
- <div *ngIf="formErrors.latencyMode" class="form-error" role="alert">
- {{ formErrors.latencyMode }}
+ <div *ngIf="formErrors().latencyMode" class="form-error" role="alert">
+ {{ formErrors().latencyMode }}
</div>
</div>
</div>
@@ -382,7 +382,7 @@
<div class="form-group">
<label i18n for="previewfile">Video thumbnail</label>
- <my-thumbnail-manager id="previewfile" formControlName="previewfile" [video]="publishedVideo"></my-thumbnail-manager>
+ <my-thumbnail-manager id="previewfile" formControlName="previewfile" [video]="publishedVideo()"></my-thumbnail-manager>
</div>
<div class="form-group">
@@ -398,14 +398,14 @@
<my-markdown-textarea
inputId="support" formControlName="support" markdownType="enhanced"
- [formError]="formErrors['support']"
+ [formError]="formErrors()['support']"
></my-markdown-textarea>
</div>
</div>
<div class="col-md-12 col-xl-4">
- <div *ngIf="videoSource" class="form-group">
+ <div *ngIf="videoSource()" class="form-group">
<label i18n for="filename">Filename</label>
<my-help>
@@ -416,7 +416,7 @@
</ng-template>
</my-help>
- <input type="text" [disabled]="true" id="filename" class="form-control" [value]="videoSource.filename" />
+ <input type="text" [disabled]="true" id="filename" class="form-control" [value]="videoSource().filename" />
</div>
<div class="form-group originally-published-at">
@@ -439,8 +439,8 @@
>
</p-calendar>
- <div *ngIf="formErrors.originallyPublishedAt" class="form-error" role="alert">
- {{ formErrors.originallyPublishedAt }}
+ <div *ngIf="formErrors().originallyPublishedAt" class="form-error" role="alert">
+ {{ formErrors().originallyPublishedAt }}
</div>
</div>
@@ -453,8 +453,8 @@
<my-select-options inputId="commentsPolicy" [items]="commentPolicies" formControlName="commentsPolicy"></my-select-options>
- <div *ngIf="formErrors.commentsPolicy" class="form-error" role="alert">
- {{ formErrors.commentsPolicy }}
+ <div *ngIf="formErrors().commentsPolicy" class="form-error" role="alert">
+ {{ formErrors().commentsPolicy }}
</div>
</div>
diff --git a/client/src/app/+videos/+video-edit/shared/video-edit.component.ts b/client/src/app/+videos/+video-edit/shared/video-edit.component.ts
index bc4c03b0f8..df2da10599 100644
--- a/client/src/app/+videos/+video-edit/shared/video-edit.component.ts
+++ b/client/src/app/+videos/+video-edit/shared/video-edit.component.ts
@@ -1,16 +1,5 @@
import { NgClass, NgFor, NgIf, NgTemplateOutlet } from '@angular/common'
-import {
- ChangeDetectorRef,
- Component,
- EventEmitter,
- Input,
- NgZone,
- OnDestroy,
- OnInit,
- Output,
- ViewChild,
- booleanAttribute
-} from '@angular/core'
+import { ChangeDetectorRef, Component, NgZone, OnDestroy, OnInit, booleanAttribute, inject, input, output, viewChild } from '@angular/core'
import { AbstractControl, FormArray, FormGroup, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms'
import { RouterLink } from '@angular/router'
import { ConfirmService, HooksService, PluginService, ServerService } from '@app/core'
@@ -131,38 +120,56 @@ type PluginField = {
]
})
export class VideoEditComponent implements OnInit, OnDestroy {
- @Input() form: FormGroup
- @Input() formErrors: FormReactiveErrors & { chapters?: { title: string }[] } = {}
- @Input() validationMessages: FormReactiveValidationMessages = {}
+ private formValidatorService = inject(FormValidatorService)
+ private videoService = inject(VideoService)
+ private serverService = inject(ServerService)
+ private pluginService = inject(PluginService)
+ private instanceService = inject(InstanceService)
+ private i18nPrimengCalendarService = inject(I18nPrimengCalendarService)
+ private ngZone = inject(NgZone)
+ private hooks = inject(HooksService)
+ private cd = inject(ChangeDetectorRef)
+ private modalService = inject(NgbModal)
+ private confirmService = inject(ConfirmService)
+
+ readonly form = input<FormGroup>(undefined)
+ readonly formErrors = input<
+ FormReactiveErrors & {
+ chapters?: {
+ title: string
+ }[]
+ }
+ >({})
+ readonly validationMessages = input<FormReactiveValidationMessages>({})
- @Input() publishedVideo: VideoDetails
+ readonly publishedVideo = input<VideoDetails>(undefined)
- @Input() userVideoChannels: SelectChannelItem[] = []
+ readonly userVideoChannels = input<SelectChannelItem[]>([])
- @Input({ transform: booleanAttribute }) forbidScheduledPublication = true
- @Input({ transform: booleanAttribute }) displayTranscriptionInfo = true
+ readonly forbidScheduledPublication = input(true, { transform: booleanAttribute })
+ readonly displayTranscriptionInfo = input(true, { transform: booleanAttribute })
- @Input() videoCaptions: VideoCaptionWithPathEdit[] = []
- @Input() videoSource: VideoSource
+ readonly videoCaptions = input<VideoCaptionWithPathEdit[]>([])
+ readonly videoSource = input<VideoSource>(undefined)
- @Input() videoChapters: VideoChapter[] = []
+ readonly videoChapters = input<VideoChapter[]>([])
- @Input({ transform: booleanAttribute }) hideWaitTranscoding = false
- @Input({ transform: booleanAttribute }) updateVideoFileEnabled = false
+ readonly hideWaitTranscoding = input(false, { transform: booleanAttribute })
+ readonly updateVideoFileEnabled = input(false, { transform: booleanAttribute })
- @Input() type: VideoEditType
- @Input() liveVideo: LiveVideo
+ readonly type = input<VideoEditType>(undefined)
+ readonly liveVideo = input<LiveVideo>(undefined)
- @ViewChild('videoCaptionAddModal', { static: true }) videoCaptionAddModal: VideoCaptionAddModalComponent
+ readonly videoCaptionAddModal = viewChild<VideoCaptionAddModalComponent>('videoCaptionAddModal')
- @Output() formBuilt = new EventEmitter<void>()
- @Output() pluginFieldsAdded = new EventEmitter<void>()
+ readonly formBuilt = output()
+ readonly pluginFieldsAdded = output()
// So that it can be accessed in the template
readonly SPECIAL_SCHEDULED_PRIVACY = VideoEdit.SPECIAL_SCHEDULED_PRIVACY
- videoPrivacies: VideoConstant<VideoPrivacyType | typeof VideoEdit.SPECIAL_SCHEDULED_PRIVACY > [] = []
- replayPrivacies: VideoConstant<VideoPrivacyType> [] = []
+ videoPrivacies: VideoConstant<VideoPrivacyType | typeof VideoEdit.SPECIAL_SCHEDULED_PRIVACY>[] = []
+ replayPrivacies: VideoConstant<VideoPrivacyType>[] = []
videoCategories: VideoConstant<number>[] = []
videoLicences: VideoConstant<number>[] = []
commentPolicies: VideoConstant<VideoCommentPolicyType>[] = []
@@ -205,19 +212,7 @@ export class VideoEditComponent implements OnInit, OnDestroy {
private firstPatchDone = false
private initialVideoCaptions: string[] = []
- constructor (
- private formValidatorService: FormValidatorService,
- private videoService: VideoService,
- private serverService: ServerService,
- private pluginService: PluginService,
- private instanceService: InstanceService,
- private i18nPrimengCalendarService: I18nPrimengCalendarService,
- private ngZone: NgZone,
- private hooks: HooksService,
- private cd: ChangeDetectorRef,
- private modalService: NgbModal,
- private confirmService: ConfirmService
- ) {
+ constructor () {
this.calendarTimezone = this.i18nPrimengCalendarService.getTimezone()
this.calendarDateFormat = this.i18nPrimengCalendarService.getDateFormat()
}
@@ -256,18 +251,19 @@ export class VideoEditComponent implements OnInit, OnDestroy {
replayPrivacy: null
}
+ const form = this.form()
this.formValidatorService.updateFormGroup(
- this.form,
- this.formErrors,
- this.validationMessages,
+ form,
+ this.formErrors(),
+ this.validationMessages(),
obj,
defaultValues
)
- this.form.addControl('chapters', new FormArray([], VIDEO_CHAPTERS_ARRAY_VALIDATOR.VALIDATORS))
+ form.addControl('chapters', new FormArray([], VIDEO_CHAPTERS_ARRAY_VALIDATOR.VALIDATORS))
this.addNewChapterControl()
- this.form.get('chapters').valueChanges.subscribe((chapters: { title: string, timecode: string }[]) => {
+ form.get('chapters').valueChanges.subscribe((chapters: { title: string, timecode: string }[]) => {
const lastChapter = chapters[chapters.length - 1]
if (lastChapter.title || lastChapter.timecode) {
@@ -290,10 +286,10 @@ export class VideoEditComponent implements OnInit, OnDestroy {
.then(() => this.updatePluginFields())
this.serverService.getVideoCategories()
- .subscribe(res => this.videoCategories = res)
+ .subscribe(res => this.videoCategories = res)
this.serverService.getVideoLicences()
- .subscribe(res => this.videoLicences = res)
+ .subscribe(res => this.videoLicences = res)
this.serverService.getCommentPolicies()
.subscribe(res => this.commentPolicies = res)
@@ -316,11 +312,11 @@ export class VideoEditComponent implements OnInit, OnDestroy {
.subscribe(privacies => {
const videoPrivacies = this.videoService.explainedPrivacyLabels(privacies).videoPrivacies
this.videoPrivacies = videoPrivacies
- this.replayPrivacies = videoPrivacies.filter((privacy) => privacy.id !== VideoPrivacy.PASSWORD_PROTECTED)
+ this.replayPrivacies = videoPrivacies.filter(privacy => privacy.id !== VideoPrivacy.PASSWORD_PROTECTED)
// Can't schedule publication if private privacy is not available (could be deleted by a plugin)
const hasPrivatePrivacy = this.videoPrivacies.some(p => p.id === VideoPrivacy.PRIVATE)
- if (this.forbidScheduledPublication || !hasPrivatePrivacy) return
+ if (this.forbidScheduledPublication() || !hasPrivatePrivacy) return
this.videoPrivacies.push({
id: this.SPECIAL_SCHEDULED_PRIVACY,
@@ -329,20 +325,20 @@ export class VideoEditComponent implements OnInit, OnDestroy {
})
})
- this.initialVideoCaptions = this.videoCaptions.map(c => c.language.id)
+ this.initialVideoCaptions = this.videoCaptions().map(c => c.language.id)
this.ngZone.runOutsideAngular(() => {
this.schedulerInterval = setInterval(() => this.minScheduledDate = new Date(), 1000 * 60) // Update every minute
})
const updateFormForPlugins = (values: any) => {
- this.form.patchValue(values)
+ this.form().patchValue(values)
this.cd.detectChanges()
}
- this.hooks.runAction('action:video-edit.init', 'video-edit', { type: this.type, updateForm: updateFormForPlugins })
+ this.hooks.runAction('action:video-edit.init', 'video-edit', { type: this.type(), updateForm: updateFormForPlugins })
- this.form.valueChanges.subscribe(() => {
- this.hooks.runAction('action:video-edit.form.updated', 'video-edit', { type: this.type, formValues: this.form.value })
+ this.form().valueChanges.subscribe(() => {
+ this.hooks.runAction('action:video-edit.form.updated', 'video-edit', { type: this.type(), formValues: this.form().value })
})
}
@@ -361,19 +357,19 @@ export class VideoEditComponent implements OnInit, OnDestroy {
}
getExistingCaptions () {
- return this.videoCaptions
- .filter(c => c.action !== 'REMOVE')
- .map(c => c.language.id)
+ return this.videoCaptions()
+ .filter(c => c.action !== 'REMOVE')
+ .map(c => c.language.id)
}
onCaptionEdited (caption: VideoCaptionEdit) {
- const existingCaption = this.videoCaptions.find(c => c.language.id === caption.language.id)
+ const existingCaption = this.videoCaptions().find(c => c.language.id === caption.language.id)
// Replace existing caption?
if (existingCaption) {
Object.assign(existingCaption, caption)
} else {
- this.videoCaptions.push(
+ this.videoCaptions().push(
Object.assign(caption, { action: 'CREATE' as 'CREATE' })
)
}
@@ -390,7 +386,7 @@ export class VideoEditComponent implements OnInit, OnDestroy {
// This caption is not on the server, just remove it from our array
if (caption.action === 'CREATE' || caption.action === 'UPDATE') {
- removeElementFromArray(this.videoCaptions, caption)
+ removeElementFromArray(this.videoCaptions(), caption)
return
}
@@ -398,7 +394,7 @@ export class VideoEditComponent implements OnInit, OnDestroy {
}
openAddCaptionModal () {
- this.videoCaptionAddModal.show()
+ this.videoCaptionAddModal().show()
}
openEditCaptionModal (videoCaption: VideoCaptionWithPathEdit) {
@@ -416,7 +412,7 @@ export class VideoEditComponent implements OnInit, OnDestroy {
modalRef.componentInstance.videoCaption = videoCaption
modalRef.componentInstance.serverConfig = this.serverConfig
- modalRef.componentInstance.publishedVideo = this.publishedVideo
+ modalRef.componentInstance.publishedVideo = this.publishedVideo()
modalRef.componentInstance.captionEdited.subscribe(this.onCaptionEdited.bind(this))
}
@@ -427,11 +423,11 @@ export class VideoEditComponent implements OnInit, OnDestroy {
}
isSaveReplayEnabled () {
- return this.form.value['saveReplay'] === true
+ return this.form().value['saveReplay'] === true
}
isPermanentLiveEnabled () {
- return this.form.value['permanentLive'] === true
+ return this.form().value['permanentLive'] === true
}
isLatencyModeEnabled () {
@@ -439,7 +435,7 @@ export class VideoEditComponent implements OnInit, OnDestroy {
}
hasPublicationDate () {
- return !!this.form.value['originallyPublishedAt']
+ return !!this.form().value['originallyPublishedAt']
}
isTranscriptionEnabled () {
@@ -453,7 +449,7 @@ export class VideoEditComponent implements OnInit, OnDestroy {
// ---------------------------------------------------------------------------
resetField (name: string) {
- this.form.patchValue({ [name]: null })
+ this.form().patchValue({ [name]: null })
}
// ---------------------------------------------------------------------------
@@ -462,9 +458,9 @@ export class VideoEditComponent implements OnInit, OnDestroy {
if (typeof pluginField.commonOptions.hidden !== 'function') return false
return pluginField.commonOptions.hidden({
- formValues: this.form.value,
- videoToUpdate: this.publishedVideo,
- liveVideo: this.liveVideo
+ formValues: this.form().value,
+ videoToUpdate: this.publishedVideo(),
+ liveVideo: this.liveVideo()
})
}
@@ -477,7 +473,7 @@ export class VideoEditComponent implements OnInit, OnDestroy {
}
private sortVideoCaptions () {
- this.videoCaptions.sort((v1, v2) => {
+ this.videoCaptions().sort((v1, v2) => {
if (v1.language.label < v2.language.label) return -1
if (v1.language.label === v2.language.label) return 0
@@ -486,11 +482,11 @@ export class VideoEditComponent implements OnInit, OnDestroy {
}
private async updatePluginFields () {
- this.pluginFields = this.pluginService.getRegisteredVideoFormFields(this.type)
+ this.pluginFields = this.pluginService.getRegisteredVideoFormFields(this.type())
if (this.pluginFields.length === 0) return
- const pluginObj: { [ id: string ]: BuildFormValidator } = {}
+ const pluginObj: { [id: string]: BuildFormValidator } = {}
const pluginValidationMessages: FormReactiveValidationMessages = {}
const pluginFormErrors: any = {}
const pluginDefaults: any = {}
@@ -504,7 +500,7 @@ export class VideoEditComponent implements OnInit, OnDestroy {
const validator = async (control: AbstractControl) => {
if (!setting.commonOptions.error) return null
- const error = await setting.commonOptions.error({ formValues: this.form.value, value: control.value })
+ const error = await setting.commonOptions.error({ formValues: this.form().value, value: control.value })
return error?.error ? { [setting.commonOptions.name]: error.text } : null
}
@@ -529,15 +525,15 @@ export class VideoEditComponent implements OnInit, OnDestroy {
pluginDefaults
)
- this.form.addControl('pluginData', this.pluginDataFormGroup)
- this.formErrors['pluginData'] = pluginFormErrors
- this.validationMessages['pluginData'] = pluginValidationMessages
+ this.form().addControl('pluginData', this.pluginDataFormGroup)
+ this.formErrors()['pluginData'] = pluginFormErrors
+ this.validationMessages()['pluginData'] = pluginValidationMessages
this.cd.detectChanges()
this.pluginFieldsAdded.emit()
// Plugins may need other control values to calculate potential errors
- this.form.valueChanges.subscribe(() => this.formValidatorService.updateTreeValidity(this.pluginDataFormGroup))
+ this.form().valueChanges.subscribe(() => this.formValidatorService.updateTreeValidity(this.pluginDataFormGroup))
}
// ---------------------------------------------------------------------------
@@ -554,8 +550,8 @@ export class VideoEditComponent implements OnInit, OnDestroy {
this.formValidatorService.addControlInFormArray({
controlName: 'chapters',
formArray: chaptersFormArray,
- formErrors: this.formErrors,
- validationMessages: this.validationMessages,
+ formErrors: this.formErrors(),
+ validationMessages: this.validationMessages(),
formToBuild: {
timecode: null,
title: VIDEO_CHAPTER_TITLE_VALIDATOR
@@ -567,15 +563,15 @@ export class VideoEditComponent implements OnInit, OnDestroy {
}
getChaptersFormArray () {
- return this.form.controls['chapters'] as FormArray
+ return this.form().controls['chapters'] as FormArray
}
deleteChapterControl (index: number) {
this.formValidatorService.removeControlFromFormArray({
controlName: 'chapters',
formArray: this.getChaptersFormArray(),
- formErrors: this.formErrors,
- validationMessages: this.validationMessages,
+ formErrors: this.formErrors(),
+ validationMessages: this.validationMessages(),
index
})
}
@@ -593,7 +589,7 @@ export class VideoEditComponent implements OnInit, OnDestroy {
this.addNewChapterControl()
}
- this.form.patchValue(chaptersEdit.toFormPatch())
+ this.form().patchValue(chaptersEdit.toFormPatch())
}
getChapterArrayErrors () {
@@ -606,17 +602,16 @@ export class VideoEditComponent implements OnInit, OnDestroy {
private trackPrivacyChange () {
// We will update the schedule input and the wait transcoding checkbox validators
- this.form.controls['privacy']
+ this.form().controls['privacy']
.valueChanges
.pipe(map(res => parseInt(res.toString(), 10)))
.subscribe(
newPrivacyId => {
-
this.schedulePublicationSelected = newPrivacyId === this.SPECIAL_SCHEDULED_PRIVACY
// Value changed
- const scheduleControl = this.form.get('schedulePublicationAt')
- const waitTranscodingControl = this.form.get('waitTranscoding')
+ const scheduleControl = this.form().get('schedulePublicationAt')
+ const waitTranscodingControl = this.form().get('waitTranscoding')
if (this.schedulePublicationSelected) {
scheduleControl.setValidators([ Validators.required ])
@@ -640,7 +635,7 @@ export class VideoEditComponent implements OnInit, OnDestroy {
this.firstPatchDone = true
this.passwordProtectionSelected = newPrivacyId === VideoPrivacy.PASSWORD_PROTECTED
- const videoPasswordControl = this.form.get('videoPassword')
+ const videoPasswordControl = this.form().get('videoPassword')
if (this.passwordProtectionSelected) {
videoPasswordControl.setValidators([ Validators.required ])
@@ -655,21 +650,21 @@ export class VideoEditComponent implements OnInit, OnDestroy {
private trackChannelChange () {
// We will update the "support" field depending on the channel
- this.form.controls['channelId']
+ this.form().controls['channelId']
.valueChanges
.pipe(map(res => parseInt(res.toString(), 10)))
.subscribe(
newChannelId => {
- const oldChannelId = parseInt(this.form.value['channelId'], 10)
+ const oldChannelId = parseInt(this.form().value['channelId'], 10)
// Not initialized yet
if (isNaN(newChannelId)) return
- const newChannel = this.userVideoChannels.find(c => c.id === newChannelId)
+ const newChannel = this.userVideoChannels().find(c => c.id === newChannelId)
if (!newChannel) return
// Wait support field update
setTimeout(() => {
- const currentSupport = this.form.value['support']
+ const currentSupport = this.form().value['support']
// First time we set the channel?
if (isNaN(oldChannelId)) {
@@ -679,7 +674,7 @@ export class VideoEditComponent implements OnInit, OnDestroy {
return
}
- const oldChannel = this.userVideoChannels.find(c => c.id === oldChannelId)
+ const oldChannel = this.userVideoChannels().find(c => c.id === oldChannelId)
if (!newChannel || !oldChannel) {
logger.error('Cannot find new or old channel.')
return
@@ -697,6 +692,6 @@ export class VideoEditComponent implements OnInit, OnDestroy {
}
private updateSupportField (support: string) {
- return this.form.patchValue({ support: support || '' })
+ return this.form().patchValue({ support: support || '' })
}
}
diff --git a/client/src/app/+videos/+video-edit/shared/video-upload.service.ts b/client/src/app/+videos/+video-edit/shared/video-upload.service.ts
index d02da5c5d6..b53f2edcad 100644
--- a/client/src/app/+videos/+video-edit/shared/video-upload.service.ts
+++ b/client/src/app/+videos/+video-edit/shared/video-upload.service.ts
@@ -1,5 +1,5 @@
import { UploaderX, UploadxOptions } from 'ngx-uploadx'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { AuthService, Notifier, ServerService } from '@app/core'
import { UploaderXFormData } from './uploaderx-form-data'
import { getUploadXRetryConfig } from '@app/helpers'
@@ -8,14 +8,9 @@ import { VideoService } from '@app/shared/shared-main/video/video.service'
@Injectable()
export class VideoUploadService {
-
- constructor (
- private server: ServerService,
- private notifier: Notifier,
- private authService: AuthService
- ) {
-
- }
+ private server = inject(ServerService)
+ private notifier = inject(Notifier)
+ private authService = inject(AuthService)
getVideoExtensions () {
return this.server.getHTMLConfig().video.file.extensions
@@ -30,8 +25,9 @@ export class VideoUploadService {
const videoQuotaUsedBytes = bytePipes.transform(quotaUsed, 0)
const videoQuotaBytes = bytePipes.transform(maxQuota, 0)
- // eslint-disable-next-line max-len
- const msg = $localize`Your video quota is exceeded with this video (video size: ${videoSizeBytes}, used: ${videoQuotaUsedBytes}, quota: ${videoQuotaBytes})`
+ const msg =
+ // eslint-disable-next-line max-len
+ $localize`Your video quota is exceeded with this video (video size: ${videoSizeBytes}, used: ${videoQuotaUsedBytes}, quota: ${videoQuotaBytes})`
this.notifier.error(msg)
return false
diff --git a/client/src/app/+videos/+video-edit/video-add-components/drag-drop.directive.ts b/client/src/app/+videos/+video-edit/video-add-components/drag-drop.directive.ts
index a3cdc242ff..0acd942266 100644
--- a/client/src/app/+videos/+video-edit/video-add-components/drag-drop.directive.ts
+++ b/client/src/app/+videos/+video-edit/video-add-components/drag-drop.directive.ts
@@ -1,27 +1,31 @@
-import { Directive, Output, EventEmitter, HostBinding, HostListener } from '@angular/core'
+import { Directive, HostBinding, HostListener, output } from '@angular/core'
@Directive({
selector: '[myDragDrop]',
standalone: true
})
export class DragDropDirective {
- @Output() fileDropped = new EventEmitter<FileList>()
+ readonly fileDropped = output<FileList>()
- @HostBinding('class.dragover') dragover = false
+ @HostBinding('class.dragover')
+ dragover = false
- @HostListener('dragover', [ '$event' ]) onDragOver (e: Event) {
+ @HostListener('dragover', [ '$event' ])
+ onDragOver (e: Event) {
e.preventDefault()
e.stopPropagation()
this.dragover = true
}
- @HostListener('dragleave', [ '$event' ]) public onDragLeave (e: Event) {
+ @HostListener('dragleave', [ '$event' ])
+ public onDragLeave (e: Event) {
e.preventDefault()
e.stopPropagation()
this.dragover = false
}
- @HostListener('drop', [ '$event' ]) public ondrop (e: DragEvent) {
+ @HostListener('drop', [ '$event' ])
+ public ondrop (e: DragEvent) {
e.preventDefault()
e.stopPropagation()
this.dragover = false
diff --git a/client/src/app/+videos/+video-edit/video-add-components/video-go-live.component.ts b/client/src/app/+videos/+video-edit/video-add-components/video-go-live.component.ts
index 36c03bc0c2..8cae1b9889 100644
--- a/client/src/app/+videos/+video-edit/video-add-components/video-go-live.component.ts
+++ b/client/src/app/+videos/+video-edit/video-add-components/video-go-live.component.ts
@@ -1,5 +1,5 @@
import { NgIf } from '@angular/common'
-import { AfterViewInit, Component, EventEmitter, OnInit, Output } from '@angular/core'
+import { AfterViewInit, Component, OnInit, inject, output } from '@angular/core'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { Router } from '@angular/router'
import { AuthService, CanComponentDeactivate, HooksService, Notifier, ServerService } from '@app/core'
@@ -54,8 +54,20 @@ import { VideoSend } from './video-send'
]
})
export class VideoGoLiveComponent extends VideoSend implements OnInit, AfterViewInit, CanComponentDeactivate {
- @Output() firstStepDone = new EventEmitter<string>()
- @Output() firstStepError = new EventEmitter<void>()
+ protected formReactiveService = inject(FormReactiveService)
+ protected loadingBar = inject(LoadingBarService)
+ protected notifier = inject(Notifier)
+ protected authService = inject(AuthService)
+ protected serverService = inject(ServerService)
+ protected videoService = inject(VideoService)
+ protected videoCaptionService = inject(VideoCaptionService)
+ protected videoChapterService = inject(VideoChapterService)
+ private liveVideoService = inject(LiveVideoService)
+ private router = inject(Router)
+ private hooks = inject(HooksService)
+
+ readonly firstStepDone = output<string>()
+ readonly firstStepError = output()
firstStepPermanentLive: boolean
@@ -71,22 +83,6 @@ export class VideoGoLiveComponent extends VideoSend implements OnInit, AfterView
error: string
- constructor (
- protected formReactiveService: FormReactiveService,
- protected loadingBar: LoadingBarService,
- protected notifier: Notifier,
- protected authService: AuthService,
- protected serverService: ServerService,
- protected videoService: VideoService,
- protected videoCaptionService: VideoCaptionService,
- protected videoChapterService: VideoChapterService,
- private liveVideoService: LiveVideoService,
- private router: Router,
- private hooks: HooksService
- ) {
- super()
- }
-
ngOnInit () {
super.ngOnInit()
}
diff --git a/client/src/app/+videos/+video-edit/video-add-components/video-import-torrent.component.ts b/client/src/app/+videos/+video-edit/video-add-components/video-import-torrent.component.ts
index d3d2997876..f68f8247d1 100644
--- a/client/src/app/+videos/+video-edit/video-add-components/video-import-torrent.component.ts
+++ b/client/src/app/+videos/+video-edit/video-add-components/video-import-torrent.component.ts
@@ -1,5 +1,5 @@
import { NgIf } from '@angular/common'
-import { AfterViewInit, Component, ElementRef, EventEmitter, OnInit, Output, ViewChild } from '@angular/core'
+import { AfterViewInit, Component, ElementRef, OnInit, inject, output, viewChild } from '@angular/core'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { Router } from '@angular/router'
import { AuthService, CanComponentDeactivate, HooksService, Notifier, ServerService } from '@app/core'
@@ -52,9 +52,21 @@ import { VideoSend } from './video-send'
]
})
export class VideoImportTorrentComponent extends VideoSend implements OnInit, AfterViewInit, CanComponentDeactivate {
- @Output() firstStepDone = new EventEmitter<string>()
- @Output() firstStepError = new EventEmitter<void>()
- @ViewChild('torrentfileInput') torrentfileInput: ElementRef<HTMLInputElement>
+ protected formReactiveService = inject(FormReactiveService)
+ protected loadingBar = inject(LoadingBarService)
+ protected notifier = inject(Notifier)
+ protected authService = inject(AuthService)
+ protected serverService = inject(ServerService)
+ protected videoService = inject(VideoService)
+ protected videoCaptionService = inject(VideoCaptionService)
+ protected videoChapterService = inject(VideoChapterService)
+ private router = inject(Router)
+ private videoImportService = inject(VideoImportService)
+ private hooks = inject(HooksService)
+
+ readonly firstStepDone = output<string>()
+ readonly firstStepError = output()
+ readonly torrentfileInput = viewChild<ElementRef<HTMLInputElement>>('torrentfileInput')
magnetUri = ''
@@ -65,22 +77,6 @@ export class VideoImportTorrentComponent extends VideoSend implements OnInit, Af
video: VideoEdit
error: string
- constructor (
- protected formReactiveService: FormReactiveService,
- protected loadingBar: LoadingBarService,
- protected notifier: Notifier,
- protected authService: AuthService,
- protected serverService: ServerService,
- protected videoService: VideoService,
- protected videoCaptionService: VideoCaptionService,
- protected videoChapterService: VideoChapterService,
- private router: Router,
- private videoImportService: VideoImportService,
- private hooks: HooksService
- ) {
- super()
- }
-
ngOnInit () {
super.ngOnInit()
}
@@ -98,14 +94,14 @@ export class VideoImportTorrentComponent extends VideoSend implements OnInit, Af
}
fileChange () {
- const torrentfile = this.torrentfileInput.nativeElement.files[0]
+ const torrentfile = this.torrentfileInput().nativeElement.files[0]
if (!torrentfile) return
this.importVideo(torrentfile)
}
setTorrentFile (files: FileList) {
- this.torrentfileInput.nativeElement.files = files
+ this.torrentfileInput().nativeElement.files = files
this.fileChange()
}
diff --git a/client/src/app/+videos/+video-edit/video-add-components/video-import-url.component.ts b/client/src/app/+videos/+video-edit/video-add-components/video-import-url.component.ts
index 6601011465..ab4961316a 100644
--- a/client/src/app/+videos/+video-edit/video-add-components/video-import-url.component.ts
+++ b/client/src/app/+videos/+video-edit/video-add-components/video-import-url.component.ts
@@ -1,5 +1,5 @@
import { NgIf } from '@angular/common'
-import { AfterViewInit, Component, EventEmitter, OnInit, Output, ViewChild } from '@angular/core'
+import { AfterViewInit, Component, OnInit, inject, output, viewChild } from '@angular/core'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { Router, RouterLink } from '@angular/router'
import { AuthService, CanComponentDeactivate, HooksService, Notifier, ServerService } from '@app/core'
@@ -49,10 +49,22 @@ import { VideoSend } from './video-send'
]
})
export class VideoImportUrlComponent extends VideoSend implements OnInit, AfterViewInit, CanComponentDeactivate {
- @ViewChild('videoEdit', { static: false }) videoEditComponent: VideoEditComponent
-
- @Output() firstStepDone = new EventEmitter<string>()
- @Output() firstStepError = new EventEmitter<void>()
+ protected formReactiveService = inject(FormReactiveService)
+ protected loadingBar = inject(LoadingBarService)
+ protected notifier = inject(Notifier)
+ protected authService = inject(AuthService)
+ protected serverService = inject(ServerService)
+ protected videoService = inject(VideoService)
+ protected videoCaptionService = inject(VideoCaptionService)
+ protected videoChapterService = inject(VideoChapterService)
+ private router = inject(Router)
+ private videoImportService = inject(VideoImportService)
+ private hooks = inject(HooksService)
+
+ readonly videoEditComponent = viewChild<VideoEditComponent>('videoEdit')
+
+ readonly firstStepDone = output<string>()
+ readonly firstStepError = output()
targetUrl = ''
@@ -63,22 +75,6 @@ export class VideoImportUrlComponent extends VideoSend implements OnInit, AfterV
video: VideoEdit
error: string
- constructor (
- protected formReactiveService: FormReactiveService,
- protected loadingBar: LoadingBarService,
- protected notifier: Notifier,
- protected authService: AuthService,
- protected serverService: ServerService,
- protected videoService: VideoService,
- protected videoCaptionService: VideoCaptionService,
- protected videoChapterService: VideoChapterService,
- private router: Router,
- private videoImportService: VideoImportService,
- private hooks: HooksService
- ) {
- super()
- }
-
ngOnInit () {
super.ngOnInit()
}
@@ -111,41 +107,41 @@ export class VideoImportUrlComponent extends VideoSend implements OnInit, AfterV
this.loadingBar.useRef().start()
this.videoImportService
- .importVideoUrl(this.targetUrl, videoUpdate)
- .pipe(
- switchMap(previous => {
- return forkJoin([
- this.videoCaptionService.listCaptions(previous.video.uuid),
- this.videoChapterService.getChapters({ videoId: previous.video.uuid }),
- this.videoService.getVideo({ videoId: previous.video.uuid })
- ]).pipe(map(([ videoCaptionsResult, { chapters }, video ]) => ({ videoCaptions: videoCaptionsResult.data, chapters, video })))
- })
- )
- .subscribe({
- next: ({ video, videoCaptions, chapters }) => {
- this.loadingBar.useRef().complete()
- this.firstStepDone.emit(video.name)
- this.isImportingVideo = false
- this.hasImportedVideo = true
-
- this.video = new VideoEdit(video)
- this.video.patch({ privacy: this.firstStepPrivacyId })
-
- this.chaptersEdit.loadFromAPI(chapters)
-
- this.videoCaptions = videoCaptions
-
- hydrateFormFromVideo(this.form, this.video, true)
- setTimeout(() => this.videoEditComponent.patchChapters(this.chaptersEdit))
- },
-
- error: err => {
- this.loadingBar.useRef().complete()
- this.isImportingVideo = false
- this.firstStepError.emit()
- this.notifier.error(err.message)
- }
+ .importVideoUrl(this.targetUrl, videoUpdate)
+ .pipe(
+ switchMap(previous => {
+ return forkJoin([
+ this.videoCaptionService.listCaptions(previous.video.uuid),
+ this.videoChapterService.getChapters({ videoId: previous.video.uuid }),
+ this.videoService.getVideo({ videoId: previous.video.uuid })
+ ]).pipe(map(([ videoCaptionsResult, { chapters }, video ]) => ({ videoCaptions: videoCaptionsResult.data, chapters, video })))
})
+ )
+ .subscribe({
+ next: ({ video, videoCaptions, chapters }) => {
+ this.loadingBar.useRef().complete()
+ this.firstStepDone.emit(video.name)
+ this.isImportingVideo = false
+ this.hasImportedVideo = true
+
+ this.video = new VideoEdit(video)
+ this.video.patch({ privacy: this.firstStepPrivacyId })
+
+ this.chaptersEdit.loadFromAPI(chapters)
+
+ this.videoCaptions = videoCaptions
+
+ hydrateFormFromVideo(this.form, this.video, true)
+ setTimeout(() => this.videoEditComponent().patchChapters(this.chaptersEdit))
+ },
+
+ error: err => {
+ this.loadingBar.useRef().complete()
+ this.isImportingVideo = false
+ this.firstStepError.emit()
+ this.notifier.error(err.message)
+ }
+ })
}
async updateSecondStep () {
@@ -158,19 +154,19 @@ export class VideoImportUrlComponent extends VideoSend implements OnInit, AfterV
// Update the video
this.updateVideoAndCaptionsAndChapters({ video: this.video, captions: this.videoCaptions, chapters: this.chaptersEdit })
- .subscribe({
- next: () => {
- this.isUpdatingVideo = false
- this.notifier.success($localize`Video to import updated.`)
-
- this.router.navigate([ '/my-library', 'video-imports' ])
- },
-
- error: err => {
- this.error = err.message
- scrollToTop()
- logger.error(err)
- }
- })
+ .subscribe({
+ next: () => {
+ this.isUpdatingVideo = false
+ this.notifier.success($localize`Video to import updated.`)
+
+ this.router.navigate([ '/my-library', 'video-imports' ])
+ },
+
+ error: err => {
+ this.error = err.message
+ scrollToTop()
+ logger.error(err)
+ }
+ })
}
}
diff --git a/client/src/app/+videos/+video-edit/video-add-components/video-send.ts b/client/src/app/+videos/+video-edit/video-add-components/video-send.ts
index 5ea962904a..6ffb94dabe 100644
--- a/client/src/app/+videos/+video-edit/video-add-components/video-send.ts
+++ b/client/src/app/+videos/+video-edit/video-add-components/video-send.ts
@@ -1,18 +1,18 @@
-import { catchError, switchMap, tap } from 'rxjs/operators'
-import { SelectChannelItem } from 'src/types/select-options-item.model'
-import { Directive, EventEmitter, OnInit } from '@angular/core'
+import { Directive, OnInit, OutputEmitterRef } from '@angular/core'
import { AuthService, CanComponentDeactivateResult, Notifier, ServerService } from '@app/core'
import { listUserChannelsForSelect } from '@app/helpers'
-import { LoadingBarService } from '@ngx-loading-bar/core'
-import { HTMLServerConfig, VideoConstant, VideoPrivacyType } from '@peertube/peertube-models'
-import { of } from 'rxjs'
+import { FormReactive } from '@app/shared/shared-forms/form-reactive'
import { VideoCaptionEdit } from '@app/shared/shared-main/video-caption/video-caption-edit.model'
import { VideoCaptionService } from '@app/shared/shared-main/video-caption/video-caption.service'
import { VideoChapterService } from '@app/shared/shared-main/video/video-chapter.service'
import { VideoChaptersEdit } from '@app/shared/shared-main/video/video-chapters-edit.model'
import { VideoEdit } from '@app/shared/shared-main/video/video-edit.model'
import { VideoService } from '@app/shared/shared-main/video/video.service'
-import { FormReactive } from '@app/shared/shared-forms/form-reactive'
+import { LoadingBarService } from '@ngx-loading-bar/core'
+import { HTMLServerConfig, VideoConstant, VideoPrivacyType } from '@peertube/peertube-models'
+import { of } from 'rxjs'
+import { catchError, switchMap, tap } from 'rxjs/operators'
+import { SelectChannelItem } from 'src/types/select-options-item.model'
@Directive()
// eslint-disable-next-line @angular-eslint/directive-class-suffix
@@ -25,8 +25,8 @@ export abstract class VideoSend extends FormReactive implements OnInit {
firstStepPrivacyId: VideoPrivacyType
firstStepChannelId: number
- abstract firstStepDone: EventEmitter<string>
- abstract firstStepError: EventEmitter<void>
+ abstract firstStepDone: OutputEmitterRef<string>
+ abstract firstStepError: OutputEmitterRef<void>
protected loadingBar: LoadingBarService
protected notifier: Notifier
@@ -55,17 +55,18 @@ export abstract class VideoSend extends FormReactive implements OnInit {
this.serverConfig = this.serverService.getHTMLConfig()
this.serverService.getVideoPrivacies()
- .subscribe(
- privacies => {
- const defaultPrivacy = this.serverConfig.defaults.publish.privacy
+ .subscribe(
+ privacies => {
+ const defaultPrivacy = this.serverConfig.defaults.publish.privacy
- const { videoPrivacies, defaultPrivacyId } = this.videoService.explainedPrivacyLabels(privacies, defaultPrivacy)
+ const { videoPrivacies, defaultPrivacyId } = this.videoService.explainedPrivacyLabels(privacies, defaultPrivacy)
- this.videoPrivacies = videoPrivacies
- this.firstStepPrivacyId = defaultPrivacyId
+ this.videoPrivacies = videoPrivacies
+ this.firstStepPrivacyId = defaultPrivacyId
- this.highestPrivacy = this.videoService.getHighestAvailablePrivacy(privacies)
- })
+ this.highestPrivacy = this.videoService.getHighestAvailablePrivacy(privacies)
+ }
+ )
}
protected updateVideoAndCaptionsAndChapters (options: {
@@ -78,19 +79,19 @@ export abstract class VideoSend extends FormReactive implements OnInit {
this.loadingBar.useRef().start()
return this.videoService.updateVideo(video)
- .pipe(
- switchMap(() => this.videoCaptionService.updateCaptions(video.uuid, captions)),
- switchMap(() => {
- return chapters
- ? this.videoChapterService.updateChapters(video.uuid, chapters)
- : of(true)
- }),
- tap(() => this.loadingBar.useRef().complete()),
- catchError(err => {
- this.loadingBar.useRef().complete()
- throw err
- })
- )
+ .pipe(
+ switchMap(() => this.videoCaptionService.updateCaptions(video.uuid, captions)),
+ switchMap(() => {
+ return chapters
+ ? this.videoChapterService.updateChapters(video.uuid, chapters)
+ : of(true)
+ }),
+ tap(() => this.loadingBar.useRef().complete()),
+ catchError(err => {
+ this.loadingBar.useRef().complete()
+ throw err
+ })
+ )
}
protected async isFormValid () {
diff --git a/client/src/app/+videos/+video-edit/video-add-components/video-upload.component.ts b/client/src/app/+videos/+video-edit/video-add-components/video-upload.component.ts
index 5d70fbad50..6b2ec8ed98 100644
--- a/client/src/app/+videos/+video-edit/video-add-components/video-upload.component.ts
+++ b/client/src/app/+videos/+video-edit/video-add-components/video-upload.component.ts
@@ -1,6 +1,6 @@
import { NgIf } from '@angular/common'
import { HttpErrorResponse } from '@angular/common/http'
-import { AfterViewInit, Component, ElementRef, EventEmitter, OnDestroy, OnInit, Output, ViewChild } from '@angular/core'
+import { AfterViewInit, Component, ElementRef, OnDestroy, OnInit, inject, output, viewChild } from '@angular/core'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { ActivatedRoute, Router } from '@angular/router'
import { AuthService, CanComponentDeactivate, HooksService, MetaService, Notifier, ServerService, UserService } from '@app/core'
@@ -55,9 +55,25 @@ import { VideoSend } from './video-send'
]
})
export class VideoUploadComponent extends VideoSend implements OnInit, OnDestroy, AfterViewInit, CanComponentDeactivate {
- @Output() firstStepDone = new EventEmitter<string>()
- @Output() firstStepError = new EventEmitter<void>()
- @ViewChild('videofileInput') videofileInput: ElementRef<HTMLInputElement>
+ protected formReactiveService = inject(FormReactiveService)
+ protected loadingBar = inject(LoadingBarService)
+ protected notifier = inject(Notifier)
+ protected authService = inject(AuthService)
+ protected serverService = inject(ServerService)
+ protected videoService = inject(VideoService)
+ protected videoCaptionService = inject(VideoCaptionService)
+ protected videoChapterService = inject(VideoChapterService)
+ private userService = inject(UserService)
+ private router = inject(Router)
+ private hooks = inject(HooksService)
+ private resumableUploadService = inject(UploadxService)
+ private metaService = inject(MetaService)
+ private route = inject(ActivatedRoute)
+ private videoUploadService = inject(VideoUploadService)
+
+ readonly firstStepDone = output<string>()
+ readonly firstStepError = output()
+ readonly videofileInput = viewChild<ElementRef<HTMLInputElement>>('videofileInput')
userVideoQuotaUsed = 0
userVideoQuotaUsedDaily = 0
@@ -86,34 +102,14 @@ export class VideoUploadComponent extends VideoSend implements OnInit, OnDestroy
private uploadServiceSubscription: Subscription
- constructor (
- protected formReactiveService: FormReactiveService,
- protected loadingBar: LoadingBarService,
- protected notifier: Notifier,
- protected authService: AuthService,
- protected serverService: ServerService,
- protected videoService: VideoService,
- protected videoCaptionService: VideoCaptionService,
- protected videoChapterService: VideoChapterService,
- private userService: UserService,
- private router: Router,
- private hooks: HooksService,
- private resumableUploadService: UploadxService,
- private metaService: MetaService,
- private route: ActivatedRoute,
- private videoUploadService: VideoUploadService
- ) {
- super()
- }
-
ngOnInit () {
super.ngOnInit()
this.userService.getMyVideoQuotaUsed()
- .subscribe(data => {
- this.userVideoQuotaUsed = data.videoQuotaUsed
- this.userVideoQuotaUsedDaily = data.videoQuotaUsedDaily
- })
+ .subscribe(data => {
+ this.userVideoQuotaUsed = data.videoQuotaUsed
+ this.userVideoQuotaUsedDaily = data.videoQuotaUsedDaily
+ })
this.uploadServiceSubscription = this.resumableUploadService.events
.subscribe(state => this.onUploadVideoOngoing(state))
@@ -209,9 +205,10 @@ export class VideoUploadComponent extends VideoSend implements OnInit, OnDestroy
}
onFileDropped (files: FileList) {
- this.videofileInput.nativeElement.files = files
+ const videofileInput = this.videofileInput()
+ videofileInput.nativeElement.files = files
- this.onFileChange({ target: this.videofileInput.nativeElement })
+ this.onFileChange({ target: videofileInput.nativeElement })
}
onFileChange (event: Event | { target: HTMLInputElement }) {
@@ -278,25 +275,25 @@ export class VideoUploadComponent extends VideoSend implements OnInit, OnDestroy
this.isUpdatingVideo = true
this.updateVideoAndCaptionsAndChapters({ video, captions: this.videoCaptions, chapters: this.chaptersEdit })
- .subscribe({
- next: () => {
- this.isUpdatingVideo = false
- this.isUploadingVideo = false
-
- this.notifier.success($localize`Video published.`)
- this.router.navigateByUrl(Video.buildWatchUrl(video))
- },
-
- error: err => {
- this.error = err.message
- scrollToTop()
- logger.error(err)
- }
- })
+ .subscribe({
+ next: () => {
+ this.isUpdatingVideo = false
+ this.isUploadingVideo = false
+
+ this.notifier.success($localize`Video published.`)
+ this.router.navigateByUrl(Video.buildWatchUrl(video))
+ },
+
+ error: err => {
+ this.error = err.message
+ scrollToTop()
+ logger.error(err)
+ }
+ })
}
private getInputVideoFile () {
- return this.videofileInput.nativeElement.files[0]
+ return this.videofileInput().nativeElement.files[0]
}
private uploadFile (file: File, previewfile?: File) {
diff --git a/client/src/app/+videos/+video-edit/video-add.component.ts b/client/src/app/+videos/+video-edit/video-add.component.ts
index 95d4f7f8dc..432460643b 100644
--- a/client/src/app/+videos/+video-edit/video-add.component.ts
+++ b/client/src/app/+videos/+video-edit/video-add.component.ts
@@ -1,5 +1,5 @@
import { NgClass, NgIf, NgTemplateOutlet } from '@angular/common'
-import { Component, HostListener, OnInit, ViewChild } from '@angular/core'
+import { Component, HostListener, OnInit, inject, viewChild } from '@angular/core'
import { ActivatedRoute, Router, RouterLink } from '@angular/router'
import {
AuthService,
@@ -45,10 +45,17 @@ import { VideoUploadComponent } from './video-add-components/video-upload.compon
]
})
export class VideoAddComponent implements OnInit, CanComponentDeactivate {
- @ViewChild('videoUpload') videoUpload: VideoUploadComponent
- @ViewChild('videoImportUrl') videoImportUrl: VideoImportUrlComponent
- @ViewChild('videoImportTorrent') videoImportTorrent: VideoImportTorrentComponent
- @ViewChild('videoGoLive') videoGoLive: VideoGoLiveComponent
+ private auth = inject(AuthService)
+ private userService = inject(UserService)
+ private hooks = inject(HooksService)
+ private serverService = inject(ServerService)
+ private route = inject(ActivatedRoute)
+ private router = inject(Router)
+
+ readonly videoUpload = viewChild<VideoUploadComponent>('videoUpload')
+ readonly videoImportUrl = viewChild<VideoImportUrlComponent>('videoImportUrl')
+ readonly videoImportTorrent = viewChild<VideoImportTorrentComponent>('videoImportTorrent')
+ readonly videoGoLive = viewChild<VideoGoLiveComponent>('videoGoLive')
user: AuthUser = null
@@ -69,15 +76,6 @@ export class VideoAddComponent implements OnInit, CanComponentDeactivate {
serverConfig: HTMLServerConfig
- constructor (
- private auth: AuthService,
- private userService: UserService,
- private hooks: HooksService,
- private serverService: ServerService,
- private route: ActivatedRoute,
- private router: Router
- ) {}
-
get isContactFormEnabled () {
return this.serverConfig.email.enabled && this.serverConfig.contactForm.enabled
}
@@ -123,11 +121,14 @@ export class VideoAddComponent implements OnInit, CanComponentDeactivate {
private async buildUploadMessages () {
// eslint-disable-next-line max-len
- const noQuota = $localize`Sorry, the upload feature is disabled for your account. If you want to add videos, an admin must unlock your quota.`
- // eslint-disable-next-line max-len
- const autoBlock = $localize`Uploaded videos are reviewed before publishing for your account. If you want to add videos without moderation review, an admin must turn off your videos auto-block.`
- // eslint-disable-next-line max-len
- const quotaLeftDaily = $localize`Your daily video quota is insufficient. If you want to add more videos, you must wait for 24 hours or an admin must increase your daily quota.`
+ const noQuota =
+ $localize`Sorry, the upload feature is disabled for your account. If you want to add videos, an admin must unlock your quota.`
+ const autoBlock =
+ // eslint-disable-next-line max-len
+ $localize`Uploaded videos are reviewed before publishing for your account. If you want to add videos without moderation review, an admin must turn off your videos auto-block.`
+ const quotaLeftDaily =
+ // eslint-disable-next-line max-len
+ $localize`Your daily video quota is insufficient. If you want to add more videos, you must wait for 24 hours or an admin must increase your daily quota.`
// eslint-disable-next-line max-len
const quotaLeft = $localize`Your video quota is insufficient. If you want to add more videos, an admin must increase your quota.`
@@ -168,10 +169,10 @@ export class VideoAddComponent implements OnInit, CanComponentDeactivate {
}
canDeactivate (): { canDeactivate: boolean, text?: string } {
- if (this.secondStepType === 'upload') return this.videoUpload.canDeactivate()
- if (this.secondStepType === 'import-url') return this.videoImportUrl.canDeactivate()
- if (this.secondStepType === 'import-torrent') return this.videoImportTorrent.canDeactivate()
- if (this.secondStepType === 'go-live') return this.videoGoLive.canDeactivate()
+ if (this.secondStepType === 'upload') return this.videoUpload().canDeactivate()
+ if (this.secondStepType === 'import-url') return this.videoImportUrl().canDeactivate()
+ if (this.secondStepType === 'import-torrent') return this.videoImportTorrent().canDeactivate()
+ if (this.secondStepType === 'go-live') return this.videoGoLive().canDeactivate()
return { canDeactivate: true }
}
diff --git a/client/src/app/+videos/+video-edit/video-update.component.ts b/client/src/app/+videos/+video-edit/video-update.component.ts
index 0bccf0bccd..3ef3275dde 100644
--- a/client/src/app/+videos/+video-edit/video-update.component.ts
+++ b/client/src/app/+videos/+video-edit/video-update.component.ts
@@ -1,6 +1,6 @@
import { NgIf } from '@angular/common'
import { HttpErrorResponse } from '@angular/common/http'
-import { Component, HostListener, OnDestroy, OnInit, ViewChild } from '@angular/core'
+import { Component, HostListener, OnDestroy, OnInit, inject, viewChild } from '@angular/core'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { ActivatedRoute, Router } from '@angular/router'
import { AuthService, CanComponentDeactivate, ConfirmService, Notifier, ServerService, UserService } from '@app/core'
@@ -48,7 +48,23 @@ const debugLogger = debug('peertube:video-update')
]
})
export class VideoUpdateComponent extends FormReactive implements OnInit, OnDestroy, CanComponentDeactivate {
- @ViewChild('videoEdit', { static: false }) videoEditComponent: VideoEditComponent
+ protected formReactiveService = inject(FormReactiveService)
+ private route = inject(ActivatedRoute)
+ private router = inject(Router)
+ private notifier = inject(Notifier)
+ private videoService = inject(VideoService)
+ private loadingBar = inject(LoadingBarService)
+ private videoCaptionService = inject(VideoCaptionService)
+ private videoChapterService = inject(VideoChapterService)
+ private server = inject(ServerService)
+ private liveVideoService = inject(LiveVideoService)
+ private videoUploadService = inject(VideoUploadService)
+ private confirmService = inject(ConfirmService)
+ private auth = inject(AuthService)
+ private userService = inject(UserService)
+ private resumableUploadService = inject(UploadxService)
+
+ readonly videoEditComponent = viewChild<VideoEditComponent>('videoEdit')
videoEdit: VideoEdit
videoDetails: VideoDetails
@@ -77,26 +93,6 @@ export class VideoUpdateComponent extends FormReactive implements OnInit, OnDest
private chaptersEdit = new VideoChaptersEdit()
- constructor (
- protected formReactiveService: FormReactiveService,
- private route: ActivatedRoute,
- private router: Router,
- private notifier: Notifier,
- private videoService: VideoService,
- private loadingBar: LoadingBarService,
- private videoCaptionService: VideoCaptionService,
- private videoChapterService: VideoChapterService,
- private server: ServerService,
- private liveVideoService: LiveVideoService,
- private videoUploadService: VideoUploadService,
- private confirmService: ConfirmService,
- private auth: AuthService,
- private userService: UserService,
- private resumableUploadService: UploadxService
- ) {
- super()
- }
-
ngOnInit () {
this.buildForm({
replaceFile: null
@@ -135,7 +131,7 @@ export class VideoUpdateComponent extends FormReactive implements OnInit, OnDest
onFormBuilt () {
hydrateFormFromVideo(this.form, this.videoEdit, true)
- setTimeout(() => this.videoEditComponent.patchChapters(this.chaptersEdit))
+ setTimeout(() => this.videoEditComponent().patchChapters(this.chaptersEdit))
if (this.liveVideo) {
this.form.patchValue({
@@ -245,27 +241,25 @@ export class VideoUpdateComponent extends FormReactive implements OnInit, OnDest
return this.liveVideoService.updateLive(this.videoEdit.id, liveVideoUpdate)
}),
-
map(() => true),
-
catchError(err => {
this.notifier.error(err.message)
return of(false)
})
)
- .subscribe({
- next: success => {
- this.isUpdatingVideo = false
- this.loadingBar.useRef().complete()
+ .subscribe({
+ next: success => {
+ this.isUpdatingVideo = false
+ this.loadingBar.useRef().complete()
- if (!success) return
+ if (!success) return
- this.updateDone = true
- this.notifier.success($localize`Video updated.`)
- this.router.navigateByUrl(Video.buildWatchUrl(this.videoEdit))
- }
- })
+ this.updateDone = true
+ this.notifier.success($localize`Video updated.`)
+ this.router.navigateByUrl(Video.buildWatchUrl(this.videoEdit))
+ }
+ })
this.replaceFileIfNeeded()
}
@@ -294,7 +288,8 @@ export class VideoUpdateComponent extends FormReactive implements OnInit, OnDest
let blockedWarning = ''
if (willBeBlocked) {
// eslint-disable-next-line max-len
- blockedWarning = ' ' + $localize`Your video will also be automatically blocked since video publication requires manual validation by moderators.`
+ blockedWarning = ' ' +
+ $localize`Your video will also be automatically blocked since video publication requires manual validation by moderators.`
}
const message = $localize`Uploading a new version of your video will completely erase the current version.` +
diff --git a/client/src/app/+videos/+video-edit/video-update.resolver.ts b/client/src/app/+videos/+video-edit/video-update.resolver.ts
index 23719095fa..3bac9b2f30 100644
--- a/client/src/app/+videos/+video-edit/video-update.resolver.ts
+++ b/client/src/app/+videos/+video-edit/video-update.resolver.ts
@@ -1,6 +1,6 @@
import { forkJoin, of } from 'rxjs'
import { map, switchMap } from 'rxjs/operators'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { ActivatedRouteSnapshot } from '@angular/router'
import { AuthService } from '@app/core'
import { listUserChannelsForSelect } from '@app/helpers'
@@ -14,25 +14,29 @@ import { LiveVideoService } from '@app/shared/shared-video-live/live-video.servi
@Injectable()
export class VideoUpdateResolver {
- constructor (
- private videoService: VideoService,
- private liveVideoService: LiveVideoService,
- private authService: AuthService,
- private videoCaptionService: VideoCaptionService,
- private videoChapterService: VideoChapterService,
- private videoPasswordService: VideoPasswordService
- ) {
- }
+ private videoService = inject(VideoService)
+ private liveVideoService = inject(LiveVideoService)
+ private authService = inject(AuthService)
+ private videoCaptionService = inject(VideoCaptionService)
+ private videoChapterService = inject(VideoChapterService)
+ private videoPasswordService = inject(VideoPasswordService)
resolve (route: ActivatedRouteSnapshot) {
const uuid: string = route.params['uuid']
return this.videoService.getVideo({ videoId: uuid })
- .pipe(
- switchMap(video => forkJoin(this.buildVideoObservables(video))),
- map(([ video, videoSource, videoChannels, videoCaptions, videoChapters, liveVideo, videoPassword ]) =>
- ({ video, videoChannels, videoCaptions, videoChapters, videoSource, liveVideo, videoPassword }))
- )
+ .pipe(
+ switchMap(video => forkJoin(this.buildVideoObservables(video))),
+ map(([ video, videoSource, videoChannels, videoCaptions, videoChapters, liveVideo, videoPassword ]) => ({
+ video,
+ videoChannels,
+ videoCaptions,
+ videoChapters,
+ videoSource,
+ liveVideo,
+ videoPassword
+ }))
+ )
}
private buildVideoObservables (video: VideoDetails) {
diff --git a/client/src/app/+videos/+video-watch/shared/action-buttons/action-buttons.component.html b/client/src/app/+videos/+video-watch/shared/action-buttons/action-buttons.component.html
index dd1992b220..6092a04a14 100644
--- a/client/src/app/+videos/+video-watch/shared/action-buttons/action-buttons.component.html
+++ b/client/src/app/+videos/+video-watch/shared/action-buttons/action-buttons.component.html
@@ -1,12 +1,12 @@
<div class="video-actions-rates">
<div class="video-actions justify-content-end">
<my-video-rate
- [video]="video" [videoPassword]="videoPassword" [isUserLoggedIn]="isUserLoggedIn"
+ [video]="video()" [videoPassword]="videoPassword()" [isUserLoggedIn]="isUserLoggedIn()"
(rateUpdated)="onRateUpdated($event)" (userRatingLoaded)="onRateUpdated($event)"
></my-video-rate>
<button
- *ngIf="video.support" (click)="showSupportModal()" (keyup.enter)="showSupportModal()" class="action-button support-button"
+ *ngIf="video().support" (click)="showSupportModal()" (keyup.enter)="showSupportModal()" class="action-button support-button"
[attr.aria-label]="tooltipSupport" [ngbTooltip]="tooltipSupport" placement="bottom auto"
>
<my-global-icon iconName="support" aria-hidden="true"></my-global-icon>
@@ -29,11 +29,11 @@
</button>
<div ngbDropdownMenu>
- <my-video-add-to-playlist [video]="video"></my-video-add-to-playlist>
+ <my-video-add-to-playlist [video]="video()"></my-video-add-to-playlist>
</div>
</div>
- @if (!isUserLoggedIn && !video.isLive) {
+ @if (!isUserLoggedIn() && !video().isLive) {
<button
*ngIf="isVideoDownloadable()" class="action-button action-button-download"
(click)="showDownloadModal()" (keydown.enter)="showDownloadModal()"
@@ -43,11 +43,11 @@
<span class="icon-text d-none d-sm-inline" i18n>DOWNLOAD</span>
</button>
- <my-video-download #videoDownloadModal [videoPassword]="videoPassword"></my-video-download>
+ <my-video-download #videoDownloadModal [videoPassword]="videoPassword()"></my-video-download>
}
<my-video-actions-dropdown
- [video]="video" [videoCaptions]="videoCaptions" [transcriptionWidgetOpened]="transcriptionWidgetOpened"
+ [video]="video()" [videoCaptions]="videoCaptions()" [transcriptionWidgetOpened]="transcriptionWidgetOpened()"
[displayOptions]="videoActionsOptions" (videoRemoved)="onVideoRemoved()"
(showTranscriptionWidget)="showTranscriptionWidget.emit()" (hideTranscriptionWidget)="hideTranscriptionWidget.emit()"
placement="bottom auto" buttonDirection="horizontal" buttonStyled="true"
@@ -57,17 +57,17 @@
<div class="likes-dislikes-bar-outer-container">
<div
- *ngIf="video.likes !== 0 || video.dislikes !== 0" class="likes-dislikes-bar-inner-container"
+ *ngIf="video().likes !== 0 || video().dislikes !== 0" class="likes-dislikes-bar-inner-container"
[ngbTooltip]="likesBarTooltipText" placement="bottom" tabindex="0"
>
<div class="likes-dislikes-bar">
- <div class="likes-bar" [ngClass]="{ 'liked': userRating !== 'none' }" [ngStyle]="{ 'width.%': video.likesPercent }"></div>
+ <div class="likes-bar" [ngClass]="{ 'liked': userRating !== 'none' }" [ngStyle]="{ 'width.%': video().likesPercent }"></div>
</div>
</div>
</div>
</div>
-<ng-container *ngIf="video">
- <my-support-modal #supportModal [name]="video.channel.displayName" [content]="video.support"></my-support-modal>
- <my-video-share #videoShareModal [video]="video" [videoCaptions]="videoCaptions" [playlist]="playlist"></my-video-share>
+<ng-container *ngIf="video()">
+ <my-support-modal #supportModal [name]="video().channel.displayName" [content]="video().support"></my-support-modal>
+ <my-video-share #videoShareModal [video]="video()" [videoCaptions]="videoCaptions()" [playlist]="playlist()"></my-video-share>
</ng-container>
diff --git a/client/src/app/+videos/+video-watch/shared/action-buttons/action-buttons.component.ts b/client/src/app/+videos/+video-watch/shared/action-buttons/action-buttons.component.ts
index b1e7989cab..157693bc12 100644
--- a/client/src/app/+videos/+video-watch/shared/action-buttons/action-buttons.component.ts
+++ b/client/src/app/+videos/+video-watch/shared/action-buttons/action-buttons.component.ts
@@ -1,5 +1,5 @@
import { NgClass, NgIf, NgStyle } from '@angular/common'
-import { Component, EventEmitter, Input, OnChanges, Output, ViewChild } from '@angular/core'
+import { Component, OnChanges, inject, input, output, viewChild } from '@angular/core'
import { RedirectService, ScreenService } from '@app/core'
import { VideoDetails } from '@app/shared/shared-main/video/video-details.model'
import { VideoShareComponent } from '@app/shared/shared-share-modal/video-share.component'
@@ -38,25 +38,28 @@ import { VideoRateComponent } from './video-rate.component'
]
})
export class ActionButtonsComponent implements OnChanges {
- @ViewChild('videoShareModal') videoShareModal: VideoShareComponent
- @ViewChild('supportModal') supportModal: SupportModalComponent
- @ViewChild('videoDownloadModal') videoDownloadModal: VideoDownloadComponent
+ private screenService = inject(ScreenService)
+ private redirectService = inject(RedirectService)
- @Input() video: VideoDetails
- @Input() videoPassword: string
- @Input() videoCaptions: VideoCaption[]
- @Input() playlist: VideoPlaylist
+ readonly videoShareModal = viewChild<VideoShareComponent>('videoShareModal')
+ readonly supportModal = viewChild<SupportModalComponent>('supportModal')
+ readonly videoDownloadModal = viewChild<VideoDownloadComponent>('videoDownloadModal')
- @Input() isUserLoggedIn: boolean
- @Input() isUserOwner: boolean
+ readonly video = input<VideoDetails>(undefined)
+ readonly videoPassword = input<string>(undefined)
+ readonly videoCaptions = input<VideoCaption[]>(undefined)
+ readonly playlist = input<VideoPlaylist>(undefined)
- @Input() transcriptionWidgetOpened: boolean
+ readonly isUserLoggedIn = input<boolean>(undefined)
+ readonly isUserOwner = input<boolean>(undefined)
- @Input() currentTime: number
- @Input() currentPlaylistPosition: number
+ readonly transcriptionWidgetOpened = input<boolean>(undefined)
- @Output() showTranscriptionWidget = new EventEmitter()
- @Output() hideTranscriptionWidget = new EventEmitter()
+ readonly currentTime = input<number>(undefined)
+ readonly currentPlaylistPosition = input<number>(undefined)
+
+ readonly showTranscriptionWidget = output()
+ readonly hideTranscriptionWidget = output()
likesBarTooltipText = ''
@@ -82,15 +85,10 @@ export class ActionButtonsComponent implements OnChanges {
userRating: UserVideoRateType
- constructor (
- private screenService: ScreenService,
- private redirectService: RedirectService
- ) { }
-
ngOnChanges () {
this.setVideoLikesBarTooltipText()
- if (this.isUserLoggedIn) {
+ if (this.isUserLoggedIn()) {
this.videoActionsOptions.download = true
// Hide the tooltips for unlogged users in mobile view, this adds confusion with the popover
@@ -104,19 +102,20 @@ export class ActionButtonsComponent implements OnChanges {
}
showDownloadModal () {
- this.videoDownloadModal.show(this.video, this.videoCaptions)
+ this.videoDownloadModal().show(this.video(), this.videoCaptions())
}
isVideoDownloadable () {
- return this.video && this.video instanceof VideoDetails && this.video.downloadEnabled && !this.video.isLive
+ const video = this.video()
+ return video && video instanceof VideoDetails && video.downloadEnabled && !video.isLive
}
showSupportModal () {
- this.supportModal.show()
+ this.supportModal().show()
}
showShareModal () {
- this.videoShareModal.show(this.currentTime, this.currentPlaylistPosition)
+ this.videoShareModal().show(this.currentTime(), this.currentPlaylistPosition())
}
onRateUpdated (userRating: UserVideoRateType) {
@@ -129,15 +128,15 @@ export class ActionButtonsComponent implements OnChanges {
}
private setVideoLikesBarTooltipText () {
- this.likesBarTooltipText = `${this.video.likes} likes / ${this.video.dislikes} dislikes`
+ this.likesBarTooltipText = `${this.video().likes} likes / ${this.video().dislikes} dislikes`
}
isVideoAddableToPlaylist () {
- const isPasswordProtected = this.video.privacy.id === VideoPrivacy.PASSWORD_PROTECTED
+ const isPasswordProtected = this.video().privacy.id === VideoPrivacy.PASSWORD_PROTECTED
- if (!this.isUserLoggedIn) return false
+ if (!this.isUserLoggedIn()) return false
- if (isPasswordProtected) return this.isUserOwner
+ if (isPasswordProtected) return this.isUserOwner()
return true
}
diff --git a/client/src/app/+videos/+video-watch/shared/action-buttons/video-rate.component.html b/client/src/app/+videos/+video-watch/shared/action-buttons/video-rate.component.html
index 7dd9b36789..6b877a3824 100644
--- a/client/src/app/+videos/+video-watch/shared/action-buttons/video-rate.component.html
+++ b/client/src/app/+videos/+video-watch/shared/action-buttons/video-rate.component.html
@@ -9,7 +9,7 @@
placement="bottom auto"
>
<my-global-icon iconName="like"></my-global-icon>
- <span *ngIf="video.likes" class="count">{{ video.likes }}</span>
+ <span *ngIf="video().likes" class="count">{{ video().likes }}</span>
</button>
<button
@@ -19,5 +19,5 @@
placement="bottom auto"
>
<my-global-icon iconName="dislike"></my-global-icon>
- <span *ngIf="video.dislikes" class="count">{{ video.dislikes }}</span>
+ <span *ngIf="video().dislikes" class="count">{{ video().dislikes }}</span>
</button>
diff --git a/client/src/app/+videos/+video-watch/shared/action-buttons/video-rate.component.ts b/client/src/app/+videos/+video-watch/shared/action-buttons/video-rate.component.ts
index 284c1859b6..d6bae8733d 100644
--- a/client/src/app/+videos/+video-watch/shared/action-buttons/video-rate.component.ts
+++ b/client/src/app/+videos/+video-watch/shared/action-buttons/video-rate.component.ts
@@ -1,5 +1,5 @@
import { Observable } from 'rxjs'
-import { Component, EventEmitter, Input, OnChanges, OnDestroy, OnInit, Output } from '@angular/core'
+import { Component, OnChanges, OnDestroy, OnInit, inject, input, output } from '@angular/core'
import { Notifier, ScreenService, Hotkey, HotkeysService } from '@app/core'
import { UserVideoRateType } from '@peertube/peertube-models'
import { GlobalIconComponent } from '../../../../shared/shared-icons/global-icon.component'
@@ -15,12 +15,17 @@ import { VideoDetails } from '@app/shared/shared-main/video/video-details.model'
imports: [ NgbPopover, NgClass, NgbTooltip, GlobalIconComponent, NgIf ]
})
export class VideoRateComponent implements OnInit, OnChanges, OnDestroy {
- @Input() video: VideoDetails
- @Input() videoPassword: string
- @Input() isUserLoggedIn: boolean
+ private videoService = inject(VideoService)
+ private notifier = inject(Notifier)
+ private hotkeysService = inject(HotkeysService)
+ private screenService = inject(ScreenService)
- @Output() userRatingLoaded = new EventEmitter<UserVideoRateType>()
- @Output() rateUpdated = new EventEmitter<UserVideoRateType>()
+ readonly video = input<VideoDetails>(undefined)
+ readonly videoPassword = input<string>(undefined)
+ readonly isUserLoggedIn = input<boolean>(undefined)
+
+ readonly userRatingLoaded = output<UserVideoRateType>()
+ readonly rateUpdated = output<UserVideoRateType>()
userRating: UserVideoRateType
@@ -29,21 +34,15 @@ export class VideoRateComponent implements OnInit, OnChanges, OnDestroy {
private hotkeys: Hotkey[]
- constructor (
- private videoService: VideoService,
- private notifier: Notifier,
- private hotkeysService: HotkeysService,
- private screenService: ScreenService
- ) { }
-
ngOnInit () {
// Hide the tooltips for unlogged users in mobile view, this adds confusion with the popover
- if (this.isUserLoggedIn || !this.screenService.isInMobileView()) {
+ const isUserLoggedIn = this.isUserLoggedIn()
+ if (isUserLoggedIn || !this.screenService.isInMobileView()) {
this.tooltipLike = $localize`Like this video`
this.tooltipDislike = $localize`Dislike this video`
}
- if (this.isUserLoggedIn) {
+ if (isUserLoggedIn) {
this.hotkeys = [
new Hotkey('Shift+l', () => {
this.setLike()
@@ -69,7 +68,7 @@ export class VideoRateComponent implements OnInit, OnChanges, OnDestroy {
}
setLike () {
- if (this.isUserLoggedIn === false) return
+ if (this.isUserLoggedIn() === false) return
// Already liked this video
if (this.userRating === 'like') this.setRating('none')
@@ -77,7 +76,7 @@ export class VideoRateComponent implements OnInit, OnChanges, OnDestroy {
}
setDislike () {
- if (this.isUserLoggedIn === false) return
+ if (this.isUserLoggedIn() === false) return
// Already disliked this video
if (this.userRating === 'dislike') this.setRating('none')
@@ -85,26 +84,26 @@ export class VideoRateComponent implements OnInit, OnChanges, OnDestroy {
}
getRatePopoverText () {
- if (this.isUserLoggedIn) return undefined
+ if (this.isUserLoggedIn()) return undefined
return $localize`You need to be logged in to rate this video.`
}
private checkUserRating () {
// Unlogged users do not have ratings
- if (this.isUserLoggedIn === false) return
+ if (this.isUserLoggedIn() === false) return
- this.videoService.getUserVideoRating(this.video.uuid)
- .subscribe({
- next: ratingObject => {
- if (!ratingObject) return
+ this.videoService.getUserVideoRating(this.video().uuid)
+ .subscribe({
+ next: ratingObject => {
+ if (!ratingObject) return
- this.userRating = ratingObject.rating
- this.userRatingLoaded.emit(this.userRating)
- },
+ this.userRating = ratingObject.rating
+ this.userRatingLoaded.emit(this.userRating)
+ },
- error: err => this.notifier.error(err.message)
- })
+ error: err => this.notifier.error(err.message)
+ })
}
private setRating (nextRating: UserVideoRateType) {
@@ -114,7 +113,7 @@ export class VideoRateComponent implements OnInit, OnChanges, OnDestroy {
none: this.videoService.unsetVideoLike.bind(this.videoService)
}
- ratingMethods[nextRating](this.video.uuid, this.videoPassword)
+ ratingMethods[nextRating](this.video().uuid, this.videoPassword())
.subscribe({
next: () => {
// Update the video like attribute
@@ -139,9 +138,10 @@ export class VideoRateComponent implements OnInit, OnChanges, OnDestroy {
if (newRating === 'like') likesToIncrement++
if (newRating === 'dislike') dislikesToIncrement++
- this.video.likes += likesToIncrement
- this.video.dislikes += dislikesToIncrement
+ const video = this.video()
+ video.likes += likesToIncrement
+ video.dislikes += dislikesToIncrement
- this.video.buildLikeAndDislikePercents()
+ video.buildLikeAndDislikePercents()
}
}
diff --git a/client/src/app/+videos/+video-watch/shared/comment/video-comment-add.component.html b/client/src/app/+videos/+video-watch/shared/comment/video-comment-add.component.html
index 80ccd23ed7..7f53cffcd7 100644
--- a/client/src/app/+videos/+video-watch/shared/comment/video-comment-add.component.html
+++ b/client/src/app/+videos/+video-watch/shared/comment/video-comment-add.component.html
@@ -1,11 +1,11 @@
<form novalidate [formGroup]="form" (ngSubmit)="formValidated()">
<div class="avatar-and-textarea">
- <my-actor-avatar [actor]="user?.account" [actorType]="getAvatarActorType()" size="25"></my-actor-avatar>
+ <my-actor-avatar [actor]="user()?.account" [actorType]="getAvatarActorType()" size="25"></my-actor-avatar>
<div class="textarea-wrapper">
<textarea
i18n-placeholder placeholder="Add comment..." myAutoResize
- [readonly]="(user === null) ? true : false"
+ [readonly]="(user() === null) ? true : false"
(click)="openVisitorModal($event)"
formControlName="text" [ngClass]="{ 'input-error': formErrors['text'] }"
(keyup.control.enter)="onValidKey()" (keyup.meta.enter)="onValidKey()" #textarea
diff --git a/client/src/app/+videos/+video-watch/shared/comment/video-comment-add.component.ts b/client/src/app/+videos/+video-watch/shared/comment/video-comment-add.component.ts
index 533b2fd7f8..6c78ba90b4 100644
--- a/client/src/app/+videos/+video-watch/shared/comment/video-comment-add.component.ts
+++ b/client/src/app/+videos/+video-watch/shared/comment/video-comment-add.component.ts
@@ -1,17 +1,5 @@
import { getLocaleDirection, NgClass, NgFor, NgIf } from '@angular/common'
-import {
- Component,
- ElementRef,
- EventEmitter,
- Inject,
- Input,
- LOCALE_ID,
- OnChanges,
- OnInit,
- Output,
- SimpleChanges,
- ViewChild
-} from '@angular/core'
+import { Component, ElementRef, LOCALE_ID, OnChanges, OnInit, SimpleChanges, inject, input, output, viewChild } from '@angular/core'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { Notifier, User } from '@app/core'
import { VIDEO_COMMENT_TEXT_VALIDATOR } from '@app/shared/form-validators/video-comment-validators'
@@ -51,43 +39,39 @@ import { RemoteSubscribeComponent } from '../../../../shared/shared-user-subscri
]
})
export class VideoCommentAddComponent extends FormReactive implements OnChanges, OnInit {
- @Input() user: User
- @Input() video: Video
- @Input() videoPassword: string
- @Input() parentComment?: VideoComment
- @Input() parentComments?: VideoComment[]
- @Input() focusOnInit = false
- @Input() textValue?: string
-
- @Output() commentCreated = new EventEmitter<VideoComment>()
- @Output() cancelEdit = new EventEmitter()
-
- @ViewChild('visitorModal', { static: true }) visitorModal: NgbModal
- @ViewChild('emojiModal', { static: true }) emojiModal: NgbModal
- @ViewChild('textarea', { static: true }) textareaElement: ElementRef
+ protected formReactiveService = inject(FormReactiveService)
+ private notifier = inject(Notifier)
+ private videoCommentService = inject(VideoCommentService)
+ private modalService = inject(NgbModal)
+ private localeId = inject(LOCALE_ID)
+
+ readonly user = input<User>(undefined)
+ readonly video = input<Video>(undefined)
+ readonly videoPassword = input<string>(undefined)
+ readonly parentComment = input<VideoComment>(undefined)
+ readonly parentComments = input<VideoComment[]>(undefined)
+ readonly focusOnInit = input(false)
+ readonly textValue = input<string>(undefined)
+
+ readonly commentCreated = output<VideoComment>()
+ readonly cancelEdit = output()
+
+ readonly visitorModal = viewChild<NgbModal>('visitorModal')
+ readonly emojiModal = viewChild<NgbModal>('emojiModal')
+ readonly textareaElement = viewChild<ElementRef>('textarea')
addingComment = false
addingCommentButtonValue: string
private emojiMarkupList: { emoji: string, name: string }[]
- constructor (
- protected formReactiveService: FormReactiveService,
- private notifier: Notifier,
- private videoCommentService: VideoCommentService,
- private modalService: NgbModal,
- @Inject(LOCALE_ID) private localeId: string
- ) {
- super()
- }
-
ngOnInit () {
this.buildForm({
text: VIDEO_COMMENT_TEXT_VALIDATOR
})
- if (this.user) {
- if (!this.parentComment) {
+ if (this.user()) {
+ if (!this.parentComment()) {
this.addingCommentButtonValue = $localize`Comment`
} else {
this.addingCommentButtonValue = $localize`Reply`
@@ -128,18 +112,18 @@ export class VideoCommentAddComponent extends FormReactive implements OnChanges,
}
openVisitorModal (event: any) {
- if (this.user === null) { // we only open it for visitors
+ if (this.user() === null) { // we only open it for visitors
// fixing ng-bootstrap ModalService and the "Expression Changed After It Has Been Checked" Error
event.srcElement.blur()
event.preventDefault()
- this.modalService.open(this.visitorModal)
+ this.modalService.open(this.visitorModal())
}
}
openEmojiModal (event: any) {
event.preventDefault()
- this.modalService.open(this.emojiModal, { backdrop: true, size: 'lg' })
+ this.modalService.open(this.emojiModal(), { backdrop: true, size: 'lg' })
}
hideModals () {
@@ -155,7 +139,7 @@ export class VideoCommentAddComponent extends FormReactive implements OnChanges,
const commentCreate: VideoCommentCreate = this.form.value
let obs: Observable<VideoComment>
- if (this.parentComment) {
+ if (this.parentComment()) {
obs = this.addCommentReply(commentCreate)
} else {
obs = this.addCommentThread(commentCreate)
@@ -186,7 +170,7 @@ export class VideoCommentAddComponent extends FormReactive implements OnChanges,
cancelCommentReply () {
this.cancelEdit.emit(null)
- this.form.value['text'] = this.textareaElement.nativeElement.value = ''
+ this.form.value['text'] = this.textareaElement().nativeElement.value = ''
}
isRTL () {
@@ -194,7 +178,7 @@ export class VideoCommentAddComponent extends FormReactive implements OnChanges,
}
getAvatarActorType () {
- if (this.user) return 'account'
+ if (this.user()) return 'account'
return 'unlogged'
}
@@ -202,47 +186,48 @@ export class VideoCommentAddComponent extends FormReactive implements OnChanges,
private addCommentReply (commentCreate: VideoCommentCreate) {
return this.videoCommentService
.addCommentReply({
- videoId: this.video.uuid,
- inReplyToCommentId: this.parentComment.id,
+ videoId: this.video().uuid,
+ inReplyToCommentId: this.parentComment().id,
comment: commentCreate,
- videoPassword: this.videoPassword
+ videoPassword: this.videoPassword()
})
}
private addCommentThread (commentCreate: VideoCommentCreate) {
return this.videoCommentService
- .addCommentThread(this.video.uuid, commentCreate, this.videoPassword)
+ .addCommentThread(this.video().uuid, commentCreate, this.videoPassword())
}
private initTextValue () {
- if (this.textValue) {
- this.patchTextValue(this.textValue, this.focusOnInit)
+ const textValue = this.textValue()
+ if (textValue) {
+ this.patchTextValue(textValue, this.focusOnInit())
return
}
- if (this.parentComment) {
- const mentions = this.parentComments
- .filter(c => c.account && c.account.id !== this.user.account.id) // Don't add mention of ourselves
+ if (this.parentComment()) {
+ const mentions = this.parentComments()
+ .filter(c => c.account && c.account.id !== this.user().account.id) // Don't add mention of ourselves
.map(c => '@' + c.by)
const mentionsSet = new Set(mentions)
const mentionsText = Array.from(mentionsSet).join(' ') + ' '
- this.patchTextValue(mentionsText, this.focusOnInit)
+ this.patchTextValue(mentionsText, this.focusOnInit())
}
}
private patchTextValue (text: string, focus: boolean) {
setTimeout(() => {
if (focus) {
- this.textareaElement.nativeElement.focus()
+ this.textareaElement().nativeElement.focus()
}
// Scroll to textarea
- this.textareaElement.nativeElement.scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'nearest' })
+ this.textareaElement().nativeElement.scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'nearest' })
// Use the native textarea autosize according to the text's break lines
- this.textareaElement.nativeElement.dispatchEvent(new Event('input'))
+ this.textareaElement().nativeElement.dispatchEvent(new Event('input'))
})
this.form.patchValue({ text })
diff --git a/client/src/app/+videos/+video-watch/shared/comment/video-comment.component.html b/client/src/app/+videos/+video-watch/shared/comment/video-comment.component.html
index 0302940b20..0bb8af9a2c 100644
--- a/client/src/app/+videos/+video-watch/shared/comment/video-comment.component.html
+++ b/client/src/app/+videos/+video-watch/shared/comment/video-comment.component.html
@@ -1,34 +1,34 @@
<div *ngIf="isCommentDisplayed()" class="root-comment" [ngClass]="{ 'is-child': isChild() }">
<div class="left">
<my-actor-avatar
- *ngIf="!comment.isDeleted" [href]="comment.account.url"
- [actor]="comment.account" actorType="account" [size]="isChild() ? '25' : '36'"
+ *ngIf="!comment().isDeleted" [href]="comment().account.url"
+ [actor]="comment().account" actorType="account" [size]="isChild() ? '25' : '36'"
></my-actor-avatar>
<div class="vertical-border"></div>
</div>
- <div class="right" [ngClass]="{ 'mb-3': firstInThread }">
+ <div class="right" [ngClass]="{ 'mb-3': firstInThread() }">
<div class="comment">
- <ng-container *ngIf="!comment.isDeleted">
- <div *ngIf="highlightedComment === true" class="highlighted-comment" i18n>Highlighted comment</div>
+ <ng-container *ngIf="!comment().isDeleted">
+ <div *ngIf="highlightedComment() === true" class="highlighted-comment" i18n>Highlighted comment</div>
<div class="comment-account-date">
<div class="comment-account">
- <a [routerLink]="[ '/a', comment.by ]">
- <span class="comment-account-name" [ngClass]="{ 'video-author': video.account.id === comment.account.id }">
- {{ comment.account.displayName }}
+ <a [routerLink]="[ '/a', comment().by ]">
+ <span class="comment-account-name" [ngClass]="{ 'video-author': video().account.id === comment().account.id }">
+ {{ comment().account.displayName }}
</span>
- <span class="comment-account-fid ms-1">{{ comment.by }}</span>
+ <span class="comment-account-fid ms-1">{{ comment().by }}</span>
</a>
</div>
- <a [routerLink]="['/w', video.shortUUID, { 'threadId': comment.threadId }]" class="comment-date" [title]="comment.createdAt">
- {{ comment.createdAt | myFromNow }}
+ <a [routerLink]="['/w', video().shortUUID, { 'threadId': comment().threadId }]" class="comment-date" [title]="comment().createdAt">
+ {{ comment().createdAt | myFromNow }}
</a>
- <span *ngIf="comment.heldForReview" class="pt-badge badge-red ms-2" i18n>Pending review</span>
+ <span *ngIf="comment().heldForReview" class="pt-badge badge-red ms-2" i18n>Pending review</span>
</div>
<div
@@ -48,11 +48,11 @@
</div>
</ng-container>
- <ng-container *ngIf="comment.isDeleted">
+ <ng-container *ngIf="comment().isDeleted">
<div class="comment-account-date">
<span class="comment-account" i18n>Deleted</span>
- <a [routerLink]="['/w', video.shortUUID, { 'threadId': comment.threadId }]"
- class="comment-date">{{ comment.createdAt | myFromNow }}</a>
+ <a [routerLink]="['/w', video().shortUUID, { 'threadId': comment().threadId }]"
+ class="comment-date">{{ comment().createdAt | myFromNow }}</a>
</div>
<div class="comment-html comment-html-deleted">
@@ -61,25 +61,25 @@
</ng-container>
<my-video-comment-add
- *ngIf="!comment.isDeleted && inReplyToCommentId === comment.id"
+ *ngIf="!comment().isDeleted && inReplyToCommentId() === comment().id"
[user]="user"
- [video]="video"
- [videoPassword]="videoPassword"
- [parentComment]="comment"
+ [video]="video()"
+ [videoPassword]="videoPassword()"
+ [parentComment]="comment()"
[parentComments]="newParentComments"
[focusOnInit]="true"
(commentCreated)="onCommentReplyCreated($event)"
(cancelEdit)="onResetReply()"
- [textValue]="redraftValue"
+ [textValue]="redraftValue()"
></my-video-comment-add>
- <div *ngIf="commentTree">
- <div *ngFor="let commentChild of commentTree.children">
+ <div *ngIf="commentTree()">
+ <div *ngFor="let commentChild of commentTree().children">
<my-video-comment
[comment]="commentChild.comment"
- [video]="video"
- [videoPassword]="videoPassword"
- [inReplyToCommentId]="inReplyToCommentId"
+ [video]="video()"
+ [videoPassword]="videoPassword()"
+ [inReplyToCommentId]="inReplyToCommentId()"
[commentTree]="commentChild"
[parentComments]="newParentComments"
(wantedToReply)="onWantToReply($event)"
@@ -88,7 +88,7 @@
(wantedToApprove)="onWantToApprove($event)"
(resetReply)="onResetReply()"
(timestampClicked)="handleTimestampClicked($event)"
- [redraftValue]="redraftValue"
+ [redraftValue]="redraftValue()"
></my-video-comment>
</div>
</div>
@@ -99,5 +99,5 @@
</div>
<ng-container *ngIf="prependModerationActions">
- <my-comment-report #commentReportModal [comment]="comment"></my-comment-report>
+ <my-comment-report #commentReportModal [comment]="comment()"></my-comment-report>
</ng-container>
diff --git a/client/src/app/+videos/+video-watch/shared/comment/video-comment.component.ts b/client/src/app/+videos/+video-watch/shared/comment/video-comment.component.ts
index 5c730d45e9..1475bc4a25 100644
--- a/client/src/app/+videos/+video-watch/shared/comment/video-comment.component.ts
+++ b/client/src/app/+videos/+video-watch/shared/comment/video-comment.component.ts
@@ -1,5 +1,5 @@
import { NgClass, NgFor, NgIf } from '@angular/common'
-import { Component, EventEmitter, Input, OnChanges, OnInit, Output, ViewChild } from '@angular/core'
+import { Component, OnChanges, OnInit, inject, input, model, output, viewChild } from '@angular/core'
import { RouterLink } from '@angular/router'
import { MarkdownService, Notifier, UserService } from '@app/core'
import { AuthService } from '@app/core/auth'
@@ -34,25 +34,30 @@ import { VideoCommentAddComponent } from './video-comment-add.component'
]
})
export class VideoCommentComponent implements OnInit, OnChanges {
- @ViewChild('commentReportModal') commentReportModal: CommentReportComponent
-
- @Input() video: Video
- @Input() videoPassword: string
- @Input() comment: VideoComment
- @Input() parentComments: VideoComment[] = []
- @Input() commentTree: VideoCommentThreadTree
- @Input() inReplyToCommentId: number
- @Input() highlightedComment = false
- @Input() firstInThread = false
- @Input() redraftValue?: string
-
- @Output() wantedToReply = new EventEmitter<VideoComment>()
- @Output() wantedToDelete = new EventEmitter<VideoComment>()
- @Output() wantedToApprove = new EventEmitter<VideoComment>()
- @Output() wantedToRedraft = new EventEmitter<VideoComment>()
- @Output() threadCreated = new EventEmitter<VideoCommentThreadTree>()
- @Output() resetReply = new EventEmitter()
- @Output() timestampClicked = new EventEmitter<number>()
+ private markdownService = inject(MarkdownService)
+ private authService = inject(AuthService)
+ private userService = inject(UserService)
+ private notifier = inject(Notifier)
+
+ readonly commentReportModal = viewChild<CommentReportComponent>('commentReportModal')
+
+ readonly video = input<Video>(undefined)
+ readonly videoPassword = input<string>(undefined)
+ readonly comment = input<VideoComment>(undefined)
+ readonly parentComments = input<VideoComment[]>([])
+ readonly inReplyToCommentId = input<number>(undefined)
+ readonly highlightedComment = input(false)
+ readonly firstInThread = input(false)
+ readonly commentTree = model<VideoCommentThreadTree>(undefined)
+ readonly redraftValue = model<string>(undefined)
+
+ readonly wantedToReply = output<VideoComment>()
+ readonly wantedToDelete = output<VideoComment>()
+ readonly wantedToApprove = output<VideoComment>()
+ readonly wantedToRedraft = output<VideoComment>()
+ readonly threadCreated = output<VideoCommentThreadTree>()
+ readonly resetReply = output()
+ readonly timestampClicked = output<number>()
prependModerationActions: DropdownAction<any>[]
@@ -62,13 +67,6 @@ export class VideoCommentComponent implements OnInit, OnChanges {
commentAccount: Account
commentUser: User
- constructor (
- private markdownService: MarkdownService,
- private authService: AuthService,
- private userService: UserService,
- private notifier: Notifier
- ) {}
-
get user () {
return this.authService.getUser()
}
@@ -82,17 +80,18 @@ export class VideoCommentComponent implements OnInit, OnChanges {
}
onCommentReplyCreated (createdComment: VideoComment) {
- if (!this.commentTree) {
- this.commentTree = {
- comment: this.comment,
+ const commentTree = this.commentTree()
+ if (!commentTree) {
+ this.commentTree.set({
+ comment: this.comment(),
hasDisplayedChildren: false,
children: []
- }
+ })
- this.threadCreated.emit(this.commentTree)
+ this.threadCreated.emit(commentTree)
}
- this.commentTree.children.unshift({
+ commentTree.children.unshift({
comment: createdComment,
hasDisplayedChildren: false,
children: []
@@ -100,23 +99,23 @@ export class VideoCommentComponent implements OnInit, OnChanges {
this.resetReply.emit()
- this.redraftValue = undefined
+ this.redraftValue.set(undefined)
}
onWantToReply (comment?: VideoComment) {
- this.wantedToReply.emit(comment || this.comment)
+ this.wantedToReply.emit(comment || this.comment())
}
onWantToDelete (comment?: VideoComment) {
- this.wantedToDelete.emit(comment || this.comment)
+ this.wantedToDelete.emit(comment || this.comment())
}
onWantToRedraft (comment?: VideoComment) {
- this.wantedToRedraft.emit(comment || this.comment)
+ this.wantedToRedraft.emit(comment || this.comment())
}
onWantToApprove (comment?: VideoComment) {
- this.wantedToApprove.emit(comment || this.comment)
+ this.wantedToApprove.emit(comment || this.comment())
}
isUserLoggedIn () {
@@ -132,49 +131,53 @@ export class VideoCommentComponent implements OnInit, OnChanges {
}
canBeRemovedUser () {
- return this.comment.account && this.isUserLoggedIn() &&
+ const comment = this.comment()
+ return comment.account && this.isUserLoggedIn() &&
(
- this.user.account.id === this.comment.account.id ||
- this.user.account.id === this.video.account.id ||
+ this.user.account.id === comment.account.id ||
+ this.user.account.id === this.video().account.id ||
this.user.hasRight(UserRight.MANAGE_ANY_VIDEO_COMMENT)
)
}
canBeApprovedByUser () {
- return this.comment.account && this.isUserLoggedIn() &&
+ return this.comment().account && this.isUserLoggedIn() &&
(
- this.user.account.id === this.video.account.id ||
+ this.user.account.id === this.video().account.id ||
this.user.hasRight(UserRight.MANAGE_ANY_VIDEO_COMMENT)
)
}
isRedraftableByUser () {
+ const comment = this.comment()
return (
- this.comment.account &&
+ comment.account &&
this.isUserLoggedIn() &&
- this.user.account.id === this.comment.account.id &&
- this.comment.totalReplies === 0
+ this.user.account.id === comment.account.id &&
+ comment.totalReplies === 0
)
}
isReportableByUser () {
+ const comment = this.comment()
return (
- this.comment.account &&
+ comment.account &&
this.isUserLoggedIn() &&
- this.comment.isDeleted === false &&
- this.user.account.id !== this.comment.account.id
+ comment.isDeleted === false &&
+ this.user.account.id !== comment.account.id
)
}
isCommentDisplayed () {
// Not deleted
- return !this.comment.isDeleted ||
- this.comment.totalReplies !== 0 || // Or root comment thread has replies
- (this.commentTree?.hasDisplayedChildren) // Or this is a reply that have other replies
+ const comment = this.comment()
+ return !comment.isDeleted ||
+ comment.totalReplies !== 0 || // Or root comment thread has replies
+ (this.commentTree()?.hasDisplayedChildren) // Or this is a reply that have other replies
}
isChild () {
- return this.parentComments.length !== 0
+ return this.parentComments().length !== 0
}
private getUserIfNeeded (account: Account) {
@@ -184,31 +187,32 @@ export class VideoCommentComponent implements OnInit, OnChanges {
const user = this.authService.getUser()
if (user.hasRight(UserRight.MANAGE_USERS)) {
this.userService.getUserWithCache(account.userId)
- .subscribe({
- next: user => this.commentUser = user,
+ .subscribe({
+ next: user => this.commentUser = user,
- error: err => this.notifier.error(err.message)
- })
+ error: err => this.notifier.error(err.message)
+ })
}
}
private async init () {
// Before HTML rendering restore line feed for markdown list compatibility
- const commentText = this.comment.text.replace(/<br.?\/?>/g, '\r\n')
+ const commentText = this.comment().text.replace(/<br.?\/?>/g, '\r\n')
const html = await this.markdownService.textMarkdownToHTML({ markdown: commentText, withHtml: true, withEmoji: true })
- this.sanitizedCommentHTML = this.markdownService.processVideoTimestamps(this.video.shortUUID, html)
- this.newParentComments = this.parentComments.concat([ this.comment ])
+ this.sanitizedCommentHTML = this.markdownService.processVideoTimestamps(this.video().shortUUID, html)
+ this.newParentComments = this.parentComments().concat([ this.comment() ])
- if (this.comment.account) {
- this.commentAccount = new Account(this.comment.account)
+ const comment = this.comment()
+ if (comment.account) {
+ this.commentAccount = new Account(comment.account)
this.getUserIfNeeded(this.commentAccount)
} else {
- this.comment.account = null
+ comment.account = null
}
this.prependModerationActions = []
- if (this.canBeApprovedByUser() && this.comment.heldForReview) {
+ if (this.canBeApprovedByUser() && comment.heldForReview) {
this.prependModerationActions.push({
label: $localize`Approve`,
iconName: 'tick',
@@ -249,6 +253,6 @@ export class VideoCommentComponent implements OnInit, OnChanges {
}
private showReportModal () {
- this.commentReportModal.show()
+ this.commentReportModal().show()
}
}
diff --git a/client/src/app/+videos/+video-watch/shared/comment/video-comments.component.html b/client/src/app/+videos/+video-watch/shared/comment/video-comments.component.html
index 1eea9f3fd0..781658f61e 100644
--- a/client/src/app/+videos/+video-watch/shared/comment/video-comments.component.html
+++ b/client/src/app/+videos/+video-watch/shared/comment/video-comments.component.html
@@ -20,9 +20,9 @@
@if (commentsEnabled) {
<my-video-comment-add
- [video]="video"
- [videoPassword]="videoPassword"
- [user]="user"
+ [video]="video()"
+ [videoPassword]="videoPassword()"
+ [user]="user()"
(commentCreated)="onCommentThreadCreated($event)"
[textValue]="commentThreadRedraftValue"
></my-video-comment-add>
@@ -35,8 +35,8 @@
<my-video-comment
*ngIf="highlightedThread"
[comment]="highlightedThread"
- [video]="video"
- [videoPassword]="videoPassword"
+ [video]="video()"
+ [videoPassword]="videoPassword()"
[inReplyToCommentId]="inReplyToCommentId"
[commentTree]="threadComments[highlightedThread.id]"
[highlightedComment]="true"
@@ -56,8 +56,8 @@
<my-video-comment
*ngIf="!highlightedThread || comment.id !== highlightedThread.id"
[comment]="comment"
- [video]="video"
- [videoPassword]="videoPassword"
+ [video]="video()"
+ [videoPassword]="videoPassword()"
[inReplyToCommentId]="inReplyToCommentId"
[commentTree]="threadComments[comment.id]"
[firstInThread]="i + 1 !== comments.length"
@@ -77,10 +77,10 @@
<ng-template #hasAuthorComments>
<ng-container *ngIf="comment.totalReplies !== comment.totalRepliesFromVideoAuthor; else onlyAuthorComments" i18n>
- View {comment.totalReplies, plural, =1 {1 reply} other {{{ comment.totalReplies }} replies}} from {{ video?.account?.displayName || 'the author' }} and others
+ View {comment.totalReplies, plural, =1 {1 reply} other {{{ comment.totalReplies }} replies}} from {{ video()?.account?.displayName || 'the author' }} and others
</ng-container>
<ng-template i18n #onlyAuthorComments>
- View {comment.totalReplies, plural, =1 {1 reply} other {{{ comment.totalReplies }} replies}} from {{ video?.account?.displayName || 'the author' }}
+ View {comment.totalReplies, plural, =1 {1 reply} other {{{ comment.totalReplies }} replies}} from {{ video()?.account?.displayName || 'the author' }}
</ng-template>
</ng-template>
diff --git a/client/src/app/+videos/+video-watch/shared/comment/video-comments.component.ts b/client/src/app/+videos/+video-watch/shared/comment/video-comments.component.ts
index 83ba530d1d..f3ea38c358 100644
--- a/client/src/app/+videos/+video-watch/shared/comment/video-comments.component.ts
+++ b/client/src/app/+videos/+video-watch/shared/comment/video-comments.component.ts
@@ -1,5 +1,5 @@
import { NgFor, NgIf } from '@angular/common'
-import { Component, ElementRef, EventEmitter, Input, OnChanges, OnDestroy, OnInit, Output, SimpleChanges, ViewChild } from '@angular/core'
+import { Component, ElementRef, OnChanges, OnDestroy, OnInit, SimpleChanges, inject, input, output, viewChild } from '@angular/core'
import { ActivatedRoute } from '@angular/router'
import { AuthService, ComponentPagination, ConfirmService, hasMoreItems, Notifier, PluginService, User } from '@app/core'
import { HooksService } from '@app/core/plugins/hooks.service'
@@ -37,12 +37,20 @@ import { VideoCommentComponent } from './video-comment.component'
]
})
export class VideoCommentsComponent implements OnInit, OnChanges, OnDestroy {
- @ViewChild('commentHighlightBlock') commentHighlightBlock: ElementRef
- @Input() video: VideoDetails
- @Input() videoPassword: string
- @Input() user: User
+ private authService = inject(AuthService)
+ private notifier = inject(Notifier)
+ private confirmService = inject(ConfirmService)
+ private videoCommentService = inject(VideoCommentService)
+ private activatedRoute = inject(ActivatedRoute)
+ private hooks = inject(HooksService)
+ private pluginService = inject(PluginService)
- @Output() timestampClicked = new EventEmitter<number>()
+ readonly commentHighlightBlock = viewChild<ElementRef>('commentHighlightBlock')
+ readonly video = input<VideoDetails>(undefined)
+ readonly videoPassword = input<string>(undefined)
+ readonly user = input<User>(undefined)
+
+ readonly timestampClicked = output<number>()
comments: VideoComment[] = []
highlightedThread: VideoComment
@@ -62,8 +70,8 @@ export class VideoCommentsComponent implements OnInit, OnChanges, OnDestroy {
commentsEnabled: boolean
- threadComments: { [ id: number ]: VideoCommentThreadTree } = {}
- threadLoading: { [ id: number ]: boolean } = {}
+ threadComments: { [id: number]: VideoCommentThreadTree } = {}
+ threadLoading: { [id: number]: boolean } = {}
syndicationItems: Syndication[] = []
@@ -71,16 +79,6 @@ export class VideoCommentsComponent implements OnInit, OnChanges, OnDestroy {
private sub: Subscription
- constructor (
- private authService: AuthService,
- private notifier: Notifier,
- private confirmService: ConfirmService,
- private videoCommentService: VideoCommentService,
- private activatedRoute: ActivatedRoute,
- private hooks: HooksService,
- private pluginService: PluginService
- ) {}
-
ngOnInit () {
this.pluginService.addAction('video-watch-comment-list:load-data', () => this.loadMoreThreads(true))
@@ -111,9 +109,9 @@ export class VideoCommentsComponent implements OnInit, OnChanges, OnDestroy {
this.threadLoading[commentId] = true
const params = {
- videoId: this.video.uuid,
+ videoId: this.video().uuid,
threadId: commentId,
- videoPassword: this.videoPassword
+ videoPassword: this.videoPassword()
}
const obs = this.hooks.wrapObsFun(
@@ -134,7 +132,7 @@ export class VideoCommentsComponent implements OnInit, OnChanges, OnDestroy {
this.highlightedThread = new VideoComment(res.comment)
// Scroll to the highlighted thread
- setTimeout(() => this.commentHighlightBlock.nativeElement.scrollIntoView(), 0)
+ setTimeout(() => this.commentHighlightBlock().nativeElement.scrollIntoView(), 0)
}
},
@@ -155,8 +153,8 @@ export class VideoCommentsComponent implements OnInit, OnChanges, OnDestroy {
}
const params = {
- videoId: this.video.uuid,
- videoPassword: this.videoPassword,
+ videoId: this.video().uuid,
+ videoPassword: this.videoPassword(),
componentPagination: this.componentPagination,
sort: this.sort
}
@@ -219,7 +217,7 @@ export class VideoCommentsComponent implements OnInit, OnChanges, OnDestroy {
title = $localize`Delete`,
message = $localize`Do you really want to delete this comment?`
): Promise<boolean> {
- if (commentToDelete.isLocal || this.video.isLocal) {
+ if (commentToDelete.isLocal || this.video().isLocal) {
message += $localize` The deletion will be sent to remote platforms so they can reflect the change.`
} else {
message += $localize` It is a remote comment, so the deletion will only be effective on your platform.`
@@ -265,7 +263,6 @@ export class VideoCommentsComponent implements OnInit, OnChanges, OnDestroy {
} else {
this.commentReplyRedraftValue = commentToRedraftText
}
-
}
}
@@ -301,7 +298,8 @@ export class VideoCommentsComponent implements OnInit, OnChanges, OnDestroy {
}
private resetVideo () {
- if (this.video.commentsPolicy.id === VideoCommentPolicy.DISABLED) return
+ const video = this.video()
+ if (video.commentsPolicy.id === VideoCommentPolicy.DISABLED) return
// Reset all our fields
this.highlightedThread = null
@@ -315,7 +313,7 @@ export class VideoCommentsComponent implements OnInit, OnChanges, OnDestroy {
this.commentsEnabled = true
- this.syndicationItems = this.videoCommentService.getVideoCommentsFeeds(this.video)
+ this.syndicationItems = this.videoCommentService.getVideoCommentsFeeds(video)
this.loadMoreThreads()
if (this.activatedRoute.snapshot.params['threadId']) {
diff --git a/client/src/app/+videos/+video-watch/shared/information/privacy-concerns.component.ts b/client/src/app/+videos/+video-watch/shared/information/privacy-concerns.component.ts
index 0970af1b76..8bab16938a 100644
--- a/client/src/app/+videos/+video-watch/shared/information/privacy-concerns.component.ts
+++ b/client/src/app/+videos/+video-watch/shared/information/privacy-concerns.component.ts
@@ -1,4 +1,4 @@
-import { Component, Input, OnInit } from '@angular/core'
+import { Component, OnInit, inject, input } from '@angular/core'
import { ServerService, User, UserService } from '@app/core'
import { peertubeLocalStorage } from '@root-helpers/peertube-web-storage'
import { isP2PEnabled } from '@root-helpers/video'
@@ -12,19 +12,17 @@ import { NgIf } from '@angular/common'
imports: [ NgIf ]
})
export class PrivacyConcernsComponent implements OnInit {
+ private serverService = inject(ServerService)
+ private userService = inject(UserService)
+
private static LS_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
- @Input() video: Video
+ readonly video = input<Video>(undefined)
display = false
private serverConfig: HTMLServerConfig
- constructor (
- private serverService: ServerService,
- private userService: UserService
- ) { }
-
ngOnInit () {
this.serverConfig = this.serverService.getHTMLConfig()
@@ -39,7 +37,7 @@ export class PrivacyConcernsComponent implements OnInit {
}
private updateDisplay (user: User) {
- if (isP2PEnabled(this.video, this.serverConfig, user.p2pEnabled) && !this.alreadyAccepted()) {
+ if (isP2PEnabled(this.video(), this.serverConfig, user.p2pEnabled) && !this.alreadyAccepted()) {
this.display = true
}
}
diff --git a/client/src/app/+videos/+video-watch/shared/information/video-alert.component.html b/client/src/app/+videos/+video-watch/shared/information/video-alert.component.html
index e34a2ad579..67010a411e 100644
--- a/client/src/app/+videos/+video-watch/shared/information/video-alert.component.html
+++ b/client/src/app/+videos/+video-watch/shared/information/video-alert.component.html
@@ -1,5 +1,5 @@
<my-alert rounded="false" type="primary" i18n *ngIf="hasVideoScheduledPublication()">
- This video will be published on {{ video.scheduledUpdate.updateAt | ptDate: 'full' }}.
+ This video will be published on {{ video().scheduledUpdate.updateAt | ptDate: 'full' }}.
</my-alert>
<my-alert rounded="false" type="primary" i18n *ngIf="isWaitingForLive()">
@@ -14,15 +14,15 @@
{{ getAlertWarning() }}
</my-alert>
-<my-alert rounded="false" i18n type="warning" *ngIf="noPlaylistVideoFound">
+<my-alert rounded="false" i18n type="warning" *ngIf="noPlaylistVideoFound()">
There are no videos available in this playlist.
</my-alert>
-<my-alert rounded="false" type="danger" *ngIf="video?.blacklisted">
+<my-alert rounded="false" type="danger" *ngIf="video()?.blacklisted">
<div class="blocked-label" i18n>This video is blocked.</div>
- {{ video.blacklistedReason }}
+ {{ video().blacklistedReason }}
</my-alert>
-<my-alert rounded="false" i18n type="warning" *ngIf="video?.canAccessPasswordProtectedVideoWithoutPassword(user)">
+<my-alert rounded="false" i18n type="warning" *ngIf="video()?.canAccessPasswordProtectedVideoWithoutPassword(user())">
This video is password protected.
</my-alert>
diff --git a/client/src/app/+videos/+video-watch/shared/information/video-alert.component.ts b/client/src/app/+videos/+video-watch/shared/information/video-alert.component.ts
index 878cdafd13..3af35313df 100644
--- a/client/src/app/+videos/+video-watch/shared/information/video-alert.component.ts
+++ b/client/src/app/+videos/+video-watch/shared/information/video-alert.component.ts
@@ -1,5 +1,5 @@
import { NgIf } from '@angular/common'
-import { Component, Input } from '@angular/core'
+import { Component, input } from '@angular/core'
import { AuthUser } from '@app/core'
import { AlertComponent } from '@app/shared/shared-main/common/alert.component'
import { PTDatePipe } from '@app/shared/shared-main/common/date.pipe'
@@ -13,14 +13,15 @@ import { VideoPrivacy, VideoState } from '@peertube/peertube-models'
imports: [ NgIf, PTDatePipe, AlertComponent ]
})
export class VideoAlertComponent {
- @Input() user: AuthUser
- @Input() video: VideoDetails
- @Input() noPlaylistVideoFound: boolean
+ readonly user = input<AuthUser>(undefined)
+ readonly video = input<VideoDetails>(undefined)
+ readonly noPlaylistVideoFound = input<boolean>(undefined)
getAlertWarning () {
- if (!this.video) return
+ const video = this.video()
+ if (!video) return
- switch (this.video.state.id) {
+ switch (video.state.id) {
case VideoState.TO_TRANSCODE:
return $localize`The video is being transcoded, it may not work properly.`
@@ -48,18 +49,18 @@ export class VideoAlertComponent {
}
hasVideoScheduledPublication () {
- return this.video?.scheduledUpdate !== undefined
+ return this.video()?.scheduledUpdate !== undefined
}
isWaitingForLive () {
- return this.video?.state.id === VideoState.WAITING_FOR_LIVE
+ return this.video()?.state.id === VideoState.WAITING_FOR_LIVE
}
isLiveEnded () {
- return this.video?.state.id === VideoState.LIVE_ENDED
+ return this.video()?.state.id === VideoState.LIVE_ENDED
}
isVideoPasswordProtected () {
- return this.video?.privacy.id === VideoPrivacy.PASSWORD_PROTECTED
+ return this.video()?.privacy.id === VideoPrivacy.PASSWORD_PROTECTED
}
}
diff --git a/client/src/app/+videos/+video-watch/shared/metadata/video-attributes.component.html b/client/src/app/+videos/+video-watch/shared/metadata/video-attributes.component.html
index 4934fb3050..05cc5404d5 100644
--- a/client/src/app/+videos/+video-watch/shared/metadata/video-attributes.component.html
+++ b/client/src/app/+videos/+video-watch/shared/metadata/video-attributes.component.html
@@ -1,58 +1,58 @@
<div class="attribute attribute-privacy">
<span i18n class="attribute-label">Privacy</span>
- <span class="attribute-value">{{ video.privacy.label }}</span>
+ <span class="attribute-value">{{ video().privacy.label }}</span>
</div>
-<div *ngIf="video.isLocal === false" class="attribute attribute-origin">
+<div *ngIf="video().isLocal === false" class="attribute attribute-origin">
<span i18n class="attribute-label">Origin</span>
<a
class="attribute-value" target="_blank" rel="noopener noreferrer"
routerLink="/search" [queryParams]="{ host: getVideoHost() }"
- >{{ video.originInstanceHost }}</a>
+ >{{ video().originInstanceHost }}</a>
<a
i18n-title title="Open the video on the origin instance"
- target="_blank" rel="noopener noreferrer" [href]="video.url"
+ target="_blank" rel="noopener noreferrer" [href]="video().url"
>
<my-global-icon iconName="external-link"></my-global-icon>
</a>
</div>
-<div *ngIf="!!video.inputFileUpdatedAt" class="attribute attribute-re-uploaded-on">
+<div *ngIf="!!video().inputFileUpdatedAt" class="attribute attribute-re-uploaded-on">
<span i18n class="attribute-label">Video re-upload</span>
- <span class="attribute-value">{{ video.inputFileUpdatedAt | ptDate: 'short' }}</span>
+ <span class="attribute-value">{{ video().inputFileUpdatedAt | ptDate: 'short' }}</span>
</div>
-<div *ngIf="!!video.originallyPublishedAt" class="attribute attribute-originally-published-at">
+<div *ngIf="!!video().originallyPublishedAt" class="attribute attribute-originally-published-at">
<span i18n class="attribute-label">Originally published</span>
- <span class="attribute-value">{{ video.originallyPublishedAt | ptDate: 'shortDate' }}</span>
+ <span class="attribute-value">{{ video().originallyPublishedAt | ptDate: 'shortDate' }}</span>
</div>
<div class="attribute attribute-category">
<span i18n class="attribute-label">Category</span>
- <span *ngIf="!video.category.id" class="attribute-value">{{ video.category.label }}</span>
+ <span *ngIf="!video().category.id" class="attribute-value">{{ video().category.label }}</span>
<a
- *ngIf="video.category.id" class="attribute-value"
- [routerLink]="[ '/search' ]" [queryParams]="{ categoryOneOf: [ video.category.id ] }"
- >{{ video.category.label }}</a>
+ *ngIf="video().category.id" class="attribute-value"
+ [routerLink]="[ '/search' ]" [queryParams]="{ categoryOneOf: [ video().category.id ] }"
+ >{{ video().category.label }}</a>
</div>
<div class="attribute attribute-licence">
<span i18n class="attribute-label">Licence</span>
- <span *ngIf="!video.licence.id" class="attribute-value">{{ video.licence.label }}</span>
+ <span *ngIf="!video().licence.id" class="attribute-value">{{ video().licence.label }}</span>
<a
- *ngIf="video.licence.id" class="attribute-value"
- [routerLink]="[ '/search' ]" [queryParams]="{ licenceOneOf: [ video.licence.id ] }"
- >{{ video.licence.label }}</a>
+ *ngIf="video().licence.id" class="attribute-value"
+ [routerLink]="[ '/search' ]" [queryParams]="{ licenceOneOf: [ video().licence.id ] }"
+ >{{ video().licence.label }}</a>
</div>
<div class="attribute attribute-language">
<span i18n class="attribute-label">Language</span>
- <span *ngIf="!video.language.id" class="attribute-value">{{ video.language.label }}</span>
+ <span *ngIf="!video().language.id" class="attribute-value">{{ video().language.label }}</span>
<a
- *ngIf="video.language.id" class="attribute-value"
- [routerLink]="[ '/search' ]" [queryParams]="{ languageOneOf: [ video.language.id ] }"
- >{{ video.language.label }}</a>
+ *ngIf="video().language.id" class="attribute-value"
+ [routerLink]="[ '/search' ]" [queryParams]="{ languageOneOf: [ video().language.id ] }"
+ >{{ video().language.label }}</a>
</div>
<div class="attribute attribute-tags">
@@ -63,9 +63,9 @@
>{{ tag }}</a>
</div>
-<div class="attribute attribute-duration" *ngIf="!video.isLive">
+<div class="attribute attribute-duration" *ngIf="!video().isLive">
<span i18n class="attribute-label">Duration</span>
- <span class="attribute-value">{{ video.duration | myTimeDurationFormatter }}</span>
+ <span class="attribute-value">{{ video().duration | myTimeDurationFormatter }}</span>
</div>
<div class="attribute attribute-plugin" *ngFor="let metadata of pluginMetadata">
diff --git a/client/src/app/+videos/+video-watch/shared/metadata/video-attributes.component.ts b/client/src/app/+videos/+video-watch/shared/metadata/video-attributes.component.ts
index 238db5aea6..26bd234101 100644
--- a/client/src/app/+videos/+video-watch/shared/metadata/video-attributes.component.ts
+++ b/client/src/app/+videos/+video-watch/shared/metadata/video-attributes.component.ts
@@ -1,5 +1,5 @@
import { NgFor, NgIf } from '@angular/common'
-import { Component, Input, OnChanges } from '@angular/core'
+import { Component, OnChanges, inject, input } from '@angular/core'
import { RouterLink } from '@angular/router'
import { HooksService } from '@app/core'
import { PTDatePipe } from '@app/shared/shared-main/common/date.pipe'
@@ -21,28 +21,29 @@ type PluginMetadata = {
imports: [ NgIf, RouterLink, GlobalIconComponent, NgFor, TimeDurationFormatterPipe, PTDatePipe ]
})
export class VideoAttributesComponent implements OnChanges {
- @Input() video: VideoDetails
+ private hooks = inject(HooksService)
- pluginMetadata: PluginMetadata[] = []
+ readonly video = input<VideoDetails>(undefined)
- constructor (private hooks: HooksService) { }
+ pluginMetadata: PluginMetadata[] = []
async ngOnChanges () {
this.pluginMetadata = await this.hooks.wrapObject(
this.pluginMetadata,
'video-watch',
'filter:video-watch.video-plugin-metadata.result',
- { video: this.video }
+ { video: this.video() }
)
}
getVideoHost () {
- return this.video.channel.host
+ return this.video().channel.host
}
getVideoTags () {
- if (!this.video || Array.isArray(this.video.tags) === false) return []
+ const video = this.video()
+ if (!video || Array.isArray(video.tags) === false) return []
- return this.video.tags
+ return video.tags
}
}
diff --git a/client/src/app/+videos/+video-watch/shared/metadata/video-avatar-channel.component.html b/client/src/app/+videos/+video-watch/shared/metadata/video-avatar-channel.component.html
index a608a22f6c..502bf474bb 100644
--- a/client/src/app/+videos/+video-watch/shared/metadata/video-avatar-channel.component.html
+++ b/client/src/app/+videos/+video-watch/shared/metadata/video-avatar-channel.component.html
@@ -1,19 +1,19 @@
<div class="wrapper">
<my-actor-avatar
- *ngIf="showChannel"
+ *ngIf="showChannel()"
class="channel"
- [actor]="video.channel" actorType="channel"
- [internalHref]="[ '/c', video.byVideoChannel ]"
+ [actor]="video().channel" actorType="channel"
+ [internalHref]="[ '/c', video().byVideoChannel ]"
[title]="channelLinkTitle"
size="35"
></my-actor-avatar>
<my-actor-avatar
- *ngIf="showAccount"
+ *ngIf="showAccount()"
class="account"
- [class.second-avatar]="showChannel"
- [actor]="video.account" actorType="account"
- [internalHref]="[ '/a', video.byAccount ]"
+ [class.second-avatar]="showChannel()"
+ [actor]="video().account" actorType="account"
+ [internalHref]="[ '/a', video().byAccount ]"
[title]="accountLinkTitle"
size="35">
</my-actor-avatar>
diff --git a/client/src/app/+videos/+video-watch/shared/metadata/video-avatar-channel.component.ts b/client/src/app/+videos/+video-watch/shared/metadata/video-avatar-channel.component.ts
index f92659fed1..0bd53afa72 100644
--- a/client/src/app/+videos/+video-watch/shared/metadata/video-avatar-channel.component.ts
+++ b/client/src/app/+videos/+video-watch/shared/metadata/video-avatar-channel.component.ts
@@ -1,4 +1,4 @@
-import { Component, Input, OnInit } from '@angular/core'
+import { Component, OnInit, input } from '@angular/core'
import { ActorAvatarComponent } from '../../../../shared/shared-actor-image/actor-avatar.component'
import { NgIf } from '@angular/common'
import { Video } from '@app/shared/shared-main/video/video.model'
@@ -10,17 +10,17 @@ import { Video } from '@app/shared/shared-main/video/video.model'
imports: [ NgIf, ActorAvatarComponent ]
})
export class VideoAvatarChannelComponent implements OnInit {
- @Input() video: Video
- @Input() byAccount: string
+ readonly video = input<Video>(undefined)
+ readonly byAccount = input<string>(undefined)
- @Input() showAccount: boolean
- @Input() showChannel: boolean
+ readonly showAccount = input<boolean>(undefined)
+ readonly showChannel = input<boolean>(undefined)
channelLinkTitle = ''
accountLinkTitle = ''
ngOnInit () {
- this.channelLinkTitle = $localize`${this.video.account.name} (channel page)`
- this.accountLinkTitle = $localize`${this.video.byAccount} (account page)`
+ this.channelLinkTitle = $localize`${this.video().account.name} (channel page)`
+ this.accountLinkTitle = $localize`${this.video().byAccount} (account page)`
}
}
diff --git a/client/src/app/+videos/+video-watch/shared/metadata/video-description.component.ts b/client/src/app/+videos/+video-watch/shared/metadata/video-description.component.ts
index 59879b3b8e..4b917bb84d 100644
--- a/client/src/app/+videos/+video-watch/shared/metadata/video-description.component.ts
+++ b/client/src/app/+videos/+video-watch/shared/metadata/video-description.component.ts
@@ -1,4 +1,4 @@
-import { Component, EventEmitter, Input, OnChanges, Output, ViewChild, ElementRef } from '@angular/core'
+import { Component, OnChanges, ElementRef, inject, input, output, viewChild } from '@angular/core'
import { MarkdownService } from '@app/core'
import { NgClass, NgIf } from '@angular/common'
import { TimestampRouteTransformerDirective } from '../timestamp-route-transformer.directive'
@@ -11,20 +11,18 @@ import { VideoDetails } from '@app/shared/shared-main/video/video-details.model'
imports: [ TimestampRouteTransformerDirective, NgClass, NgIf ]
})
export class VideoDescriptionComponent implements OnChanges {
- @ViewChild('descriptionHTML') descriptionHTML: ElementRef<HTMLElement>
+ private markdownService = inject(MarkdownService)
- @Input() video: VideoDetails
+ readonly descriptionHTML = viewChild<ElementRef<HTMLElement>>('descriptionHTML')
- @Output() timestampClicked = new EventEmitter<number>()
+ readonly video = input<VideoDetails>(undefined)
+
+ readonly timestampClicked = output<number>()
completeDescriptionShown = false
videoHTMLDescription = ''
- constructor (
- private markdownService: MarkdownService
- ) { }
-
ngOnChanges () {
this.completeDescriptionShown = false
@@ -32,7 +30,7 @@ export class VideoDescriptionComponent implements OnChanges {
}
hasEllipsis () {
- const el = this.descriptionHTML?.nativeElement
+ const el = this.descriptionHTML()?.nativeElement
if (!el) return false
return el.offsetHeight < el.scrollHeight
@@ -51,8 +49,8 @@ export class VideoDescriptionComponent implements OnChanges {
}
private async setVideoDescriptionHTML () {
- const html = await this.markdownService.textMarkdownToHTML({ markdown: this.video.description, withHtml: true, withEmoji: true })
+ const html = await this.markdownService.textMarkdownToHTML({ markdown: this.video().description, withHtml: true, withEmoji: true })
- this.videoHTMLDescription = this.markdownService.processVideoTimestamps(this.video.shortUUID, html)
+ this.videoHTMLDescription = this.markdownService.processVideoTimestamps(this.video().shortUUID, html)
}
}
diff --git a/client/src/app/+videos/+video-watch/shared/player-widgets/video-transcription.component.ts b/client/src/app/+videos/+video-watch/shared/player-widgets/video-transcription.component.ts
index 0e543afec2..9003d7f69e 100644
--- a/client/src/app/+videos/+video-watch/shared/player-widgets/video-transcription.component.ts
+++ b/client/src/app/+videos/+video-watch/shared/player-widgets/video-transcription.component.ts
@@ -1,22 +1,11 @@
-import { NgClass, NgFor, NgIf } from '@angular/common'
-import {
- Component,
- ElementRef,
- EventEmitter,
- HostListener,
- Input,
- OnChanges,
- OnInit,
- Output,
- SimpleChanges,
- ViewChild
-} from '@angular/core'
+import { NgClass, NgFor } from '@angular/common'
+import { Component, ElementRef, HostListener, OnChanges, OnInit, SimpleChanges, inject, input, output, viewChild } from '@angular/core'
import { FormsModule } from '@angular/forms'
import { Notifier } from '@app/core'
import { durationToString, isInViewport } from '@app/helpers'
import { SelectOptionsComponent } from '@app/shared/shared-forms/select/select-options.component'
import { VideoCaptionService } from '@app/shared/shared-main/video-caption/video-caption.service'
-import { NgbCollapse, NgbTooltip } from '@ng-bootstrap/ng-bootstrap'
+import { NgbCollapse } from '@ng-bootstrap/ng-bootstrap'
import { Video, VideoCaption } from '@peertube/peertube-models'
import { parse } from '@plussub/srt-vtt-parser'
import debug from 'debug'
@@ -41,9 +30,7 @@ type Segment = {
templateUrl: './video-transcription.component.html',
styleUrls: [ './player-widget.component.scss', './video-transcription.component.scss' ],
imports: [
- NgIf,
NgClass,
- NgbTooltip,
GlobalIconComponent,
NgFor,
NgbCollapse,
@@ -53,15 +40,19 @@ type Segment = {
]
})
export class VideoTranscriptionComponent implements OnInit, OnChanges {
- @ViewChild('settingsPanel') settingsPanel: ElementRef
+ private notifier = inject(Notifier)
+ private captionService = inject(VideoCaptionService)
- @Input() video: Video
- @Input() captions: VideoCaption[]
- @Input() currentTime: number
+ readonly settingsPanel = viewChild<ElementRef>('settingsPanel')
+ readonly video = input<Video>(undefined)
+ readonly captions = input<VideoCaption[]>(undefined)
// Output the duration clicked
- @Output() segmentClicked = new EventEmitter<number>()
- @Output() closeTranscription = new EventEmitter<void>()
+ readonly currentTime = input<number>(undefined)
+
+ // Output the duration clicked
+ readonly segmentClicked = output<number>()
+ readonly closeTranscription = output()
currentCaption: VideoCaption
segments: Segment[] = []
@@ -79,17 +70,11 @@ export class VideoTranscriptionComponent implements OnInit, OnChanges {
private segmentsStore: Segment[] = []
private searchSubject = new Subject<string>()
- constructor (
- private notifier: Notifier,
- private captionService: VideoCaptionService
- ) {
- }
-
@HostListener('document:click', [ '$event' ])
clickout (event: Event) {
if (!this.settingsPanelShown) return
- if (!this.settingsPanel?.nativeElement.contains(event.target)) {
+ if (!this.settingsPanel()?.nativeElement.contains(event.target)) {
this.isSettingsPanelCollapsed = true
}
}
@@ -119,7 +104,7 @@ export class VideoTranscriptionComponent implements OnInit, OnChanges {
}
updateCurrentCaption () {
- this.currentCaption = this.captions.find(c => c.language.id === this.currentLanguage)
+ this.currentCaption = this.captions().find(c => c.language.id === this.currentLanguage)
this.parseCurrentCaption()
}
@@ -138,13 +123,15 @@ export class VideoTranscriptionComponent implements OnInit, OnChanges {
this.languagesOptions = []
- if (!this.video || !this.captions || this.captions.length === 0) return
+ const captions = this.captions()
+ const video = this.video()
+ if (!video || !captions || captions.length === 0) return
- this.currentLanguage = this.captions.some(c => c.language.id === this.video.language.id)
- ? this.video.language.id
- : this.captions[0].language.id
+ this.currentLanguage = captions.some(c => c.language.id === this.video().language.id)
+ ? video.language.id
+ : captions[0].language.id
- this.languagesOptions = this.captions.map(c => ({
+ this.languagesOptions = captions.map(c => ({
id: c.language.id,
label: c.automaticallyGenerated
? $localize`${c.language.label} (automatically generated)`
@@ -213,12 +200,13 @@ export class VideoTranscriptionComponent implements OnInit, OnChanges {
const lastActiveSegment = this.activeSegment
this.activeSegment = undefined
- if (isNaN(this.currentTime)) return
+ const currentTime = this.currentTime()
+ if (isNaN(currentTime)) return
for (let i = this.segmentsStore.length - 1; i >= 0; i--) {
const current = this.segmentsStore[i]
- if (current.start <= this.currentTime) {
+ if (current.start <= currentTime) {
this.activeSegment = current
break
}
diff --git a/client/src/app/+videos/+video-watch/shared/player-widgets/video-watch-playlist.component.html b/client/src/app/+videos/+video-watch/shared/player-widgets/video-watch-playlist.component.html
index 38610291fc..8a127f0057 100644
--- a/client/src/app/+videos/+video-watch/shared/player-widgets/video-watch-playlist.component.html
+++ b/client/src/app/+videos/+video-watch/shared/player-widgets/video-watch-playlist.component.html
@@ -1,10 +1,10 @@
<div
- *ngIf="playlist && (currentPlaylistPosition || noPlaylistVideos)" class="widget-root playlist"
+ *ngIf="playlist() && (currentPlaylistPosition || noPlaylistVideos)" class="widget-root playlist"
myInfiniteScroller [onItself]="true" (nearOfBottom)="onPlaylistVideosNearOfBottom()"
>
<div class="widget-header playlist-info">
<div class="widget-title playlist-display-name">
- {{ playlist.displayName }}
+ {{ playlist().displayName }}
<span *ngIf="isUnlistedPlaylist()" class="pt-badge badge-warning" i18n>Unlisted</span>
<span *ngIf="isPrivatePlaylist()" class="pt-badge badge-danger" i18n>Private</span>
@@ -12,7 +12,7 @@
</div>
<div class="playlist-by-index">
- <div class="playlist-by">{{ playlist.ownerBy }}</div>
+ <div class="playlist-by">{{ playlist().ownerBy }}</div>
<div class="playlist-index">
<span>{{ currentPlaylistPosition }}</span><span>{{ playlistPagination.totalItems }}</span>
</div>
@@ -39,7 +39,7 @@
<div *ngFor="let playlistElement of playlistElements" [ngClass]="'element-' + playlistElement.position">
<my-video-playlist-element-miniature
- [playlistElement]="playlistElement" [playlist]="playlist" [owned]="isPlaylistOwned()" (elementRemoved)="onElementRemoved($event)"
+ [playlistElement]="playlistElement" [playlist]="playlist()" [owned]="isPlaylistOwned()" (elementRemoved)="onElementRemoved($event)"
[playing]="currentPlaylistPosition === playlistElement.position" [accountLink]="false" [position]="playlistElement.position"
></my-video-playlist-element-miniature>
</div>
diff --git a/client/src/app/+videos/+video-watch/shared/player-widgets/video-watch-playlist.component.ts b/client/src/app/+videos/+video-watch/shared/player-widgets/video-watch-playlist.component.ts
index 178169a7ff..4f637cd9c3 100644
--- a/client/src/app/+videos/+video-watch/shared/player-widgets/video-watch-playlist.component.ts
+++ b/client/src/app/+videos/+video-watch/shared/player-widgets/video-watch-playlist.component.ts
@@ -1,5 +1,5 @@
import { NgClass, NgFor, NgIf } from '@angular/common'
-import { Component, EventEmitter, Input, Output } from '@angular/core'
+import { Component, inject, input, output } from '@angular/core'
import { Router } from '@angular/router'
import {
AuthService,
@@ -29,12 +29,20 @@ import { VideoPlaylistElementMiniatureComponent } from '../../../../shared/share
imports: [ NgIf, InfiniteScrollerDirective, NgClass, NgbTooltip, GlobalIconComponent, NgFor, VideoPlaylistElementMiniatureComponent ]
})
export class VideoWatchPlaylistComponent {
+ private hooks = inject(HooksService)
+ private userService = inject(UserService)
+ private auth = inject(AuthService)
+ private notifier = inject(Notifier)
+ private videoPlaylist = inject(VideoPlaylistService)
+ private sessionStorage = inject(SessionStorageService)
+ private router = inject(Router)
+
static SESSION_STORAGE_LOOP_PLAYLIST = 'loop_playlist'
- @Input() playlist: VideoPlaylist
+ readonly playlist = input<VideoPlaylist>(undefined)
- @Output() videoFound = new EventEmitter<string>()
- @Output() noVideoFound = new EventEmitter<void>()
+ readonly videoFound = output<string>()
+ readonly noVideoFound = output()
playlistElements: VideoPlaylistElement[] = []
playlistPagination: ComponentPagination = {
@@ -52,15 +60,7 @@ export class VideoWatchPlaylistComponent {
noPlaylistVideos = false
currentPlaylistPosition: number
- constructor (
- private hooks: HooksService,
- private userService: UserService,
- private auth: AuthService,
- private notifier: Notifier,
- private videoPlaylist: VideoPlaylistService,
- private sessionStorage: SessionStorageService,
- private router: Router
- ) {
+ constructor () {
this.userService.getAnonymousOrLoggedUser()
.subscribe(user => this.autoPlayNextVideoPlaylist = user.autoPlayNextVideoPlaylist)
@@ -75,7 +75,7 @@ export class VideoWatchPlaylistComponent {
if (this.playlistPagination.totalItems <= (this.playlistPagination.currentPage * this.playlistPagination.itemsPerPage)) return
this.playlistPagination.currentPage += 1
- this.loadPlaylistElements(this.playlist, false, position)
+ this.loadPlaylistElements(this.playlist(), false, position)
}
onElementRemoved (playlistElement: VideoPlaylistElement) {
@@ -85,21 +85,22 @@ export class VideoWatchPlaylistComponent {
}
isPlaylistOwned () {
- return this.playlist.isLocal === true &&
+ const playlist = this.playlist()
+ return playlist.isLocal === true &&
this.auth.isLoggedIn() &&
- this.playlist.ownerAccount.name === this.auth.getUser().username
+ playlist.ownerAccount.name === this.auth.getUser().username
}
isUnlistedPlaylist () {
- return this.playlist.privacy.id === VideoPlaylistPrivacy.UNLISTED
+ return this.playlist().privacy.id === VideoPlaylistPrivacy.UNLISTED
}
isPrivatePlaylist () {
- return this.playlist.privacy.id === VideoPlaylistPrivacy.PRIVATE
+ return this.playlist().privacy.id === VideoPlaylistPrivacy.PRIVATE
}
isPublicPlaylist () {
- return this.playlist.privacy.id === VideoPlaylistPrivacy.PUBLIC
+ return this.playlist().privacy.id === VideoPlaylistPrivacy.PUBLIC
}
loadPlaylistElements (playlist: VideoPlaylist, redirectToFirst = false, position?: number) {
@@ -142,7 +143,7 @@ export class VideoWatchPlaylistComponent {
if (this.playlistElements.length === 0 || !position) return
// Handle the reverse index
- if (position < 0) position = this.playlist.videosLength + position + 1
+ if (position < 0) position = this.playlist().videosLength + position + 1
for (const playlistElement of this.playlistElements) {
// >= if the previous videos were not valid
diff --git a/client/src/app/+videos/+video-watch/shared/recommendations/recommended-videos.component.html b/client/src/app/+videos/+video-watch/shared/recommendations/recommended-videos.component.html
index 82c63809bf..05fc983ada 100644
--- a/client/src/app/+videos/+video-watch/shared/recommendations/recommended-videos.component.html
+++ b/client/src/app/+videos/+video-watch/shared/recommendations/recommended-videos.component.html
@@ -1,10 +1,10 @@
-<div class="other-videos" [ngClass]="{ 'display-as-row': displayAsRow }">
+<div class="other-videos" [ngClass]="{ 'display-as-row': displayAsRow() }">
@if (videos.length !== 0) {
<div class="title-page-container">
<h2 i18n>Other videos</h2>
<div
- *ngIf="!playlist" class="title-page-autoplay"
+ *ngIf="!playlist()" class="title-page-autoplay"
[ngbTooltip]="autoPlayNextVideoTooltip" placement="bottom-right auto"
>
<span i18n>AUTOPLAY</span>
@@ -18,16 +18,16 @@
</div>
<ng-container *ngFor="let video of videos; let i = index; let length = count">
- <span i18n *ngIf="!playlist && i === 0 && length !== 0 && autoPlayNextVideo" class="title-page-next-video-label">Next video to be played</span>
+ <span i18n *ngIf="!playlist() && i === 0 && length !== 0 && autoPlayNextVideo" class="title-page-next-video-label">Next video to be played</span>
<my-video-miniature
- [displayOptions]="displayOptions" [video]="video" [user]="user" [displayAsRow]="displayAsRow"
+ [displayOptions]="displayOptions" [video]="video" [user]="user" [displayAsRow]="displayAsRow()"
(videoBlocked)="onVideoRemoved()" (videoRemoved)="onVideoRemoved()" (videoAccountMuted)="onVideoRemoved()"
actorImageSize="32"
>
</my-video-miniature>
- <hr *ngIf="!playlist && i === 0 && length > 1 && autoPlayNextVideo" />
+ <hr *ngIf="!playlist() && i === 0 && length > 1 && autoPlayNextVideo" />
</ng-container>
}
</div>
diff --git a/client/src/app/+videos/+video-watch/shared/recommendations/recommended-videos.component.ts b/client/src/app/+videos/+video-watch/shared/recommendations/recommended-videos.component.ts
index e9c48dceef..475b18a60d 100644
--- a/client/src/app/+videos/+video-watch/shared/recommendations/recommended-videos.component.ts
+++ b/client/src/app/+videos/+video-watch/shared/recommendations/recommended-videos.component.ts
@@ -1,5 +1,5 @@
-import { AsyncPipe, NgClass, NgFor, NgIf } from '@angular/common'
-import { Component, EventEmitter, Input, OnChanges, OnDestroy, OnInit, Output } from '@angular/core'
+import { NgClass, NgFor, NgIf } from '@angular/common'
+import { Component, OnChanges, OnDestroy, OnInit, inject, input, output } from '@angular/core'
import { FormsModule } from '@angular/forms'
import { AuthService, Notifier, User, UserService } from '@app/core'
import { VideoDetails } from '@app/shared/shared-main/video/video-details.model'
@@ -15,14 +15,19 @@ import { VideoRecommendationService } from './video-recommendation.service'
selector: 'my-recommended-videos',
templateUrl: './recommended-videos.component.html',
styleUrls: [ './recommended-videos.component.scss' ],
- imports: [ NgClass, NgIf, NgbTooltip, InputSwitchComponent, FormsModule, NgFor, VideoMiniatureComponent, AsyncPipe ]
+ imports: [ NgClass, NgIf, NgbTooltip, InputSwitchComponent, FormsModule, NgFor, VideoMiniatureComponent ]
})
export class RecommendedVideosComponent implements OnInit, OnChanges, OnDestroy {
- @Input() currentVideo: VideoDetails
- @Input() playlist: VideoPlaylist
- @Input() displayAsRow: boolean
+ private userService = inject(UserService)
+ private authService = inject(AuthService)
+ private notifier = inject(Notifier)
+ private videoRecommendation = inject(VideoRecommendationService)
- @Output() gotRecommendations = new EventEmitter<Video[]>()
+ readonly currentVideo = input<VideoDetails>(undefined)
+ readonly playlist = input<VideoPlaylist>(undefined)
+ readonly displayAsRow = input<boolean>(undefined)
+
+ readonly gotRecommendations = output<Video[]>()
videos: Video[] = []
@@ -40,12 +45,7 @@ export class RecommendedVideosComponent implements OnInit, OnChanges, OnDestroy
private userSub: Subscription
- constructor (
- private userService: UserService,
- private authService: AuthService,
- private notifier: Notifier,
- private videoRecommendation: VideoRecommendationService
- ) {
+ constructor () {
this.autoPlayNextVideoTooltip = $localize`When active, the next video is automatically played after the current one.`
}
@@ -62,7 +62,7 @@ export class RecommendedVideosComponent implements OnInit, OnChanges, OnDestroy
}
ngOnChanges () {
- if (this.currentVideo) {
+ if (this.currentVideo()) {
this.loadRecommendations()
}
}
@@ -93,7 +93,7 @@ export class RecommendedVideosComponent implements OnInit, OnChanges, OnDestroy
}
private loadRecommendations () {
- this.videoRecommendation.getRecommendations(this.currentVideo, this.videoRecommendation.getRecommentationHistory())
+ this.videoRecommendation.getRecommendations(this.currentVideo(), this.videoRecommendation.getRecommendationHistory())
.subscribe({
next: videos => {
this.videos = videos
diff --git a/client/src/app/+videos/+video-watch/shared/recommendations/video-recommendation.service.ts b/client/src/app/+videos/+video-watch/shared/recommendations/video-recommendation.service.ts
index 7355c38bb3..75e529e795 100644
--- a/client/src/app/+videos/+video-watch/shared/recommendations/video-recommendation.service.ts
+++ b/client/src/app/+videos/+video-watch/shared/recommendations/video-recommendation.service.ts
@@ -1,4 +1,4 @@
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { ServerService, UserService } from '@app/core'
import { VideoDetails } from '@app/shared/shared-main/video/video-details.model'
import { Video } from '@app/shared/shared-main/video/video.model'
@@ -11,20 +11,20 @@ import { map, switchMap } from 'rxjs/operators'
@Injectable()
export class VideoRecommendationService {
+ private videos = inject(VideoService)
+ private searchService = inject(SearchService)
+ private userService = inject(UserService)
+ private serverService = inject(ServerService)
+
private config: HTMLServerConfig
private readonly videoIdsHistory = new Set<number>()
- constructor (
- private videos: VideoService,
- private searchService: SearchService,
- private userService: UserService,
- private serverService: ServerService
- ) {
+ constructor () {
this.config = this.serverService.getHTMLConfig()
}
- getRecommentationHistory () {
+ getRecommendationHistory () {
return this.videoIdsHistory
}
@@ -89,14 +89,14 @@ export class VideoRecommendationService {
: undefined
})
})
- .pipe(
- map(v => v.data),
- switchMap(videos => {
- if (videos.length <= 1) return defaultSubscription
+ .pipe(
+ map(v => v.data),
+ switchMap(videos => {
+ if (videos.length <= 1) return defaultSubscription
- return of(videos)
- })
- )
+ return of(videos)
+ })
+ )
})
)
}
diff --git a/client/src/app/+videos/+video-watch/shared/timestamp-route-transformer.directive.ts b/client/src/app/+videos/+video-watch/shared/timestamp-route-transformer.directive.ts
index f95d84d254..3cdfa39f8d 100644
--- a/client/src/app/+videos/+video-watch/shared/timestamp-route-transformer.directive.ts
+++ b/client/src/app/+videos/+video-watch/shared/timestamp-route-transformer.directive.ts
@@ -1,11 +1,11 @@
-import { Directive, EventEmitter, HostListener, Output } from '@angular/core'
+import { Directive, HostListener, output } from '@angular/core'
@Directive({
selector: '[myTimestampRouteTransformer]',
standalone: true
})
export class TimestampRouteTransformerDirective {
- @Output() timestampClicked = new EventEmitter<number>()
+ readonly timestampClicked = output<number>()
@HostListener('click', [ '$event' ])
public onClick ($event: Event) {
diff --git a/client/src/app/+videos/+video-watch/video-watch.component.ts b/client/src/app/+videos/+video-watch/video-watch.component.ts
index 6a08d9145d..6e186231e6 100644
--- a/client/src/app/+videos/+video-watch/video-watch.component.ts
+++ b/client/src/app/+videos/+video-watch/video-watch.component.ts
@@ -1,5 +1,5 @@
import { NgClass, NgIf, NgTemplateOutlet, PlatformLocation } from '@angular/common'
-import { Component, ElementRef, Inject, LOCALE_ID, NgZone, OnDestroy, OnInit, ViewChild } from '@angular/core'
+import { Component, ElementRef, LOCALE_ID, NgZone, OnDestroy, OnInit, inject, viewChild } from '@angular/core'
import { ActivatedRoute, Router, RouterLink } from '@angular/router'
import {
AuthService,
@@ -123,9 +123,33 @@ type URLOptions = {
]
})
export class VideoWatchComponent implements OnInit, OnDestroy {
- @ViewChild('videoWatchPlaylist', { static: true }) videoWatchPlaylist: VideoWatchPlaylistComponent
- @ViewChild('subscribeButton') subscribeButton: SubscribeButtonComponent
- @ViewChild('playerElement') playerElement: ElementRef<HTMLVideoElement>
+ private route = inject(ActivatedRoute)
+ private router = inject(Router)
+ private videoService = inject(VideoService)
+ private playlistService = inject(VideoPlaylistService)
+ private liveVideoService = inject(LiveVideoService)
+ private confirmService = inject(ConfirmService)
+ private authService = inject(AuthService)
+ private userService = inject(UserService)
+ private serverService = inject(ServerService)
+ private restExtractor = inject(RestExtractor)
+ private notifier = inject(Notifier)
+ private zone = inject(NgZone)
+ private videoCaptionService = inject(VideoCaptionService)
+ private videoChapterService = inject(VideoChapterService)
+ private hotkeysService = inject(HotkeysService)
+ private hooks = inject(HooksService)
+ private pluginService = inject(PluginService)
+ private peertubeSocket = inject(PeerTubeSocket)
+ private screenService = inject(ScreenService)
+ private videoFileTokenService = inject(VideoFileTokenService)
+ private location = inject(PlatformLocation)
+ private metaService = inject(MetaService)
+ private localeId = inject(LOCALE_ID)
+
+ readonly videoWatchPlaylist = viewChild<VideoWatchPlaylistComponent>('videoWatchPlaylist')
+ readonly subscribeButton = viewChild<SubscribeButtonComponent>('subscribeButton')
+ readonly playerElement = viewChild<ElementRef<HTMLVideoElement>>('playerElement')
peertubePlayer: PeerTubePlayer
theaterEnabled = false
@@ -161,32 +185,6 @@ export class VideoWatchComponent implements OnInit, OnDestroy {
private hotkeys: Hotkey[] = []
- constructor (
- private route: ActivatedRoute,
- private router: Router,
- private videoService: VideoService,
- private playlistService: VideoPlaylistService,
- private liveVideoService: LiveVideoService,
- private confirmService: ConfirmService,
- private authService: AuthService,
- private userService: UserService,
- private serverService: ServerService,
- private restExtractor: RestExtractor,
- private notifier: Notifier,
- private zone: NgZone,
- private videoCaptionService: VideoCaptionService,
- private videoChapterService: VideoChapterService,
- private hotkeysService: HotkeysService,
- private hooks: HooksService,
- private pluginService: PluginService,
- private peertubeSocket: PeerTubeSocket,
- private screenService: ScreenService,
- private videoFileTokenService: VideoFileTokenService,
- private location: PlatformLocation,
- private metaService: MetaService,
- @Inject(LOCALE_ID) private localeId: string
- ) { }
-
get user () {
return this.authService.getUser()
}
@@ -238,7 +236,7 @@ export class VideoWatchComponent implements OnInit, OnDestroy {
}
getCurrentPlaylistPosition () {
- return this.videoWatchPlaylist.currentPlaylistPosition
+ return this.videoWatchPlaylist().currentPlaylistPosition
}
onRecommendations (videos: Video[]) {
@@ -324,7 +322,7 @@ export class VideoWatchComponent implements OnInit, OnDestroy {
this.playlistPosition = 1
}
- this.videoWatchPlaylist.updatePlaylistIndex(this.playlistPosition)
+ this.videoWatchPlaylist().updatePlaylistIndex(this.playlistPosition)
const start = queryParams['start']
if (this.peertubePlayer?.getPlayer() && start) {
@@ -358,7 +356,6 @@ export class VideoWatchComponent implements OnInit, OnDestroy {
return this.liveVideoService.getVideoLive(video.uuid)
.pipe(map(live => ({ live, video })))
}),
-
switchMap(({ video, live }) => {
if (!videoRequiresFileToken(video)) return of({ video, live, videoFileToken: undefined })
@@ -413,7 +410,7 @@ export class VideoWatchComponent implements OnInit, OnDestroy {
next: playlist => {
this.playlist = playlist
- this.videoWatchPlaylist.loadPlaylistElements(playlist, !this.playlistPosition, this.playlistPosition)
+ this.videoWatchPlaylist().loadPlaylistElements(playlist, !this.playlistPosition, this.playlistPosition)
},
error: err => this.handleRequestError(err)
@@ -611,7 +608,7 @@ export class VideoWatchComponent implements OnInit, OnDestroy {
private hasNextVideo () {
if (this.playlist) {
- return this.videoWatchPlaylist.hasNextVideo()
+ return this.videoWatchPlaylist().hasNextVideo()
}
return true
@@ -619,7 +616,7 @@ export class VideoWatchComponent implements OnInit, OnDestroy {
private getNextVideoTitle () {
if (this.playlist) {
- return this.videoWatchPlaylist.getNextVideo()?.video?.name || ''
+ return this.videoWatchPlaylist().getNextVideo()?.video?.name || ''
}
return this.nextRecommendedVideoTitle
@@ -628,7 +625,7 @@ export class VideoWatchComponent implements OnInit, OnDestroy {
private playNextVideoInAngularZone () {
this.zone.run(() => {
if (this.playlist) {
- this.videoWatchPlaylist.navigateToNextPlaylistVideo()
+ this.videoWatchPlaylist().navigateToNextPlaylistVideo()
return
}
@@ -669,7 +666,7 @@ export class VideoWatchComponent implements OnInit, OnDestroy {
const { urlOptions } = options
return {
- playerElement: () => this.playerElement.nativeElement,
+ playerElement: () => this.playerElement().nativeElement,
enableHotkeys: true,
inactivityTimeout: 2500,
@@ -848,10 +845,10 @@ export class VideoWatchComponent implements OnInit, OnDestroy {
videoRatio: video.aspectRatio,
previousVideo: {
- enabled: this.playlist && this.videoWatchPlaylist.hasPreviousVideo(),
+ enabled: this.playlist && this.videoWatchPlaylist().hasPreviousVideo(),
handler: this.playlist
- ? () => this.zone.run(() => this.videoWatchPlaylist.navigateToPreviousPlaylistVideo())
+ ? () => this.zone.run(() => this.videoWatchPlaylist().navigateToPreviousPlaylistVideo())
: undefined,
displayControlBarButton: !!this.playlist
@@ -978,8 +975,9 @@ export class VideoWatchComponent implements OnInit, OnDestroy {
if (this.isUserLoggedIn()) {
this.hotkeys = this.hotkeys.concat([
new Hotkey('shift+s', () => {
- if (this.subscribeButton.isSubscribedToAll()) this.subscribeButton.unsubscribe()
- else this.subscribeButton.subscribe()
+ const subscribeButton = this.subscribeButton()
+ if (subscribeButton.isSubscribedToAll()) subscribeButton.unsubscribe()
+ else subscribeButton.subscribe()
return false
}, $localize`Subscribe to the account`)
diff --git a/client/src/app/+videos/video-list/overview/overview.service.ts b/client/src/app/+videos/video-list/overview/overview.service.ts
index 6fba0d9b53..bec0554ed8 100644
--- a/client/src/app/+videos/video-list/overview/overview.service.ts
+++ b/client/src/app/+videos/video-list/overview/overview.service.ts
@@ -1,7 +1,7 @@
import { forkJoin, Observable, of } from 'rxjs'
import { catchError, map, switchMap, tap } from 'rxjs/operators'
import { HttpClient, HttpParams } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { RestExtractor, ServerService } from '@app/core'
import { immutableAssign } from '@app/helpers'
import { objectKeysTyped, peertubeTranslate } from '@peertube/peertube-core-utils'
@@ -12,25 +12,23 @@ import { VideoService } from '@app/shared/shared-main/video/video.service'
@Injectable()
export class OverviewService {
- static BASE_OVERVIEW_URL = environment.apiUrl + '/api/v1/overviews/'
+ private authHttp = inject(HttpClient)
+ private restExtractor = inject(RestExtractor)
+ private videosService = inject(VideoService)
+ private serverService = inject(ServerService)
- constructor (
- private authHttp: HttpClient,
- private restExtractor: RestExtractor,
- private videosService: VideoService,
- private serverService: ServerService
- ) {}
+ static BASE_OVERVIEW_URL = environment.apiUrl + '/api/v1/overviews/'
getVideosOverview (page: number): Observable<VideosOverview> {
let params = new HttpParams()
params = params.append('page', page + '')
return this.authHttp
- .get<VideosOverviewServer>(OverviewService.BASE_OVERVIEW_URL + 'videos', { params })
- .pipe(
- switchMap(serverVideosOverview => this.updateVideosOverview(serverVideosOverview)),
- catchError(err => this.restExtractor.handleError(err))
- )
+ .get<VideosOverviewServer>(OverviewService.BASE_OVERVIEW_URL + 'videos', { params })
+ .pipe(
+ switchMap(serverVideosOverview => this.updateVideosOverview(serverVideosOverview)),
+ catchError(err => this.restExtractor.handleError(err))
+ )
}
private updateVideosOverview (serverVideosOverview: VideosOverviewServer): Observable<VideosOverview> {
@@ -64,16 +62,15 @@ export class OverviewService {
// Translate categories
switchMap(() => {
return this.serverService.getServerLocale()
- .pipe(
- tap(translations => {
- for (const c of videosOverviewResult.categories) {
- c.category.label = peertubeTranslate(c.category.label, translations)
- }
- })
- )
+ .pipe(
+ tap(translations => {
+ for (const c of videosOverviewResult.categories) {
+ c.category.label = peertubeTranslate(c.category.label, translations)
+ }
+ })
+ )
}),
map(() => videosOverviewResult)
)
}
-
}
diff --git a/client/src/app/+videos/video-list/overview/video-overview.component.ts b/client/src/app/+videos/video-list/overview/video-overview.component.ts
index 485a867b0c..b1b7fc117a 100644
--- a/client/src/app/+videos/video-list/overview/video-overview.component.ts
+++ b/client/src/app/+videos/video-list/overview/video-overview.component.ts
@@ -1,5 +1,5 @@
import { CommonModule } from '@angular/common'
-import { AfterViewChecked, ChangeDetectorRef, Component, ElementRef, OnDestroy, OnInit, ViewChild } from '@angular/core'
+import { AfterViewChecked, ChangeDetectorRef, Component, ElementRef, OnDestroy, OnInit, inject, viewChild } from '@angular/core'
import { RouterLink } from '@angular/router'
import { DisableForReuseHook, Notifier, User, UserService } from '@app/core'
import { ActorAvatarComponent, ActorAvatarInput } from '@app/shared/shared-actor-image/actor-avatar.component'
@@ -24,7 +24,12 @@ import { OverviewService } from './overview.service'
]
})
export class VideoOverviewComponent implements OnInit, OnDestroy, AfterViewChecked, DisableForReuseHook {
- @ViewChild('quickAccessContent') quickAccessContent: ElementRef
+ private notifier = inject(Notifier)
+ private userService = inject(UserService)
+ private overviewService = inject(OverviewService)
+ private cd = inject(ChangeDetectorRef)
+
+ readonly quickAccessContent = viewChild<ElementRef>('quickAccessContent')
onDataSubject = new Subject<any>()
@@ -60,13 +65,6 @@ export class VideoOverviewComponent implements OnInit, OnDestroy, AfterViewCheck
private userSub: Subscription
- constructor (
- private notifier: Notifier,
- private userService: UserService,
- private overviewService: OverviewService,
- private cd: ChangeDetectorRef
- ) { }
-
ngOnInit () {
this.loadMoreResults()
@@ -93,7 +91,7 @@ export class VideoOverviewComponent implements OnInit, OnDestroy, AfterViewCheck
this.checkQuickAccessOverflow = false
- const el = this.quickAccessContent.nativeElement as HTMLElement
+ const el = this.quickAccessContent().nativeElement as HTMLElement
this.quickAccessOverflow = el.scrollWidth > el.clientWidth
this.cd.detectChanges()
}
@@ -120,62 +118,62 @@ export class VideoOverviewComponent implements OnInit, OnDestroy, AfterViewCheck
this.isLoading = true
this.overviewService.getVideosOverview(this.currentPage)
- .subscribe({
- next: overview => {
- this.isLoading = false
-
- if (overview.tags.length === 0 && overview.channels.length === 0 && overview.categories.length === 0) {
- this.lastWasEmpty = true
- if (this.loaded === false) this.notResults = true
-
- return
- }
-
- this.loaded = true
- this.onDataSubject.next(overview)
-
- for (const value of overview.categories) {
- this.objects.push({
- buttonLabel: $localize`Browse "${value.category.label}" videos`,
- label: value.category.label,
- routerLink: [ '/search' ],
- queryParams: { categoryOneOf: [ value.category.id ] },
- videos: value.videos,
- type: $localize`category`
- })
- }
-
- for (const value of overview.tags) {
- this.objects.push({
- buttonLabel: $localize`Browse "#${value.tag}" videos`,
- label: `#${value.tag}`,
- routerLink: [ '/search' ],
- queryParams: { tagsOneOf: [ value.tag ] },
- videos: value.videos,
- type: $localize`tag`
- })
- }
-
- for (const value of overview.channels) {
- this.objects.push({
- buttonLabel: $localize`View the channel`,
- label: value.videos[0].byVideoChannel,
- routerLink: [ '/c', value.videos[0].byVideoChannel ],
- queryParams: {},
- videos: value.videos,
- channel: value.channel,
- type: $localize`channel`
- })
- }
-
- this.quickAccessLinks = this.objects.map(o => o)
- this.checkQuickAccessOverflow = true
- },
-
- error: err => {
- this.notifier.error(err.message)
- this.isLoading = false
+ .subscribe({
+ next: overview => {
+ this.isLoading = false
+
+ if (overview.tags.length === 0 && overview.channels.length === 0 && overview.categories.length === 0) {
+ this.lastWasEmpty = true
+ if (this.loaded === false) this.notResults = true
+
+ return
}
- })
+
+ this.loaded = true
+ this.onDataSubject.next(overview)
+
+ for (const value of overview.categories) {
+ this.objects.push({
+ buttonLabel: $localize`Browse "${value.category.label}" videos`,
+ label: value.category.label,
+ routerLink: [ '/search' ],
+ queryParams: { categoryOneOf: [ value.category.id ] },
+ videos: value.videos,
+ type: $localize`category`
+ })
+ }
+
+ for (const value of overview.tags) {
+ this.objects.push({
+ buttonLabel: $localize`Browse "#${value.tag}" videos`,
+ label: `#${value.tag}`,
+ routerLink: [ '/search' ],
+ queryParams: { tagsOneOf: [ value.tag ] },
+ videos: value.videos,
+ type: $localize`tag`
+ })
+ }
+
+ for (const value of overview.channels) {
+ this.objects.push({
+ buttonLabel: $localize`View the channel`,
+ label: value.videos[0].byVideoChannel,
+ routerLink: [ '/c', value.videos[0].byVideoChannel ],
+ queryParams: {},
+ videos: value.videos,
+ channel: value.channel,
+ type: $localize`channel`
+ })
+ }
+
+ this.quickAccessLinks = this.objects.map(o => o)
+ this.checkQuickAccessOverflow = true
+ },
+
+ error: err => {
+ this.notifier.error(err.message)
+ this.isLoading = false
+ }
+ })
}
}
diff --git a/client/src/app/+videos/video-list/video-user-subscriptions.component.ts b/client/src/app/+videos/video-list/video-user-subscriptions.component.ts
index a079f78887..d1331c5eaa 100644
--- a/client/src/app/+videos/video-list/video-user-subscriptions.component.ts
+++ b/client/src/app/+videos/video-list/video-user-subscriptions.component.ts
@@ -1,6 +1,6 @@
import { firstValueFrom } from 'rxjs'
import { switchMap, tap } from 'rxjs/operators'
-import { Component } from '@angular/core'
+import { Component, inject } from '@angular/core'
import { AuthService, ComponentPaginationLight, DisableForReuseHook, ScopedTokensService } from '@app/core'
import { HooksService } from '@app/core/plugins/hooks.service'
import { VideoSortField } from '@peertube/peertube-models'
@@ -15,6 +15,12 @@ import { VideoFilters } from '@app/shared/shared-video-miniature/video-filters.m
imports: [ VideosListComponent ]
})
export class VideoUserSubscriptionsComponent implements DisableForReuseHook {
+ private authService = inject(AuthService)
+ private userSubscription = inject(UserSubscriptionService)
+ private hooks = inject(HooksService)
+ private videoService = inject(VideoService)
+ private scopedTokensService = inject(ScopedTokensService)
+
getVideosObservableFunction = this.getVideosObservable.bind(this)
getSyndicationItemsFunction = this.getSyndicationItems.bind(this)
@@ -32,16 +38,6 @@ export class VideoUserSubscriptionsComponent implements DisableForReuseHook {
private feedToken: string
- constructor (
- private authService: AuthService,
- private userSubscription: UserSubscriptionService,
- private hooks: HooksService,
- private videoService: VideoService,
- private scopedTokensService: ScopedTokensService
- ) {
-
- }
-
getVideosObservable (pagination: ComponentPaginationLight, filters: VideoFilters) {
const params = {
...filters.toVideosAPIObject(),
diff --git a/client/src/app/+videos/video-list/videos-list-all.component.ts b/client/src/app/+videos/video-list/videos-list-all.component.ts
index 370fe20e49..fbafdd47b8 100644
--- a/client/src/app/+videos/video-list/videos-list-all.component.ts
+++ b/client/src/app/+videos/video-list/videos-list-all.component.ts
@@ -1,4 +1,4 @@
-import { Component, OnDestroy, OnInit } from '@angular/core'
+import { Component, OnDestroy, OnInit, inject } from '@angular/core'
import { ActivatedRoute } from '@angular/router'
import { ComponentPaginationLight, DisableForReuseHook, MetaService } from '@app/core'
import { HooksService } from '@app/core/plugins/hooks.service'
@@ -15,6 +15,11 @@ import { VideosListComponent } from '../../shared/shared-video-miniature/videos-
]
})
export class VideosListAllComponent implements OnInit, OnDestroy, DisableForReuseHook {
+ private route = inject(ActivatedRoute)
+ private videoService = inject(VideoService)
+ private hooks = inject(HooksService)
+ private meta = inject(MetaService)
+
getVideosObservableFunction = this.getVideosObservable.bind(this)
getSyndicationItemsFunction = this.getSyndicationItems.bind(this)
@@ -33,14 +38,6 @@ export class VideosListAllComponent implements OnInit, OnDestroy, DisableForReus
private routeSub: Subscription
- constructor (
- private route: ActivatedRoute,
- private videoService: VideoService,
- private hooks: HooksService,
- private meta: MetaService
- ) {
- }
-
ngOnInit () {
this.defaultSort = '-publishedAt'
this.defaultScope = 'federated'
diff --git a/client/src/app/app.component.ts b/client/src/app/app.component.ts
index 9a866c8f9a..9b87f0498a 100644
--- a/client/src/app/app.component.ts
+++ b/client/src/app/app.component.ts
@@ -1,9 +1,9 @@
import { forkJoin } from 'rxjs'
import { filter, first, map } from 'rxjs/operators'
import { DOCUMENT, getLocaleDirection, NgClass, NgIf, PlatformLocation } from '@angular/common'
-import { AfterViewInit, Component, Inject, LOCALE_ID, OnDestroy, OnInit, ViewChild } from '@angular/core'
+import { AfterViewInit, Component, LOCALE_ID, OnDestroy, OnInit, inject, viewChild } from '@angular/core'
import { DomSanitizer, SafeHtml } from '@angular/platform-browser'
-import { Event, GuardsCheckStart, RouteConfigLoadEnd, RouteConfigLoadStart, Router, RouterLink, RouterOutlet } from '@angular/router'
+import { Event, GuardsCheckStart, RouteConfigLoadEnd, RouteConfigLoadStart, Router, RouterOutlet } from '@angular/router'
import {
AuthService,
Hotkey,
@@ -37,7 +37,7 @@ import { HotkeysCheatSheetComponent } from './hotkeys/hotkeys-cheat-sheet.compon
import { MenuComponent } from './menu/menu.component'
import { ConfirmComponent } from './modal/confirm.component'
import { GlobalIconComponent, GlobalIconName } from './shared/shared-icons/global-icon.component'
-import { ButtonComponent } from './shared/shared-main/buttons/button.component'
+
import { InstanceService } from './shared/shared-main/instance/instance.service'
@Component({
@@ -48,7 +48,6 @@ import { InstanceService } from './shared/shared-main/instance/instance.service'
NgIf,
HotkeysCheatSheetComponent,
NgClass,
- RouterLink,
HeaderComponent,
MenuComponent,
GlobalIconComponent,
@@ -60,17 +59,37 @@ import { InstanceService } from './shared/shared-main/instance/instance.service'
AccountSetupWarningModalComponent,
AdminWelcomeModalComponent,
InstanceConfigWarningModalComponent,
- CustomModalComponent,
- ButtonComponent
+ CustomModalComponent
]
})
export class AppComponent implements OnInit, AfterViewInit, OnDestroy {
+ private document = inject<Document>(DOCUMENT)
+ private localeId = inject(LOCALE_ID)
+ private router = inject(Router)
+ private authService = inject(AuthService)
+ private serverService = inject(ServerService)
+ private peertubeRouter = inject(PeerTubeRouterService)
+ private pluginService = inject(PluginService)
+ private instanceService = inject(InstanceService)
+ private domSanitizer = inject(DomSanitizer)
+ private screenService = inject(ScreenService)
+ private hotkeysService = inject(HotkeysService)
+ private hooks = inject(HooksService)
+ private location = inject(PlatformLocation)
+ private modalService = inject(NgbModal)
+ private markdownService = inject(MarkdownService)
+ private ngbConfig = inject(NgbConfig)
+ private loadingBar = inject(LoadingBarService)
+ private scrollService = inject(ScrollService)
+ private userLocalStorage = inject(UserLocalStorageService)
+ menu = inject(MenuService)
+
private static LS_BROADCAST_MESSAGE = 'app-broadcast-message-dismissed'
- @ViewChild('accountSetupWarningModal') accountSetupWarningModal: AccountSetupWarningModalComponent
- @ViewChild('adminWelcomeModal') adminWelcomeModal: AdminWelcomeModalComponent
- @ViewChild('instanceConfigWarningModal') instanceConfigWarningModal: InstanceConfigWarningModalComponent
- @ViewChild('customModal') customModal: CustomModalComponent
+ readonly accountSetupWarningModal = viewChild<AccountSetupWarningModalComponent>('accountSetupWarningModal')
+ readonly adminWelcomeModal = viewChild<AdminWelcomeModalComponent>('adminWelcomeModal')
+ readonly instanceConfigWarningModal = viewChild<InstanceConfigWarningModalComponent>('instanceConfigWarningModal')
+ readonly customModal = viewChild<CustomModalComponent>('customModal')
customCSS: SafeHtml
broadcastMessage: { message: string, dismissable: boolean, class: string } | null = null
@@ -79,28 +98,7 @@ export class AppComponent implements OnInit, AfterViewInit, OnDestroy {
private serverConfig: HTMLServerConfig
private userLoaded = false
- constructor (
- @Inject(DOCUMENT) private document: Document,
- @Inject(LOCALE_ID) private localeId: string,
- private router: Router,
- private authService: AuthService,
- private serverService: ServerService,
- private peertubeRouter: PeerTubeRouterService,
- private pluginService: PluginService,
- private instanceService: InstanceService,
- private domSanitizer: DomSanitizer,
- private screenService: ScreenService,
- private hotkeysService: HotkeysService,
- private hooks: HooksService,
- private location: PlatformLocation,
- private modalService: NgbModal,
- private markdownService: MarkdownService,
- private ngbConfig: NgbConfig,
- private loadingBar: LoadingBarService,
- private scrollService: ScrollService,
- private userLocalStorage: UserLocalStorageService,
- public menu: MenuService
- ) {
+ constructor () {
this.ngbConfig.animation = false
}
@@ -159,7 +157,7 @@ export class AppComponent implements OnInit, AfterViewInit, OnDestroy {
}
ngAfterViewInit () {
- this.pluginService.initializeCustomModal(this.customModal)
+ this.pluginService.initializeCustomModal(this.customModal())
}
ngOnDestroy () {
@@ -279,11 +277,11 @@ export class AppComponent implements OnInit, AfterViewInit, OnDestroy {
private listenUserChangeForModals () {
this.authService.userInformationLoaded
- .pipe(map(() => this.authService.getUser()))
- .subscribe(user => {
- this.userLoaded = true
- this.openModalsIfNeeded(user)
- })
+ .pipe(map(() => this.authService.getUser()))
+ .subscribe(user => {
+ this.userLoaded = true
+ this.openModalsIfNeeded(user)
+ })
}
onModalCreated () {
@@ -304,30 +302,34 @@ export class AppComponent implements OnInit, AfterViewInit, OnDestroy {
}
private openAdminModalsIfNeeded (user: User) {
- if (!this.adminWelcomeModal) return
+ const adminWelcomeModal = this.adminWelcomeModal()
+ if (!adminWelcomeModal) return
- if (this.adminWelcomeModal.shouldOpen(user)) {
- return this.adminWelcomeModal.show()
+ if (adminWelcomeModal.shouldOpen(user)) {
+ return adminWelcomeModal.show()
}
- if (!this.instanceConfigWarningModal) return
- if (!this.instanceConfigWarningModal.shouldOpenByUser(user)) return
+ const instanceConfigWarningModal = this.instanceConfigWarningModal()
+ if (!instanceConfigWarningModal) return
+ if (!instanceConfigWarningModal.shouldOpenByUser(user)) return
forkJoin([
this.serverService.getConfig().pipe(first()),
this.instanceService.getAbout().pipe(first())
]).subscribe(([ config, about ]) => {
- if (this.instanceConfigWarningModal.shouldOpen(config, about)) {
- this.instanceConfigWarningModal.show(about)
+ const instanceConfigWarningModalValue = this.instanceConfigWarningModal()
+ if (instanceConfigWarningModalValue.shouldOpen(config, about)) {
+ instanceConfigWarningModalValue.show(about)
}
})
}
private openAccountModalsIfNeeded (user: User) {
- if (!this.accountSetupWarningModal) return
+ const accountSetupWarningModal = this.accountSetupWarningModal()
+ if (!accountSetupWarningModal) return
- if (this.accountSetupWarningModal.shouldOpen(user)) {
- this.accountSetupWarningModal.show(user)
+ if (accountSetupWarningModal.shouldOpen(user)) {
+ accountSetupWarningModal.show(user)
}
}
diff --git a/client/src/app/core/auth/auth.service.ts b/client/src/app/core/auth/auth.service.ts
index 40682ffff0..e55b56682e 100644
--- a/client/src/app/core/auth/auth.service.ts
+++ b/client/src/app/core/auth/auth.service.ts
@@ -1,5 +1,5 @@
import { HttpClient, HttpErrorResponse, HttpHeaders, HttpParams } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { Router } from '@angular/router'
import { Hotkey, HotkeysService } from '@app/core'
import { Notifier } from '@app/core/notification/notifier.service'
@@ -23,6 +23,12 @@ type UserLoginWithUserInformation = UserLoginWithUsername & User
@Injectable()
export class AuthService {
+ private http = inject(HttpClient)
+ private notifier = inject(Notifier)
+ private hotkeysService = inject(HotkeysService)
+ private restExtractor = inject(RestExtractor)
+ private router = inject(Router)
+
private static BASE_CLIENT_URL = environment.apiUrl + '/api/v1/oauth-clients/local'
private static BASE_TOKEN_URL = environment.apiUrl + '/api/v1/users/token'
private static BASE_REVOKE_TOKEN_URL = environment.apiUrl + '/api/v1/users/revoke-token'
@@ -43,13 +49,7 @@ export class AuthService {
private user: AuthUser = null
private refreshingTokenObservable: Observable<void>
- constructor (
- private http: HttpClient,
- private notifier: Notifier,
- private hotkeysService: HotkeysService,
- private restExtractor: RestExtractor,
- private router: Router
- ) {
+ constructor () {
this.loginChanged = new Subject<AuthStatus>()
this.loginChangedSource = this.loginChanged.asObservable()
@@ -83,30 +83,30 @@ export class AuthService {
loadClientCredentials () {
// Fetch the client_id/client_secret
this.http.get<OAuthClientLocal>(AuthService.BASE_CLIENT_URL)
- .pipe(catchError(res => this.restExtractor.handleError(res)))
- .subscribe({
- next: res => {
- this.clientId = res.client_id
- this.clientSecret = res.client_secret
+ .pipe(catchError(res => this.restExtractor.handleError(res)))
+ .subscribe({
+ next: res => {
+ this.clientId = res.client_id
+ this.clientSecret = res.client_secret
- peertubeLocalStorage.setItem(AuthService.LS_OAUTH_CLIENT_KEYS.CLIENT_ID, this.clientId)
- peertubeLocalStorage.setItem(AuthService.LS_OAUTH_CLIENT_KEYS.CLIENT_SECRET, this.clientSecret)
+ peertubeLocalStorage.setItem(AuthService.LS_OAUTH_CLIENT_KEYS.CLIENT_ID, this.clientId)
+ peertubeLocalStorage.setItem(AuthService.LS_OAUTH_CLIENT_KEYS.CLIENT_SECRET, this.clientSecret)
- logger.info('Client credentials loaded.')
- },
+ logger.info('Client credentials loaded.')
+ },
- error: err => {
- let errorMessage = err.message
+ error: err => {
+ let errorMessage = err.message
- if (err.status === HttpStatusCode.FORBIDDEN_403) {
- errorMessage = $localize`Cannot retrieve OAuth Client credentials: ${err.message}.
+ if (err.status === HttpStatusCode.FORBIDDEN_403) {
+ errorMessage = $localize`Cannot retrieve OAuth Client credentials: ${err.message}.
Ensure you have correctly configured PeerTube (config/ directory), in particular the "webserver" section.`
- }
-
- // We put a bigger timeout: this is an important message
- this.notifier.error(errorMessage, $localize`Error`, 7000)
}
- })
+
+ // We put a bigger timeout: this is an important message
+ this.notifier.error(errorMessage, $localize`Error`, 7000)
+ }
+ })
}
getRefreshToken () {
@@ -168,12 +168,12 @@ Ensure you have correctly configured PeerTube (config/ directory), in particular
if (otpToken) headers = headers.set('x-peertube-otp', otpToken)
return this.http.post<UserLogin>(AuthService.BASE_TOKEN_URL, objectToUrlEncoded(body), { headers })
- .pipe(
- map(res => Object.assign(res, { username })),
- mergeMap(res => this.mergeUserInformation(res)),
- map(res => this.handleLogin(res)),
- catchError(res => this.restExtractor.handleError(res))
- )
+ .pipe(
+ map(res => Object.assign(res, { username })),
+ mergeMap(res => this.mergeUserInformation(res)),
+ map(res => this.handleLogin(res)),
+ catchError(res => this.restExtractor.handleError(res))
+ )
}
logout () {
@@ -208,10 +208,10 @@ Ensure you have correctly configured PeerTube (config/ directory), in particular
// Form url encoded
const body = new HttpParams().set('refresh_token', refreshToken)
- .set('client_id', this.clientId)
- .set('client_secret', this.clientSecret)
- .set('response_type', 'code')
- .set('grant_type', 'refresh_token')
+ .set('client_id', this.clientId)
+ .set('client_secret', this.clientSecret)
+ .set('response_type', 'code')
+ .set('grant_type', 'refresh_token')
const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
@@ -245,13 +245,13 @@ Ensure you have correctly configured PeerTube (config/ directory), in particular
}
this.mergeUserInformation(obj)
- .subscribe({
- next: res => {
- this.user.patch(res)
+ .subscribe({
+ next: res => {
+ this.user.patch(res)
- this.userInformationLoaded.next(true)
- }
- })
+ this.userInformationLoaded.next(true)
+ }
+ })
}
isOTPMissingError (err: HttpErrorResponse) {
@@ -267,7 +267,7 @@ Ensure you have correctly configured PeerTube (config/ directory), in particular
const headers = new HttpHeaders().set('Authorization', `${obj.token_type} ${obj.access_token}`)
return this.http.get<UserServerModel>(AuthService.BASE_USER_INFORMATION_URL, { headers })
- .pipe(map(res => Object.assign(obj, res)))
+ .pipe(map(res => Object.assign(obj, res)))
}
private handleLogin (obj: UserLoginWithUserInformation) {
diff --git a/client/src/app/core/hotkeys/hotkeys.service.ts b/client/src/app/core/hotkeys/hotkeys.service.ts
index 2daab404f5..12f4885777 100644
--- a/client/src/app/core/hotkeys/hotkeys.service.ts
+++ b/client/src/app/core/hotkeys/hotkeys.service.ts
@@ -1,6 +1,6 @@
// Thanks to https://github.com/brtnshrdr/angular2-hotkeys
-import { Injectable, NgZone } from '@angular/core'
+import { Injectable, NgZone, inject } from '@angular/core'
import debug from 'debug'
import { Subject } from 'rxjs'
import { tinykeys } from 'tinykeys'
@@ -10,6 +10,8 @@ const debugLogger = debug('peertube:hotkeys')
@Injectable()
export class HotkeysService {
+ private zone = inject(NgZone)
+
cheatSheetToggle = new Subject<boolean>()
private hotkeys: Hotkey[] = []
@@ -20,7 +22,7 @@ export class HotkeysService {
private removeTinyKeysStore = new Map<Hotkey, (() => void)[]>()
- constructor (private zone: NgZone) {
+ constructor () {
this.initCheatSheet()
}
diff --git a/client/src/app/core/menu/menu.service.ts b/client/src/app/core/menu/menu.service.ts
index cf1633d007..1b0121a4ef 100644
--- a/client/src/app/core/menu/menu.service.ts
+++ b/client/src/app/core/menu/menu.service.ts
@@ -1,19 +1,19 @@
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { fromEvent } from 'rxjs'
import { debounceTime } from 'rxjs/operators'
import { LocalStorageService, ScreenService } from '../wrappers'
@Injectable()
export class MenuService {
+ private screenService = inject(ScreenService)
+ private localStorageService = inject(LocalStorageService)
+
private static LS_MENU_COLLAPSED = 'menu-collapsed'
private menuCollapsed = false
private menuChangedByUser = false
- constructor (
- private screenService: ScreenService,
- private localStorageService: LocalStorageService
- ) {
+ constructor () {
// Do not display menu on small or touch screens
if (this.screenService.isInSmallView() || this.screenService.isInTouchScreen()) {
this.setMenuCollapsed(true)
diff --git a/client/src/app/core/notification/notifier.service.ts b/client/src/app/core/notification/notifier.service.ts
index 15af5c1b65..54e7d69b2e 100644
--- a/client/src/app/core/notification/notifier.service.ts
+++ b/client/src/app/core/notification/notifier.service.ts
@@ -1,12 +1,12 @@
import { MessageService } from 'primeng/api'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { logger } from '@root-helpers/logger'
@Injectable()
export class Notifier {
- readonly TIMEOUT = 5000
+ private messageService = inject(MessageService)
- constructor (private messageService: MessageService) { }
+ readonly TIMEOUT = 5000
info (text: string, title?: string, timeout?: number, sticky?: boolean) {
if (!title) title = $localize`Info`
diff --git a/client/src/app/core/notification/peertube-socket.service.ts b/client/src/app/core/notification/peertube-socket.service.ts
index e0e470af04..c6d21c6408 100644
--- a/client/src/app/core/notification/peertube-socket.service.ts
+++ b/client/src/app/core/notification/peertube-socket.service.ts
@@ -1,6 +1,6 @@
import { Subject } from 'rxjs'
import { ManagerOptions, Socket, SocketOptions } from 'socket.io-client'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { LiveVideoEventPayload, LiveVideoEventType, UserNotification as UserNotificationServer } from '@peertube/peertube-models'
import { environment } from '../../../environments/environment'
import { AuthService } from '../auth'
@@ -9,6 +9,8 @@ export type NotificationEvent = 'new' | 'read' | 'read-all'
@Injectable()
export class PeerTubeSocket {
+ private auth = inject(AuthService)
+
private io: (uri: string, opts?: Partial<ManagerOptions & SocketOptions>) => Socket
private notificationSubject = new Subject<{ type: NotificationEvent, notification?: UserNotificationServer }>()
@@ -17,10 +19,6 @@ export class PeerTubeSocket {
private notificationSocket: Socket
private liveVideosSocket: Socket
- constructor (
- private auth: AuthService
- ) {}
-
async getMyNotificationsSocket () {
await this.initNotificationSocket()
diff --git a/client/src/app/core/plugins/hooks.service.ts b/client/src/app/core/plugins/hooks.service.ts
index 59c627c051..596451f169 100644
--- a/client/src/app/core/plugins/hooks.service.ts
+++ b/client/src/app/core/plugins/hooks.service.ts
@@ -1,6 +1,6 @@
import { from, Observable } from 'rxjs'
import { mergeMap, switchMap } from 'rxjs/operators'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { PluginService } from '@app/core/plugins/plugin.service'
import { logger } from '@root-helpers/logger'
import { ClientActionHookName, ClientFilterHookName, PluginClientScope } from '@peertube/peertube-models'
@@ -11,10 +11,10 @@ type ObservableFunction<U, T> = RawFunction<U, Observable<T>>
@Injectable()
export class HooksService {
- constructor (
- private authService: AuthService,
- private pluginService: PluginService
- ) {
+ private authService = inject(AuthService)
+ private pluginService = inject(PluginService)
+
+ constructor () {
// Run auth hooks
this.authService.userInformationLoaded
.subscribe(() => this.runAction('action:auth-user.information-loaded', 'common', { user: this.authService.getUser() }))
@@ -28,8 +28,13 @@ export class HooksService {
})
}
- wrapObsFun <P, R, H1 extends ClientFilterHookName, H2 extends ClientFilterHookName>
- (fun: ObservableFunction<P, R>, params: P, scope: PluginClientScope, hookParamName: H1, hookResultName: H2) {
+ wrapObsFun<P, R, H1 extends ClientFilterHookName, H2 extends ClientFilterHookName> (
+ fun: ObservableFunction<P, R>,
+ params: P,
+ scope: PluginClientScope,
+ hookParamName: H1,
+ hookResultName: H2
+ ) {
return from(this.pluginService.ensurePluginsAreLoaded(scope))
.pipe(
mergeMap(() => this.wrapObjectWithoutScopeLoad(params, hookParamName)),
@@ -38,8 +43,13 @@ export class HooksService {
)
}
- async wrapFun <P, R, H1 extends ClientFilterHookName, H2 extends ClientFilterHookName>
- (fun: RawFunction<P, R>, params: P, scope: PluginClientScope, hookParamName: H1, hookResultName: H2) {
+ async wrapFun<P, R, H1 extends ClientFilterHookName, H2 extends ClientFilterHookName> (
+ fun: RawFunction<P, R>,
+ params: P,
+ scope: PluginClientScope,
+ hookParamName: H1,
+ hookResultName: H2
+ ) {
await this.pluginService.ensurePluginsAreLoaded(scope)
const newParams = await this.wrapObjectWithoutScopeLoad(params, hookParamName)
diff --git a/client/src/app/core/plugins/plugin.service.ts b/client/src/app/core/plugins/plugin.service.ts
index 0165c83b4f..cb70e5b293 100644
--- a/client/src/app/core/plugins/plugin.service.ts
+++ b/client/src/app/core/plugins/plugin.service.ts
@@ -1,7 +1,7 @@
import { firstValueFrom, Observable, of } from 'rxjs'
import { catchError, map, shareReplay } from 'rxjs/operators'
import { HttpClient } from '@angular/common/http'
-import { Inject, Injectable, LOCALE_ID, NgZone } from '@angular/core'
+import { Injectable, LOCALE_ID, NgZone, inject } from '@angular/core'
import { VideoEditType } from '@app/+videos/+video-edit/shared/video-edit.type'
import { AuthService } from '@app/core/auth'
import { Notifier } from '@app/core/notification'
@@ -42,6 +42,15 @@ type FormFields = {
@Injectable()
export class PluginService implements ClientHook {
+ private authService = inject(AuthService)
+ private notifier = inject(Notifier)
+ private markdownRenderer = inject(MarkdownService)
+ private server = inject(ServerService)
+ private zone = inject(NgZone)
+ private authHttp = inject(HttpClient)
+ private restExtractor = inject(RestExtractor)
+ private localeId = inject(LOCALE_ID)
+
private static BASE_PLUGIN_API_URL = environment.apiUrl + '/api/v1/plugins'
private static BASE_PLUGIN_URL = environment.apiUrl + '/plugins'
@@ -52,10 +61,10 @@ export class PluginService implements ClientHook {
private formFields: FormFields = {
video: []
}
- private settingsScripts: { [ npmName: string ]: RegisterClientSettingsScriptOptions } = {}
+ private settingsScripts: { [npmName: string]: RegisterClientSettingsScriptOptions } = {}
private clientRoutes: {
- [ parentRoute in RegisterClientRouteOptions['parentRoute'] ]?: {
- [ route: string ]: RegisterClientRouteOptions
+ [parentRoute in RegisterClientRouteOptions['parentRoute']]?: {
+ [route: string]: RegisterClientRouteOptions
}
} = {}
@@ -63,16 +72,7 @@ export class PluginService implements ClientHook {
private actions = new Map<ClientDoActionName, ClientDoActionCallback>()
- constructor (
- private authService: AuthService,
- private notifier: Notifier,
- private markdownRenderer: MarkdownService,
- private server: ServerService,
- private zone: NgZone,
- private authHttp: HttpClient,
- private restExtractor: RestExtractor,
- @Inject(LOCALE_ID) private localeId: string
- ) {
+ constructor () {
this.loadTranslations()
this.pluginsManager = new PluginsManager({
@@ -102,7 +102,7 @@ export class PluginService implements ClientHook {
this.customModal = customModal
}
- runHook <T> (hookName: ClientHookName, result?: T, params?: any): Promise<T> {
+ runHook<T> (hookName: ClientHookName, result?: T, params?: any): Promise<T> {
return this.zone.runOutsideAngular(() => {
return this.pluginsManager.runHook(hookName, result, params)
})
@@ -190,10 +190,10 @@ export class PluginService implements ClientHook {
translateBy (npmName: string, toTranslate: string) {
const obs = this.translationsObservable
- .pipe(
- map(allTranslations => allTranslations[npmName]),
- map(translations => peertubeTranslate(toTranslate, translations))
- )
+ .pipe(
+ map(allTranslations => allTranslations[npmName]),
+ map(translations => peertubeTranslate(toTranslate, translations))
+ )
return firstValueFrom(obs)
}
@@ -268,10 +268,10 @@ export class PluginService implements ClientHook {
const path = PluginService.BASE_PLUGIN_API_URL + '/' + npmName + '/public-settings'
const obs = this.authHttp.get<PublicServerSetting>(path)
- .pipe(
- map(p => p.publicSettings),
- catchError(res => this.restExtractor.handleError(res))
- )
+ .pipe(
+ map(p => p.publicSettings),
+ catchError(res => this.restExtractor.handleError(res))
+ )
return firstValueFrom(obs)
},
@@ -337,7 +337,7 @@ export class PluginService implements ClientHook {
if (isDefaultLocale(completeLocale)) this.translationsObservable = of({}).pipe(shareReplay())
this.translationsObservable = this.authHttp
- .get<PluginTranslation>(PluginService.BASE_PLUGIN_URL + '/translations/' + completeLocale + '.json')
- .pipe(shareReplay())
+ .get<PluginTranslation>(PluginService.BASE_PLUGIN_URL + '/translations/' + completeLocale + '.json')
+ .pipe(shareReplay())
}
}
diff --git a/client/src/app/core/renderer/html-renderer.service.ts b/client/src/app/core/renderer/html-renderer.service.ts
index d41d89d15a..d3e2910704 100644
--- a/client/src/app/core/renderer/html-renderer.service.ts
+++ b/client/src/app/core/renderer/html-renderer.service.ts
@@ -1,4 +1,4 @@
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import {
getDefaultSanitizedHrefAttributes,
getDefaultSanitizedSchemes,
@@ -9,10 +9,12 @@ import { LinkifierService } from './linkifier.service'
@Injectable()
export class HtmlRendererService {
+ private linkifier = inject(LinkifierService)
+
private simpleDomPurify: DOMPurifyI
private enhancedDomPurify: DOMPurifyI
- constructor (private linkifier: LinkifierService) {
+ constructor () {
this.simpleDomPurify = DOMPurify()
this.enhancedDomPurify = DOMPurify()
diff --git a/client/src/app/core/renderer/markdown.service.ts b/client/src/app/core/renderer/markdown.service.ts
index 5603e54874..c5d84ca6b3 100644
--- a/client/src/app/core/renderer/markdown.service.ts
+++ b/client/src/app/core/renderer/markdown.service.ts
@@ -1,4 +1,4 @@
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import {
buildVideoLink,
COMPLETE_RULES,
@@ -36,6 +36,8 @@ type MarkdownParserConfigs = {
@Injectable()
export class MarkdownService {
+ private htmlRenderer = inject(HtmlRendererService)
+
private markdownParsers: MarkdownParsers = {
textMarkdownIt: null,
textWithHTMLMarkdownIt: null,
@@ -61,8 +63,6 @@ export class MarkdownService {
private emojiModule: any
- constructor (private htmlRenderer: HtmlRendererService) {}
-
textMarkdownToHTML (options: {
markdown: string
withHtml?: boolean // default false
diff --git a/client/src/app/core/rest/rest-extractor.service.ts b/client/src/app/core/rest/rest-extractor.service.ts
index a4ccf13f66..808af21e72 100644
--- a/client/src/app/core/rest/rest-extractor.service.ts
+++ b/client/src/app/core/rest/rest-extractor.service.ts
@@ -1,6 +1,6 @@
import { throwError as observableThrowError } from 'rxjs'
import { HttpHeaderResponse } from '@angular/common/http'
-import { Inject, Injectable, LOCALE_ID } from '@angular/core'
+import { Injectable, LOCALE_ID, inject } from '@angular/core'
import { Router } from '@angular/router'
import { DateFormat, dateToHuman } from '@app/helpers'
import { HttpStatusCode, HttpStatusCodeType, ResultList } from '@peertube/peertube-models'
@@ -8,13 +8,10 @@ import { logger } from '@root-helpers/logger'
@Injectable()
export class RestExtractor {
+ private localeId = inject(LOCALE_ID)
+ private router = inject(Router)
- constructor (
- @Inject(LOCALE_ID) private localeId: string,
- private router: Router
- ) { }
-
- applyToResultListData <T, A, U> (
+ applyToResultListData<T, A, U> (
result: ResultList<T>,
fun: (data: T, ...args: A[]) => U,
additionalArgs: A[] = []
@@ -27,7 +24,7 @@ export class RestExtractor {
}
}
- convertResultListDateToHuman <T> (
+ convertResultListDateToHuman<T> (
result: ResultList<T>,
fieldsToConvert: string[] = [ 'createdAt' ],
format?: DateFormat
diff --git a/client/src/app/core/routing/can-deactivate-guard.service.ts b/client/src/app/core/routing/can-deactivate-guard.service.ts
index 7d63793cd6..ff617bcd36 100644
--- a/client/src/app/core/routing/can-deactivate-guard.service.ts
+++ b/client/src/app/core/routing/can-deactivate-guard.service.ts
@@ -1,6 +1,6 @@
import debug from 'debug'
import { Observable } from 'rxjs'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { ConfirmService } from '@app/core/confirm'
export type CanComponentDeactivateResult = { text?: string, canDeactivate: Observable<boolean> | boolean }
@@ -13,8 +13,7 @@ export interface CanComponentDeactivate {
@Injectable()
export class CanDeactivateGuard {
-
- constructor (private confirmService: ConfirmService) { }
+ private confirmService = inject(ConfirmService)
canDeactivate (component: CanComponentDeactivate) {
const result = component.canDeactivate()
@@ -28,5 +27,4 @@ export class CanDeactivateGuard {
$localize`Warning`
)
}
-
}
diff --git a/client/src/app/core/routing/login-guard.service.ts b/client/src/app/core/routing/login-guard.service.ts
index be0ced881e..47fe00849d 100644
--- a/client/src/app/core/routing/login-guard.service.ts
+++ b/client/src/app/core/routing/login-guard.service.ts
@@ -1,15 +1,12 @@
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'
import { AuthService } from '../auth/auth.service'
import { RedirectService } from './redirect.service'
@Injectable()
export class LoginGuard {
-
- constructor (
- private auth: AuthService,
- private redirectService: RedirectService
- ) {}
+ private auth = inject(AuthService)
+ private redirectService = inject(RedirectService)
canActivate (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (this.auth.isLoggedIn() === true) return true
diff --git a/client/src/app/core/routing/meta-guard.service.ts b/client/src/app/core/routing/meta-guard.service.ts
index b68e06abe6..a4b4061415 100644
--- a/client/src/app/core/routing/meta-guard.service.ts
+++ b/client/src/app/core/routing/meta-guard.service.ts
@@ -1,11 +1,10 @@
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { ActivatedRouteSnapshot } from '@angular/router'
import { MetaService } from './meta.service'
@Injectable()
export class MetaGuard {
-
- constructor (private meta: MetaService) { }
+ private meta = inject(MetaService)
canActivate (route: ActivatedRouteSnapshot): boolean {
const metaSettings = route.data?.meta
diff --git a/client/src/app/core/routing/meta.service.ts b/client/src/app/core/routing/meta.service.ts
index c2cd1205ae..a5f890184d 100644
--- a/client/src/app/core/routing/meta.service.ts
+++ b/client/src/app/core/routing/meta.service.ts
@@ -1,4 +1,4 @@
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { Meta, Title } from '@angular/platform-browser'
import { getOriginUrl } from '@app/helpers'
import { getDefaultRSSFeeds } from '@peertube/peertube-core-utils'
@@ -11,13 +11,13 @@ export interface MetaSettings {
@Injectable()
export class MetaService {
+ private titleService = inject(Title)
+ private meta = inject(Meta)
+ private server = inject(ServerService)
+
private config: HTMLServerConfig
- constructor (
- private titleService: Title,
- private meta: Meta,
- private server: ServerService
- ) {
+ constructor () {
this.config = this.server.getHTMLConfig()
}
@@ -48,7 +48,7 @@ export class MetaService {
setRSSFeeds (rssFeeds: { title: string, url: string }[]) {
const head = document.getElementsByTagName('head')[0]
- head.querySelectorAll('link[rel="alternate"]').forEach((el) => head.removeChild(el))
+ head.querySelectorAll('link[rel="alternate"]').forEach(el => head.removeChild(el))
for (const rssFeed of rssFeeds) {
const link = document.createElement('link')
diff --git a/client/src/app/core/routing/peertube-router.service.ts b/client/src/app/core/routing/peertube-router.service.ts
index 35716cc794..d307628a62 100644
--- a/client/src/app/core/routing/peertube-router.service.ts
+++ b/client/src/app/core/routing/peertube-router.service.ts
@@ -1,5 +1,5 @@
import { filter } from 'rxjs/operators'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { ActivatedRoute, ActivatedRouteSnapshot, Event, NavigationEnd, Router, Scroll } from '@angular/router'
import { ServerService } from '../server'
@@ -11,13 +11,11 @@ export const enum RouterSetting {
@Injectable()
export class PeerTubeRouterService {
- static readonly ROUTE_SETTING_NAME = 's'
+ private route = inject(ActivatedRoute)
+ private router = inject(Router)
+ private server = inject(ServerService)
- constructor (
- private route: ActivatedRoute,
- private router: Router,
- private server: ServerService
- ) { }
+ static readonly ROUTE_SETTING_NAME = 's'
addRouteSetting (toAdd: RouterSetting) {
if (this.hasRouteSetting(toAdd)) return
@@ -74,5 +72,4 @@ export class PeerTubeRouterService {
return this.router.navigate(baseRoute, { queryParams })
}
-
}
diff --git a/client/src/app/core/routing/redirect.service.ts b/client/src/app/core/routing/redirect.service.ts
index 5be4a96d67..c88b77ad56 100644
--- a/client/src/app/core/routing/redirect.service.ts
+++ b/client/src/app/core/routing/redirect.service.ts
@@ -1,4 +1,4 @@
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { NavigationCancel, NavigationEnd, Router } from '@angular/router'
import { VideoSortField } from '@peertube/peertube-models'
import { logger } from '@root-helpers/logger'
@@ -12,6 +12,10 @@ const debugLogger = debug('peertube:router:RedirectService')
@Injectable()
export class RedirectService {
+ private router = inject(Router)
+ private serverService = inject(ServerService)
+ private storage = inject(SessionStorageService)
+
private static SESSION_STORAGE_LATEST_SESSION_URL_KEY = 'redirect-latest-session-url'
// Default route could change according to the instance configuration
@@ -27,14 +31,6 @@ export class RedirectService {
private defaultTrendingAlgorithm = RedirectService.INIT_DEFAULT_TRENDING_ALGORITHM
private defaultRoute = RedirectService.INIT_DEFAULT_ROUTE
- constructor (
- private router: Router,
- private serverService: ServerService,
- private storage: SessionStorageService
- ) {
-
- }
-
init () {
const config = this.serverService.getHTMLConfig()
if (config.instance.defaultClientRoute) {
@@ -113,16 +109,15 @@ export class RedirectService {
logger.info(`Redirecting to ${this.defaultRoute}...`)
this.router.navigateByUrl(this.defaultRoute, { skipLocationChange })
- .then(() => this.redirectingToHomepage = false)
- .catch(err => {
- this.redirectingToHomepage = false
-
- logger.error(`Cannot navigate to ${this.defaultRoute}, resetting default route to ${RedirectService.INIT_DEFAULT_ROUTE}`, err)
+ .then(() => this.redirectingToHomepage = false)
+ .catch(err => {
+ this.redirectingToHomepage = false
- this.defaultRoute = RedirectService.INIT_DEFAULT_ROUTE
- return this.router.navigateByUrl(this.defaultRoute, { skipLocationChange })
- })
+ logger.error(`Cannot navigate to ${this.defaultRoute}, resetting default route to ${RedirectService.INIT_DEFAULT_ROUTE}`, err)
+ this.defaultRoute = RedirectService.INIT_DEFAULT_ROUTE
+ return this.router.navigateByUrl(this.defaultRoute, { skipLocationChange })
+ })
}
redirectToLogin () {
diff --git a/client/src/app/core/routing/scroll.service.ts b/client/src/app/core/routing/scroll.service.ts
index 92b7772a7e..c2a31ee485 100644
--- a/client/src/app/core/routing/scroll.service.ts
+++ b/client/src/app/core/routing/scroll.service.ts
@@ -1,7 +1,7 @@
import debug from 'debug'
import { pairwise } from 'rxjs'
import { ViewportScroller } from '@angular/common'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { RouterSetting } from '../'
import { PeerTubeRouterService } from './peertube-router.service'
import { logger } from '@root-helpers/logger'
@@ -10,14 +10,11 @@ const debugLogger = debug('peertube:main:ScrollService')
@Injectable()
export class ScrollService {
+ private viewportScroller = inject(ViewportScroller)
+ private peertubeRouter = inject(PeerTubeRouterService)
private resetScroll = true
- constructor (
- private viewportScroller: ViewportScroller,
- private peertubeRouter: PeerTubeRouterService
- ) { }
-
enableScrollRestoration () {
// We'll manage scroll restoration ourselves
this.viewportScroller.setHistoryScrollRestoration('manual')
@@ -29,40 +26,40 @@ export class ScrollService {
private produceScroll () {
// When we add the a-state parameter, we don't want to alter the scroll
this.peertubeRouter.getNavigationEndEvents().pipe(pairwise())
- .subscribe(([ e1, e2 ]) => {
- try {
- this.resetScroll = false
-
- const previousUrl = new URL(window.location.origin + e1.urlAfterRedirects)
- const nextUrl = new URL(window.location.origin + e2.urlAfterRedirects)
-
- if (previousUrl.pathname !== nextUrl.pathname) {
- this.resetScroll = true
- return
- }
-
- if (this.peertubeRouter.hasRouteSetting(RouterSetting.DISABLE_SCROLL_RESTORE)) {
- this.resetScroll = false
- return
- }
-
- // Remove route settings from the comparison
- const nextSearchParams = nextUrl.searchParams
- nextSearchParams.delete(PeerTubeRouterService.ROUTE_SETTING_NAME)
-
- const previousSearchParams = previousUrl.searchParams
-
- nextSearchParams.sort()
- previousSearchParams.sort()
-
- if (nextSearchParams.toString() !== previousSearchParams.toString()) {
- this.resetScroll = true
- }
- } catch (err) {
- logger.error('Cannot parse URL to check next scroll.', err)
- this.resetScroll = true
- }
- })
+ .subscribe(([ e1, e2 ]) => {
+ try {
+ this.resetScroll = false
+
+ const previousUrl = new URL(window.location.origin + e1.urlAfterRedirects)
+ const nextUrl = new URL(window.location.origin + e2.urlAfterRedirects)
+
+ if (previousUrl.pathname !== nextUrl.pathname) {
+ this.resetScroll = true
+ return
+ }
+
+ if (this.peertubeRouter.hasRouteSetting(RouterSetting.DISABLE_SCROLL_RESTORE)) {
+ this.resetScroll = false
+ return
+ }
+
+ // Remove route settings from the comparison
+ const nextSearchParams = nextUrl.searchParams
+ nextSearchParams.delete(PeerTubeRouterService.ROUTE_SETTING_NAME)
+
+ const previousSearchParams = previousUrl.searchParams
+
+ nextSearchParams.sort()
+ previousSearchParams.sort()
+
+ if (nextSearchParams.toString() !== previousSearchParams.toString()) {
+ this.resetScroll = true
+ }
+ } catch (err) {
+ logger.error('Cannot parse URL to check next scroll.', err)
+ this.resetScroll = true
+ }
+ })
}
private consumeScroll () {
@@ -88,5 +85,4 @@ export class ScrollService {
}
})
}
-
}
diff --git a/client/src/app/core/routing/server-config-resolver.service.ts b/client/src/app/core/routing/server-config-resolver.service.ts
index 8d2390d38f..bb1d806278 100644
--- a/client/src/app/core/routing/server-config-resolver.service.ts
+++ b/client/src/app/core/routing/server-config-resolver.service.ts
@@ -1,9 +1,9 @@
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { ServerService } from '../server'
@Injectable()
export class ServerConfigResolver {
- constructor (private server: ServerService) {}
+ private server = inject(ServerService)
resolve () {
return this.server.getConfig()
diff --git a/client/src/app/core/routing/unlogged-guard.service.ts b/client/src/app/core/routing/unlogged-guard.service.ts
index 9920ee41dd..824f578fa6 100644
--- a/client/src/app/core/routing/unlogged-guard.service.ts
+++ b/client/src/app/core/routing/unlogged-guard.service.ts
@@ -1,15 +1,12 @@
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'
import { AuthService } from '../auth/auth.service'
import { RedirectService } from './redirect.service'
@Injectable()
export class UnloggedGuard {
-
- constructor (
- private auth: AuthService,
- private redirectService: RedirectService
- ) {}
+ private auth = inject(AuthService)
+ private redirectService = inject(RedirectService)
canActivate (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (this.auth.isLoggedIn() === false) return true
diff --git a/client/src/app/core/routing/user-right-guard.service.ts b/client/src/app/core/routing/user-right-guard.service.ts
index 33e767467b..d6ffb117f6 100644
--- a/client/src/app/core/routing/user-right-guard.service.ts
+++ b/client/src/app/core/routing/user-right-guard.service.ts
@@ -1,15 +1,12 @@
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'
import { AuthService } from '../auth/auth.service'
import { RedirectService } from './redirect.service'
@Injectable()
export class UserRightGuard {
-
- constructor (
- private redirectService: RedirectService,
- private auth: AuthService
- ) {}
+ private redirectService = inject(RedirectService)
+ private auth = inject(AuthService)
canActivate (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const user = this.auth.getUser()
diff --git a/client/src/app/core/scoped-tokens/scoped-tokens.service.ts b/client/src/app/core/scoped-tokens/scoped-tokens.service.ts
index f7d192feba..437baeee8d 100644
--- a/client/src/app/core/scoped-tokens/scoped-tokens.service.ts
+++ b/client/src/app/core/scoped-tokens/scoped-tokens.service.ts
@@ -1,32 +1,30 @@
import { catchError } from 'rxjs/operators'
import { HttpClient } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { ScopedToken } from '@peertube/peertube-models'
import { environment } from '../../../environments/environment'
import { RestExtractor } from '../rest'
@Injectable()
export class ScopedTokensService {
- private static BASE_SCOPED_TOKENS_URL = environment.apiUrl + '/api/v1/users/scoped-tokens'
+ private authHttp = inject(HttpClient)
+ private restExtractor = inject(RestExtractor)
- constructor (
- private authHttp: HttpClient,
- private restExtractor: RestExtractor
- ) {}
+ private static BASE_SCOPED_TOKENS_URL = environment.apiUrl + '/api/v1/users/scoped-tokens'
getScopedTokens () {
return this.authHttp
- .get<ScopedToken>(ScopedTokensService.BASE_SCOPED_TOKENS_URL)
- .pipe(
- catchError(res => this.restExtractor.handleError(res))
- )
+ .get<ScopedToken>(ScopedTokensService.BASE_SCOPED_TOKENS_URL)
+ .pipe(
+ catchError(res => this.restExtractor.handleError(res))
+ )
}
renewScopedTokens () {
return this.authHttp
- .post<ScopedToken>(ScopedTokensService.BASE_SCOPED_TOKENS_URL, {})
- .pipe(
- catchError(res => this.restExtractor.handleError(res))
- )
+ .post<ScopedToken>(ScopedTokensService.BASE_SCOPED_TOKENS_URL, {})
+ .pipe(
+ catchError(res => this.restExtractor.handleError(res))
+ )
}
}
diff --git a/client/src/app/core/server/server.service.ts b/client/src/app/core/server/server.service.ts
index f60b50d3bd..e26a729f7b 100644
--- a/client/src/app/core/server/server.service.ts
+++ b/client/src/app/core/server/server.service.ts
@@ -1,7 +1,7 @@
import { Observable, of, Subject } from 'rxjs'
import { first, map, share, shareReplay, switchMap, tap } from 'rxjs/operators'
import { HttpClient } from '@angular/common/http'
-import { Inject, Injectable, LOCALE_ID } from '@angular/core'
+import { Injectable, LOCALE_ID, inject } from '@angular/core'
import { getDevLocale, isOnDevLocale } from '@app/helpers'
import { getCompleteLocale, isDefaultLocale, peertubeTranslate } from '@peertube/peertube-core-utils'
import {
@@ -18,6 +18,9 @@ import { environment } from '../../../environments/environment'
@Injectable()
export class ServerService {
+ private http = inject(HttpClient)
+ private localeId = inject(LOCALE_ID)
+
private static BASE_CONFIG_URL = environment.apiUrl + '/api/v1/config/'
private static BASE_VIDEO_URL = environment.apiUrl + '/api/v1/videos/'
private static BASE_VIDEO_PLAYLIST_URL = environment.apiUrl + '/api/v1/video-playlists/'
@@ -40,12 +43,6 @@ export class ServerService {
private config: ServerConfig
private htmlConfig: HTMLServerConfig
- constructor (
- private http: HttpClient,
- @Inject(LOCALE_ID) private localeId: string
- ) {
- }
-
loadHTMLConfig () {
try {
this.loadHTMLConfigLocally()
@@ -82,20 +79,20 @@ export class ServerService {
if (!this.configObservable) {
this.configObservable = this.http.get<ServerConfig>(ServerService.BASE_CONFIG_URL)
- .pipe(
- tap(config => {
- this.config = config
- this.htmlConfig = config
- this.configLoaded = true
- }),
- tap(config => {
- if (this.configReset) {
- this.configReloaded.next(config)
- this.configReset = false
- }
- }),
- share()
- )
+ .pipe(
+ tap(config => {
+ this.config = config
+ this.htmlConfig = config
+ this.configLoaded = true
+ }),
+ tap(config => {
+ if (this.configReset) {
+ this.configReloaded.next(config)
+ this.configReset = false
+ }
+ }),
+ share()
+ )
}
return this.configObservable
@@ -166,7 +163,7 @@ export class ServerService {
return this.videoPlaylistPrivaciesObservable.pipe(first())
}
- getServerLocale (): Observable<{ [ id: string ]: string }> {
+ getServerLocale (): Observable<{ [id: string]: string }> {
if (!this.localeObservable) {
const completeLocale = isOnDevLocale() ? getDevLocale() : getCompleteLocale(this.localeId)
@@ -175,8 +172,8 @@ export class ServerService {
this.localeObservable = of({}).pipe(shareReplay())
} else {
this.localeObservable = this.http
- .get(ServerService.BASE_LOCALE_URL + completeLocale + '/server.json')
- .pipe(shareReplay())
+ .get(ServerService.BASE_LOCALE_URL + completeLocale + '/server.json')
+ .pipe(shareReplay())
}
}
@@ -187,40 +184,40 @@ export class ServerService {
return this.http.get<ServerStats>(ServerService.BASE_STATS_URL)
}
- private loadAttributeEnum <T extends string | number> (
+ private loadAttributeEnum<T extends string | number> (
baseUrl: string,
attributeName: 'categories' | 'licences' | 'languages' | 'privacies',
sort = false
) {
return this.getServerLocale()
- .pipe(
- switchMap(translations => {
- return this.http.get<{ [ id: string ]: string }>(baseUrl + attributeName)
- .pipe(map(data => ({ data, translations })))
- }),
- map(({ data, translations }) => {
- const hashToPopulate: VideoConstant<T>[] = Object.keys(data)
- .map(dataKey => {
- const label = data[dataKey]
-
- const id = attributeName === 'languages'
- ? dataKey as T
- : parseInt(dataKey, 10) as T
-
- return {
- id,
- label: peertubeTranslate(label, translations)
- }
- })
-
- if (sort === true) {
- hashToPopulate.sort((a, b) => a.label.localeCompare(b.label))
- }
-
- return hashToPopulate
- }),
- shareReplay()
- )
+ .pipe(
+ switchMap(translations => {
+ return this.http.get<{ [id: string]: string }>(baseUrl + attributeName)
+ .pipe(map(data => ({ data, translations })))
+ }),
+ map(({ data, translations }) => {
+ const hashToPopulate: VideoConstant<T>[] = Object.keys(data)
+ .map(dataKey => {
+ const label = data[dataKey]
+
+ const id = attributeName === 'languages'
+ ? dataKey as T
+ : parseInt(dataKey, 10) as T
+
+ return {
+ id,
+ label: peertubeTranslate(label, translations)
+ }
+ })
+
+ if (sort === true) {
+ hashToPopulate.sort((a, b) => a.label.localeCompare(b.label))
+ }
+
+ return hashToPopulate
+ }),
+ shareReplay()
+ )
}
private loadHTMLConfigLocally () {
diff --git a/client/src/app/core/theme/theme.service.ts b/client/src/app/core/theme/theme.service.ts
index bf728495c8..bfd0fb25c5 100644
--- a/client/src/app/core/theme/theme.service.ts
+++ b/client/src/app/core/theme/theme.service.ts
@@ -1,4 +1,4 @@
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { sortBy } from '@peertube/peertube-core-utils'
import { HTMLServerConfig, ServerConfig, ServerConfigTheme } from '@peertube/peertube-models'
import { logger } from '@root-helpers/logger'
@@ -17,6 +17,12 @@ const debugLogger = debug('peertube:theme')
@Injectable()
export class ThemeService {
+ private auth = inject(AuthService)
+ private userService = inject(UserService)
+ private pluginService = inject(PluginService)
+ private server = inject(ServerService)
+ private localStorageService = inject(LocalStorageService)
+
private oldInjectedProperties: string[] = []
private oldThemeName: string
@@ -28,14 +34,6 @@ export class ThemeService {
private serverConfig: HTMLServerConfig
- constructor (
- private auth: AuthService,
- private userService: UserService,
- private pluginService: PluginService,
- private server: ServerService,
- private localStorageService: LocalStorageService
- ) {}
-
initialize () {
this.serverConfig = this.server.getHTMLConfig()
this.internalThemes = this.serverConfig.theme.builtIn.map(t => t.name)
diff --git a/client/src/app/core/users/user-local-storage.service.ts b/client/src/app/core/users/user-local-storage.service.ts
index 43da942138..bfa4b4be0b 100644
--- a/client/src/app/core/users/user-local-storage.service.ts
+++ b/client/src/app/core/users/user-local-storage.service.ts
@@ -1,5 +1,5 @@
import { filter, throttleTime } from 'rxjs'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { AuthService, AuthStatus } from '@app/core/auth'
import { objectKeysTyped } from '@peertube/peertube-core-utils'
import { NSFWPolicyType, UserRoleType, UserUpdateMe } from '@peertube/peertube-models'
@@ -11,12 +11,11 @@ import { LocalStorageService } from '../wrappers/storage.service'
@Injectable()
export class UserLocalStorageService {
+ private authService = inject(AuthService)
+ private server = inject(ServerService)
+ private localStorageService = inject(LocalStorageService)
- constructor (
- private authService: AuthService,
- private server: ServerService,
- private localStorageService: LocalStorageService
- ) {
+ constructor () {
this.authService.userInformationLoaded.subscribe({
next: () => {
const user = this.authService.getUser()
@@ -132,9 +131,9 @@ export class UserLocalStorageService {
videoLanguages: UserLocalStorageKeys.VIDEO_LANGUAGES
}
- const obj: [ string, string | boolean | string[] ][] = objectKeysTyped(localStorageKeys)
+ const obj: [string, string | boolean | string[]][] = objectKeysTyped(localStorageKeys)
.filter(key => key in profile)
- .map(key => ([ localStorageKeys[key], profile[key] ]))
+ .map(key => [ localStorageKeys[key], profile[key] ])
for (const [ key, value ] of obj) {
try {
diff --git a/client/src/app/core/users/user.service.ts b/client/src/app/core/users/user.service.ts
index 7ad0ee9bf8..39caca40aa 100644
--- a/client/src/app/core/users/user.service.ts
+++ b/client/src/app/core/users/user.service.ts
@@ -1,7 +1,7 @@
import { Observable, of } from 'rxjs'
import { catchError, first, map, shareReplay } from 'rxjs/operators'
import { HttpClient, HttpParams } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { AuthService } from '@app/core/auth'
import { ActorImage, User as UserServerModel, UserUpdateMe, UserVideoQuota } from '@peertube/peertube-models'
import { environment } from '../../../environments/environment'
@@ -11,18 +11,16 @@ import { User } from './user.model'
@Injectable()
export class UserService {
+ private authHttp = inject(HttpClient)
+ private authService = inject(AuthService)
+ private restExtractor = inject(RestExtractor)
+ private userLocalStorageService = inject(UserLocalStorageService)
+
static BASE_USERS_URL = environment.apiUrl + '/api/v1/users/'
- private userCache: { [ id: number ]: Observable<UserServerModel> } = {}
+ private userCache: { [id: number]: Observable<UserServerModel> } = {}
private signupInThisSession = false
- constructor (
- private authHttp: HttpClient,
- private authService: AuthService,
- private restExtractor: RestExtractor,
- private userLocalStorageService: UserLocalStorageService
- ) { }
-
// ---------------------------------------------------------------------------
getUserWithCache (userId: number) {
@@ -37,7 +35,7 @@ export class UserService {
const params = new HttpParams().append('withStats', withStats + '')
return this.authHttp.get<UserServerModel>(UserService.BASE_USERS_URL + userId, { params })
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
// ---------------------------------------------------------------------------
@@ -58,7 +56,7 @@ export class UserService {
listenAnonymousUpdate () {
return this.userLocalStorageService.listenUserInfoChange()
- .pipe(map(() => this.getAnonymousUser()))
+ .pipe(map(() => this.getAnonymousUser()))
}
getAnonymousUser () {
@@ -71,10 +69,10 @@ export class UserService {
}
return this.authService.userInformationLoaded
- .pipe(
- first(),
- map(() => this.authService.getUser())
- )
+ .pipe(
+ first(),
+ map(() => this.authService.getUser())
+ )
}
// ---------------------------------------------------------------------------
@@ -87,7 +85,7 @@ export class UserService {
}
return this.authHttp.put(url, body)
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
changeEmail (password: string, newEmail: string) {
@@ -98,49 +96,49 @@ export class UserService {
}
return this.authHttp.put(url, body)
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
updateMyProfile (profile: UserUpdateMe) {
const url = UserService.BASE_USERS_URL + 'me'
return this.authHttp.put(url, profile)
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
deleteMe () {
const url = UserService.BASE_USERS_URL + 'me'
return this.authHttp.delete(url)
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
changeAvatar (avatarForm: FormData) {
const url = UserService.BASE_USERS_URL + 'me/avatar/pick'
return this.authHttp.post<{ avatars: ActorImage[] }>(url, avatarForm)
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
deleteAvatar () {
const url = UserService.BASE_USERS_URL + 'me/avatar'
return this.authHttp.delete(url)
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
getMyVideoQuotaUsed () {
const url = UserService.BASE_USERS_URL + 'me/video-quota-used'
return this.authHttp.get<UserVideoQuota>(url)
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
askResetPassword (email: string) {
const url = UserService.BASE_USERS_URL + '/ask-reset-password'
return this.authHttp.post(url, { email })
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
resetPassword (userId: number, verificationString: string, password: string) {
@@ -151,7 +149,7 @@ export class UserService {
}
return this.authHttp.post(url, body)
- .pipe(catchError(res => this.restExtractor.handleError(res)))
+ .pipe(catchError(res => this.restExtractor.handleError(res)))
}
autocomplete (search: string): Observable<string[]> {
diff --git a/client/src/app/header/header.component.ts b/client/src/app/header/header.component.ts
index 4f9b566ee9..7f6faac3b7 100644
--- a/client/src/app/header/header.component.ts
+++ b/client/src/app/header/header.component.ts
@@ -1,5 +1,5 @@
import { CommonModule } from '@angular/common'
-import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core'
+import { Component, OnDestroy, OnInit, inject, viewChild } from '@angular/core'
import { NavigationEnd, Router, RouterLink } from '@angular/router'
import {
AuthService,
@@ -50,13 +50,21 @@ import { SearchTypeaheadComponent } from './search-typeahead.component'
ButtonComponent
]
})
-
export class HeaderComponent implements OnInit, OnDestroy {
+ private authService = inject(AuthService)
+ private serverService = inject(ServerService)
+ private redirectService = inject(RedirectService)
+ private hotkeysService = inject(HotkeysService)
+ private screenService = inject(ScreenService)
+ private modalService = inject(PeertubeModalService)
+ private router = inject(Router)
+ private menu = inject(MenuService)
+
private static LS_HIDE_MOBILE_MSG = 'hide-mobile-msg'
- @ViewChild('languageChooserModal', { static: true }) languageChooserModal: LanguageChooserComponent
- @ViewChild('quickSettingsModal', { static: true }) quickSettingsModal: QuickSettingsModalComponent
- @ViewChild('dropdown') dropdown: NgbDropdown
+ readonly languageChooserModal = viewChild<LanguageChooserComponent>('languageChooserModal')
+ readonly quickSettingsModal = viewChild<QuickSettingsModalComponent>('quickSettingsModal')
+ readonly dropdown = viewChild<NgbDropdown>('dropdown')
user: AuthUser
loggedIn: boolean
@@ -76,19 +84,8 @@ export class HeaderComponent implements OnInit, OnDestroy {
private hotkeysSub: Subscription
private authSub: Subscription
- constructor (
- private authService: AuthService,
- private serverService: ServerService,
- private redirectService: RedirectService,
- private hotkeysService: HotkeysService,
- private screenService: ScreenService,
- private modalService: PeertubeModalService,
- private router: Router,
- private menu: MenuService
- ) { }
-
get language () {
- return this.languageChooserModal.getCurrentLanguage()
+ return this.languageChooserModal().getCurrentLanguage()
}
get requiresApproval () {
@@ -113,7 +110,7 @@ export class HeaderComponent implements OnInit, OnDestroy {
ngOnInit () {
this.htmlConfig = this.serverService.getHTMLConfig()
- this.currentInterfaceLanguage = this.languageChooserModal.getCurrentLanguage()
+ this.currentInterfaceLanguage = this.languageChooserModal().getCurrentLanguage()
this.loggedIn = this.authService.isLoggedIn()
this.updateUserState()
@@ -257,11 +254,11 @@ export class HeaderComponent implements OnInit, OnDestroy {
}
openLanguageChooser () {
- this.languageChooserModal.show()
+ this.languageChooserModal().show()
}
openQuickSettings () {
- this.quickSettingsModal.show()
+ this.quickSettingsModal().show()
}
openHotkeysCheatSheet () {
diff --git a/client/src/app/header/notification-dropdown.component.ts b/client/src/app/header/notification-dropdown.component.ts
index a2e21f8051..6ed5f32582 100644
--- a/client/src/app/header/notification-dropdown.component.ts
+++ b/client/src/app/header/notification-dropdown.component.ts
@@ -1,5 +1,5 @@
import { CommonModule } from '@angular/common'
-import { Component, EventEmitter, OnDestroy, OnInit, Output, ViewChild } from '@angular/core'
+import { Component, OnDestroy, OnInit, inject, output, viewChild } from '@angular/core'
import { NavigationEnd, Router, RouterLink, RouterLinkActive } from '@angular/router'
import { Notifier, PeerTubeSocket, ScreenService } from '@app/core'
import { GlobalIconComponent } from '@app/shared/shared-icons/global-icon.component'
@@ -25,9 +25,15 @@ import { filter } from 'rxjs/operators'
]
})
export class NotificationDropdownComponent implements OnInit, OnDestroy {
- @ViewChild('dropdown', { static: false }) dropdown: NgbDropdown
+ private userNotificationService = inject(UserNotificationService)
+ private screenService = inject(ScreenService)
+ private peertubeSocket = inject(PeerTubeSocket)
+ private notifier = inject(Notifier)
+ private router = inject(Router)
- @Output() navigate = new EventEmitter<HTMLAnchorElement>()
+ readonly dropdown = viewChild<NgbDropdown>('dropdown')
+
+ readonly navigate = output<HTMLAnchorElement>()
unreadNotifications = 0
loaded = false
@@ -39,29 +45,20 @@ export class NotificationDropdownComponent implements OnInit, OnDestroy {
private notificationSub: Subscription
private routeSub: Subscription
- constructor (
- private userNotificationService: UserNotificationService,
- private screenService: ScreenService,
- private peertubeSocket: PeerTubeSocket,
- private notifier: Notifier,
- private router: Router
- ) {
- }
-
ngOnInit () {
this.userNotificationService.countUnreadNotifications()
- .subscribe({
- next: result => {
- this.unreadNotifications = result
- this.subscribeToNotifications()
- },
+ .subscribe({
+ next: result => {
+ this.unreadNotifications = result
+ this.subscribeToNotifications()
+ },
- error: err => this.notifier.error(err.message)
- })
+ error: err => this.notifier.error(err.message)
+ })
this.routeSub = this.router.events
- .pipe(filter(event => event instanceof NavigationEnd))
- .subscribe(() => this.closeDropdown())
+ .pipe(filter(event => event instanceof NavigationEnd))
+ .subscribe(() => this.closeDropdown())
}
ngOnDestroy () {
@@ -74,7 +71,8 @@ export class NotificationDropdownComponent implements OnInit, OnDestroy {
}
closeDropdown () {
- if (this.dropdown) this.dropdown.close()
+ const dropdown = this.dropdown()
+ if (dropdown) dropdown.close()
}
onDropdownShown () {
diff --git a/client/src/app/header/search-typeahead.component.ts b/client/src/app/header/search-typeahead.component.ts
index b8a9562535..111c186306 100644
--- a/client/src/app/header/search-typeahead.component.ts
+++ b/client/src/app/header/search-typeahead.component.ts
@@ -1,13 +1,13 @@
import { of } from 'rxjs'
import { first, tap } from 'rxjs/operators'
import { ListKeyManager } from '@angular/cdk/a11y'
-import { AfterViewChecked, Component, OnDestroy, OnInit, QueryList, ViewChildren } from '@angular/core'
+import { AfterViewChecked, Component, OnDestroy, OnInit, inject, viewChildren } from '@angular/core'
import { ActivatedRoute, Params, Router } from '@angular/router'
import { AuthService, ServerService } from '@app/core'
import { logger } from '@root-helpers/logger'
import { HTMLServerConfig, SearchTargetType } from '@peertube/peertube-models'
import { SuggestionComponent, SuggestionPayload, SuggestionPayloadType } from './suggestion.component'
-import { NgFor, NgIf, NgClass } from '@angular/common'
+import { NgFor, NgIf } from '@angular/common'
import { GlobalIconComponent } from '../shared/shared-icons/global-icon.component'
import { FormsModule } from '@angular/forms'
@@ -15,10 +15,15 @@ import { FormsModule } from '@angular/forms'
selector: 'my-search-typeahead',
templateUrl: './search-typeahead.component.html',
styleUrls: [ './search-typeahead.component.scss' ],
- imports: [ FormsModule, GlobalIconComponent, NgFor, SuggestionComponent, NgIf, NgClass ]
+ imports: [ FormsModule, GlobalIconComponent, NgFor, SuggestionComponent, NgIf ]
})
export class SearchTypeaheadComponent implements OnInit, AfterViewChecked, OnDestroy {
- @ViewChildren(SuggestionComponent) suggestionItems: QueryList<SuggestionComponent>
+ private authService = inject(AuthService)
+ private router = inject(Router)
+ private route = inject(ActivatedRoute)
+ private serverService = inject(ServerService)
+
+ readonly suggestionItems = viewChildren(SuggestionComponent)
hasChannel = false
inChannel = false
@@ -36,13 +41,6 @@ export class SearchTypeaheadComponent implements OnInit, AfterViewChecked, OnDes
private scheduleKeyboardEventsInit = false
- constructor (
- private authService: AuthService,
- private router: Router,
- private route: ActivatedRoute,
- private serverService: ServerService
- ) {}
-
ngOnInit () {
this.route.queryParams
.pipe(first(params => this.isOnSearch() && params.search !== undefined && params.search !== null))
@@ -70,7 +68,7 @@ export class SearchTypeaheadComponent implements OnInit, AfterViewChecked, OnDes
}
showSearchGlobalHelp () {
- return this.search && this.areSuggestionsOpened && this.keyboardEventsManager?.activeItem?.result?.type === 'search-index'
+ return this.search && this.areSuggestionsOpened && this.keyboardEventsManager?.activeItem?.result()?.type === 'search-index'
}
canSearchAnyURI () {
@@ -88,11 +86,11 @@ export class SearchTypeaheadComponent implements OnInit, AfterViewChecked, OnDes
initKeyboardEventsManager () {
if (this.keyboardEventsManager) return
- this.keyboardEventsManager = new ListKeyManager(this.suggestionItems)
+ this.keyboardEventsManager = new ListKeyManager(this.suggestionItems())
- const activeIndex = this.suggestionItems.toArray().findIndex(i => i.result.default === true)
+ const activeIndex = this.suggestionItems().findIndex(i => i.result().default === true)
if (activeIndex === -1) {
- logger.error('Cannot find active index.', { suggestionItems: this.suggestionItems })
+ logger.error('Cannot find active index.', { suggestionItems: this.suggestionItems() })
}
this.updateItemsState(activeIndex)
@@ -142,10 +140,10 @@ export class SearchTypeaheadComponent implements OnInit, AfterViewChecked, OnDes
this.keyboardEventsManager.setActiveItem(index)
}
- for (const item of this.suggestionItems) {
+ for (const item of this.suggestionItems()) {
if (this.keyboardEventsManager.activeItem && this.keyboardEventsManager.activeItem === item) {
item.active = true
- this.activeSearch = item.result.type
+ this.activeSearch = item.result().type
continue
}
@@ -192,7 +190,7 @@ export class SearchTypeaheadComponent implements OnInit, AfterViewChecked, OnDes
}
if (!searchTarget) {
- searchTarget = this.buildSearchTarget(this.keyboardEventsManager.activeItem.result)
+ searchTarget = this.buildSearchTarget(this.keyboardEventsManager.activeItem.result())
}
Object.assign(queryParams, { search: this.search, searchTarget })
@@ -208,10 +206,10 @@ export class SearchTypeaheadComponent implements OnInit, AfterViewChecked, OnDes
if (queryParams?.languageOneOf) return of(queryParams)
return this.authService.userInformationLoaded
- .pipe(
- first(),
- tap(() => Object.assign(queryParams, { languageOneOf: this.authService.getUser().videoLanguages }))
- )
+ .pipe(
+ first(),
+ tap(() => Object.assign(queryParams, { languageOneOf: this.authService.getUser().videoLanguages }))
+ )
}
private buildSearchTarget (result: SuggestionPayload): SearchTargetType {
diff --git a/client/src/app/header/suggestion.component.html b/client/src/app/header/suggestion.component.html
index 2a7e682030..da24d38c7e 100644
--- a/client/src/app/header/suggestion.component.html
+++ b/client/src/app/header/suggestion.component.html
@@ -1,19 +1,19 @@
<a
tabindex="-1" class="d-flex flex-auto align-items-center p-2" [class.focus-visible]="active"
[attr.title]="getTitle()"
- [attr.aria-describedby]="describedby"
+ [attr.aria-describedby]="describedby()"
>
<my-global-icon class="me-2" iconName="search"></my-global-icon>
<div
class="flex-auto overflow-hidden no-wrap d-flex align-items-center"
- [attr.aria-label]="result.text"
+ [attr.aria-label]="result().text"
>
- {{ result.text }}
+ {{ result().text }}
</div>
<div class="result-type border rounded flex-shrink-0 px-1 ms-1 f6">
- <span *ngIf="result.type === 'search-instance'" i18n>In this instance's network</span>
- <span *ngIf="result.type === 'search-index'" i18n>In the vidiverse</span>
+ <span *ngIf="result().type === 'search-instance'" i18n>In this instance's network</span>
+ <span *ngIf="result().type === 'search-index'" i18n>In the vidiverse</span>
</div>
</a>
diff --git a/client/src/app/header/suggestion.component.ts b/client/src/app/header/suggestion.component.ts
index 10523d34a9..e44eae1a41 100644
--- a/client/src/app/header/suggestion.component.ts
+++ b/client/src/app/header/suggestion.component.ts
@@ -1,6 +1,6 @@
import { ListKeyManagerOption } from '@angular/cdk/a11y'
import { NgIf } from '@angular/common'
-import { Component, Input, OnInit } from '@angular/core'
+import { Component, OnInit, input } from '@angular/core'
import { RouterLink } from '@angular/router'
import { GlobalIconComponent } from '../shared/shared-icons/global-icon.component'
@@ -20,21 +20,22 @@ export type SuggestionPayloadType = 'search-instance' | 'search-index'
imports: [ GlobalIconComponent, NgIf ]
})
export class SuggestionComponent implements OnInit, ListKeyManagerOption {
- @Input() result: SuggestionPayload
- @Input() highlight: string
- @Input() describedby: string
+ readonly result = input<SuggestionPayload>(undefined)
+ readonly highlight = input<string>(undefined)
+ readonly describedby = input<string>(undefined)
disabled = false
active = false
getTitle () {
- if (this.result.type === 'search-instance') return $localize`Search "${this.result.text}" in this instance's network`
- if (this.result.type === 'search-index') return $localize`Search "${this.result.text}" in the vidiverse`
+ const result = this.result()
+ if (result.type === 'search-instance') return $localize`Search "${result.text}" in this instance's network`
+ if (result.type === 'search-index') return $localize`Search "${result.text}" in the vidiverse`
return undefined
}
ngOnInit () {
- if (this.result.default) this.active = true
+ if (this.result().default) this.active = true
}
}
diff --git a/client/src/app/homepage-redirect.component.ts b/client/src/app/homepage-redirect.component.ts
index 76c7e222b8..98f06d64fd 100644
--- a/client/src/app/homepage-redirect.component.ts
+++ b/client/src/app/homepage-redirect.component.ts
@@ -1,4 +1,4 @@
-import { Component, OnInit } from '@angular/core'
+import { Component, OnInit, inject } from '@angular/core'
import { ActivatedRoute } from '@angular/router'
import { is18nPath } from '@peertube/peertube-core-utils'
import { RedirectService } from './core/routing/redirect.service'
@@ -8,18 +8,15 @@ import { RedirectService } from './core/routing/redirect.service'
*
* Since we also want to use the `skipLocationChange` option, we cannot use a guard that returns a UrlTree
* See https://github.com/angular/angular/issues/27148
-*/
+ */
@Component({
template: '',
standalone: true
})
export class HomepageRedirectComponent implements OnInit {
-
- constructor (
- private route: ActivatedRoute,
- private redirectService: RedirectService
- ) { }
+ private route = inject(ActivatedRoute)
+ private redirectService = inject(RedirectService)
ngOnInit () {
const url = this.route.snapshot.url
diff --git a/client/src/app/hotkeys/hotkeys-cheat-sheet.component.html b/client/src/app/hotkeys/hotkeys-cheat-sheet.component.html
index ea9a46724a..23ac0f241b 100644
--- a/client/src/app/hotkeys/hotkeys-cheat-sheet.component.html
+++ b/client/src/app/hotkeys/hotkeys-cheat-sheet.component.html
@@ -1,6 +1,6 @@
<div class="cfp-hotkeys-container fade" [ngClass]="{'in': helpVisible}">
<div class="cfp-hotkeys">
- <h1 class="cfp-hotkeys-title">{{ title }}</h1>
+ <h1 class="cfp-hotkeys-title">{{ title() }}</h1>
<div class="d-flex justify-content-center m-3">
<my-peertube-checkbox
diff --git a/client/src/app/hotkeys/hotkeys-cheat-sheet.component.ts b/client/src/app/hotkeys/hotkeys-cheat-sheet.component.ts
index 267c7c612d..5162112970 100644
--- a/client/src/app/hotkeys/hotkeys-cheat-sheet.component.ts
+++ b/client/src/app/hotkeys/hotkeys-cheat-sheet.component.ts
@@ -1,5 +1,5 @@
import { Subscription } from 'rxjs'
-import { Component, EventEmitter, Input, OnDestroy, OnInit, Output } from '@angular/core'
+import { Component, OnDestroy, OnInit, inject, input, output } from '@angular/core'
import { LocalStorageService, HotkeysService, Hotkey } from '@app/core'
import { FormsModule } from '@angular/forms'
import { PeertubeCheckboxComponent } from '../shared/shared-forms/peertube-checkbox.component'
@@ -12,9 +12,12 @@ import { NgClass, NgFor } from '@angular/common'
imports: [ NgClass, PeertubeCheckboxComponent, FormsModule, NgFor ]
})
export class HotkeysCheatSheetComponent implements OnInit, OnDestroy {
- @Input() title = $localize`Keyboard Shortcuts`
+ private hotkeysService = inject(HotkeysService)
+ private localStorage = inject(LocalStorageService)
- @Output() hotkeysModalStateChange = new EventEmitter<boolean>()
+ readonly title = input($localize`Keyboard Shortcuts`)
+
+ readonly hotkeysModalStateChange = output<boolean>()
hotkeysEnabled = true
@@ -25,11 +28,6 @@ export class HotkeysCheatSheetComponent implements OnInit, OnDestroy {
private readonly localStorageHotkeysDisabledKey = 'peertube-hotkeys-disabled'
- constructor (
- private hotkeysService: HotkeysService,
- private localStorage: LocalStorageService
- ) {}
-
ngOnInit () {
if (this.localStorage.getItem(this.localStorageHotkeysDisabledKey) === 'true') {
this.hotkeysEnabled = false
diff --git a/client/src/app/menu/home-menu.component.ts b/client/src/app/menu/home-menu.component.ts
index 634aa5eca8..896bdfdce2 100644
--- a/client/src/app/menu/home-menu.component.ts
+++ b/client/src/app/menu/home-menu.component.ts
@@ -1,4 +1,4 @@
-import { Component, OnDestroy, OnInit } from '@angular/core'
+import { Component, OnDestroy, OnInit, inject } from '@angular/core'
import { AuthService, ServerService } from '@app/core'
import { HorizontalMenuComponent, HorizontalMenuEntry } from '@app/shared/shared-main/menu/horizontal-menu.component'
import { Subscription } from 'rxjs'
@@ -9,17 +9,13 @@ import { Subscription } from 'rxjs'
imports: [ HorizontalMenuComponent ]
})
export class HomeMenuComponent implements OnInit, OnDestroy {
+ private server = inject(ServerService)
+ private authService = inject(AuthService)
+
menuEntries: HorizontalMenuEntry[] = []
private sub: Subscription
- constructor (
- private server: ServerService,
- private authService: AuthService
- ) {
-
- }
-
ngOnInit () {
this.buildMenu()
diff --git a/client/src/app/menu/language-chooser.component.ts b/client/src/app/menu/language-chooser.component.ts
index d197757cc7..58d245e754 100644
--- a/client/src/app/menu/language-chooser.component.ts
+++ b/client/src/app/menu/language-chooser.component.ts
@@ -1,5 +1,5 @@
import { CommonModule } from '@angular/common'
-import { Component, ElementRef, Inject, LOCALE_ID, ViewChild } from '@angular/core'
+import { Component, ElementRef, LOCALE_ID, inject, viewChild } from '@angular/core'
import { getDevLocale, isOnDevLocale } from '@app/helpers'
import { GlobalIconComponent } from '@app/shared/shared-icons/global-icon.component'
import { NgbModal } from '@ng-bootstrap/ng-bootstrap'
@@ -12,14 +12,14 @@ import { getCompleteLocale, getShortLocale, I18N_LOCALES, objectKeysTyped, sortB
imports: [ CommonModule, GlobalIconComponent ]
})
export class LanguageChooserComponent {
- @ViewChild('modal', { static: true }) modal: ElementRef
+ private modalService = inject(NgbModal)
+ private localeId = inject(LOCALE_ID)
+
+ readonly modal = viewChild<ElementRef>('modal')
languages: { id: string, label: string, iso: string }[] = []
- constructor (
- private modalService: NgbModal,
- @Inject(LOCALE_ID) private localeId: string
- ) {
+ constructor () {
const l = objectKeysTyped(I18N_LOCALES)
.map(k => ({ id: k, label: I18N_LOCALES[k], iso: getShortLocale(k) }))
@@ -27,7 +27,7 @@ export class LanguageChooserComponent {
}
show () {
- this.modalService.open(this.modal, { centered: true })
+ this.modalService.open(this.modal(), { centered: true })
}
buildLanguageLink (lang: { id: string }) {
diff --git a/client/src/app/menu/menu.component.ts b/client/src/app/menu/menu.component.ts
index 3094d2a786..20b9754d75 100644
--- a/client/src/app/menu/menu.component.ts
+++ b/client/src/app/menu/menu.component.ts
@@ -1,5 +1,5 @@
import { CommonModule } from '@angular/common'
-import { Component, OnDestroy, OnInit } from '@angular/core'
+import { Component, OnDestroy, OnInit, inject } from '@angular/core'
import { Params, RouterLink, RouterLinkActive } from '@angular/router'
import {
AuthService,
@@ -56,6 +56,13 @@ const debugLogger = debug('peertube:menu:MenuComponent')
]
})
export class MenuComponent implements OnInit, OnDestroy {
+ private authService = inject(AuthService)
+ private userService = inject(UserService)
+ private serverService = inject(ServerService)
+ private hooks = inject(HooksService)
+ private menu = inject(MenuService)
+ private redirectService = inject(RedirectService)
+
menuSections: MenuSection[] = []
loggedIn: boolean
@@ -64,15 +71,6 @@ export class MenuComponent implements OnInit, OnDestroy {
private authSub: Subscription
- constructor (
- private authService: AuthService,
- private userService: UserService,
- private serverService: ServerService,
- private hooks: HooksService,
- private menu: MenuService,
- private redirectService: RedirectService
- ) { }
-
get shortDescription () {
return this.serverService.getHTMLConfig().instance.shortDescription
}
diff --git a/client/src/app/menu/quick-settings-modal.component.ts b/client/src/app/menu/quick-settings-modal.component.ts
index fca07b6013..3c7ecab4e5 100644
--- a/client/src/app/menu/quick-settings-modal.component.ts
+++ b/client/src/app/menu/quick-settings-modal.component.ts
@@ -1,5 +1,5 @@
import { CommonModule } from '@angular/common'
-import { Component, EventEmitter, OnDestroy, OnInit, Output, ViewChild } from '@angular/core'
+import { Component, OnDestroy, OnInit, inject, output, viewChild } from '@angular/core'
import { ActivatedRoute, Router } from '@angular/router'
import { AuthService, AuthStatus, LocalStorageService, User, UserService } from '@app/core'
import { GlobalIconComponent } from '@app/shared/shared-icons/global-icon.component'
@@ -25,11 +25,18 @@ import { filter } from 'rxjs/operators'
]
})
export class QuickSettingsModalComponent implements OnInit, OnDestroy {
+ private modalService = inject(NgbModal)
+ private userService = inject(UserService)
+ private authService = inject(AuthService)
+ private localStorageService = inject(LocalStorageService)
+ private route = inject(ActivatedRoute)
+ private router = inject(Router)
+
private static readonly QUERY_MODAL_NAME = 'quick-settings'
- @ViewChild('modal', { static: true }) modal: NgbModal
+ readonly modal = viewChild<NgbModal>('modal')
- @Output() openLanguageModal = new EventEmitter<void>()
+ readonly openLanguageModal = output()
user: User
userInformationLoaded = new ReplaySubject<boolean>(1)
@@ -40,16 +47,6 @@ export class QuickSettingsModalComponent implements OnInit, OnDestroy {
private loginSub: Subscription
private localStorageSub: Subscription
- constructor (
- private modalService: NgbModal,
- private userService: UserService,
- private authService: AuthService,
- private localStorageService: LocalStorageService,
- private route: ActivatedRoute,
- private router: Router
- ) {
- }
-
ngOnInit () {
this.user = this.userService.getAnonymousUser()
@@ -71,7 +68,7 @@ export class QuickSettingsModalComponent implements OnInit, OnDestroy {
this.routeSub = this.route.queryParams.subscribe(params => {
if (params['modal'] === QuickSettingsModalComponent.QUERY_MODAL_NAME) {
- this.openedModal = this.modalService.open(this.modal, { centered: true })
+ this.openedModal = this.modalService.open(this.modal(), { centered: true })
this.openedModal.hidden.subscribe(() => this.setModalQuery('remove'))
}
diff --git a/client/src/app/modal/account-setup-warning-modal.component.ts b/client/src/app/modal/account-setup-warning-modal.component.ts
index 3de4ee3f66..10edceed50 100644
--- a/client/src/app/modal/account-setup-warning-modal.component.ts
+++ b/client/src/app/modal/account-setup-warning-modal.component.ts
@@ -1,5 +1,5 @@
import { CommonModule } from '@angular/common'
-import { Component, ElementRef, EventEmitter, OnInit, Output, ViewChild } from '@angular/core'
+import { Component, ElementRef, OnInit, inject, output, viewChild } from '@angular/core'
import { FormsModule } from '@angular/forms'
import { RouterLink } from '@angular/router'
import { Notifier, ServerService, User, UserService } from '@app/core'
@@ -16,9 +16,14 @@ import { peertubeLocalStorage } from '@root-helpers/peertube-web-storage'
imports: [ CommonModule, GlobalIconComponent, PeertubeCheckboxComponent, FormsModule, RouterLink ]
})
export class AccountSetupWarningModalComponent implements OnInit {
- @ViewChild('modal', { static: true }) modal: ElementRef
+ private userService = inject(UserService)
+ private modalService = inject(NgbModal)
+ private notifier = inject(Notifier)
+ private serverService = inject(ServerService)
- @Output() created = new EventEmitter<void>()
+ readonly modal = viewChild<ElementRef>('modal')
+
+ readonly created = output()
stopDisplayModal = false
ref: NgbModalRef
@@ -33,13 +38,6 @@ export class AccountSetupWarningModalComponent implements OnInit {
this.created.emit()
}
- constructor (
- private userService: UserService,
- private modalService: NgbModal,
- private notifier: Notifier,
- private serverService: ServerService
- ) { }
-
get instanceName () {
return this.serverService.getHTMLConfig().instance.name
}
@@ -68,7 +66,7 @@ export class AccountSetupWarningModalComponent implements OnInit {
if (this.ref) return
- this.ref = this.modalService.open(this.modal, {
+ this.ref = this.modalService.open(this.modal(), {
centered: true,
backdrop: 'static',
keyboard: false,
@@ -84,10 +82,10 @@ export class AccountSetupWarningModalComponent implements OnInit {
peertubeLocalStorage.setItem(this.LS_KEYS.NO_ACCOUNT_SETUP_WARNING_MODAL, 'true')
this.userService.updateMyProfile({ noAccountSetupWarningModal: true })
- .subscribe({
- next: () => logger.info('We will not open the account setup modal again.'),
+ .subscribe({
+ next: () => logger.info('We will not open the account setup modal again.'),
- error: err => this.notifier.error(err.message)
- })
+ error: err => this.notifier.error(err.message)
+ })
}
}
diff --git a/client/src/app/modal/admin-welcome-modal.component.ts b/client/src/app/modal/admin-welcome-modal.component.ts
index 6e13b1b40c..1c10d31eb9 100644
--- a/client/src/app/modal/admin-welcome-modal.component.ts
+++ b/client/src/app/modal/admin-welcome-modal.component.ts
@@ -1,4 +1,4 @@
-import { Component, ElementRef, EventEmitter, OnInit, Output, ViewChild } from '@angular/core'
+import { Component, ElementRef, OnInit, inject, output, viewChild } from '@angular/core'
import { Notifier, User, UserService } from '@app/core'
import { GlobalIconComponent } from '@app/shared/shared-icons/global-icon.component'
import { NgbModal } from '@ng-bootstrap/ng-bootstrap'
@@ -12,20 +12,18 @@ import { peertubeLocalStorage } from '@root-helpers/peertube-web-storage'
imports: [ GlobalIconComponent ]
})
export class AdminWelcomeModalComponent implements OnInit {
- @ViewChild('modal', { static: true }) modal: ElementRef
+ private userService = inject(UserService)
+ private modalService = inject(NgbModal)
+ private notifier = inject(Notifier)
- @Output() created = new EventEmitter<void>()
+ readonly modal = viewChild<ElementRef>('modal')
+
+ readonly created = output()
private LS_KEYS = {
NO_WELCOME_MODAL: 'no_welcome_modal'
}
- constructor (
- private userService: UserService,
- private modalService: NgbModal,
- private notifier: Notifier
- ) { }
-
ngOnInit () {
this.created.emit()
}
@@ -39,7 +37,7 @@ export class AdminWelcomeModalComponent implements OnInit {
}
show () {
- this.modalService.open(this.modal, {
+ this.modalService.open(this.modal(), {
centered: true,
backdrop: 'static',
keyboard: false,
diff --git a/client/src/app/modal/confirm.component.ts b/client/src/app/modal/confirm.component.ts
index 14191455df..f6053cc8f6 100644
--- a/client/src/app/modal/confirm.component.ts
+++ b/client/src/app/modal/confirm.component.ts
@@ -1,4 +1,4 @@
-import { Component, ElementRef, OnInit, ViewChild } from '@angular/core'
+import { Component, ElementRef, OnInit, inject, viewChild } from '@angular/core'
import { HtmlRendererService } from '@app/core'
import { ConfirmService } from '@app/core/confirm/confirm.service'
import { POP_STATE_MODAL_DISMISS } from '@app/helpers'
@@ -16,7 +16,11 @@ import { GlobalIconComponent } from '../shared/shared-icons/global-icon.componen
imports: [ GlobalIconComponent, NgIf, FormsModule, InputTextComponent ]
})
export class ConfirmComponent implements OnInit {
- @ViewChild('confirmModal', { static: true }) confirmModal: ElementRef
+ private modalService = inject(NgbModal)
+ private html = inject(HtmlRendererService)
+ private confirmService = inject(ConfirmService)
+
+ readonly confirmModal = viewChild<ElementRef>('confirmModal')
title = ''
message = ''
@@ -32,12 +36,6 @@ export class ConfirmComponent implements OnInit {
private openedModal: NgbModalRef
- constructor (
- private modalService: NgbModal,
- private html: HtmlRendererService,
- private confirmService: ConfirmService
- ) { }
-
ngOnInit () {
this.confirmService.showConfirm.subscribe(
payload => {
@@ -93,17 +91,17 @@ export class ConfirmComponent implements OnInit {
showModal () {
this.inputValue = ''
- this.openedModal = this.modalService.open(this.confirmModal, { centered: true })
+ this.openedModal = this.modalService.open(this.confirmModal(), { centered: true })
this.openedModal.result
- .then(() => {
- this.confirmService.confirmResponse.next({ confirmed: true, value: this.inputValue })
- })
- .catch((reason: string) => {
- // If the reason was that the user used the back button, we don't care about the confirm dialog result
- if (!reason || reason !== POP_STATE_MODAL_DISMISS) {
- this.confirmService.confirmResponse.next({ confirmed: false, value: this.inputValue })
- }
- })
+ .then(() => {
+ this.confirmService.confirmResponse.next({ confirmed: true, value: this.inputValue })
+ })
+ .catch((reason: string) => {
+ // If the reason was that the user used the back button, we don't care about the confirm dialog result
+ if (!reason || reason !== POP_STATE_MODAL_DISMISS) {
+ this.confirmService.confirmResponse.next({ confirmed: false, value: this.inputValue })
+ }
+ })
}
}
diff --git a/client/src/app/modal/custom-modal.component.html b/client/src/app/modal/custom-modal.component.html
index 9d49a05701..57880971c1 100644
--- a/client/src/app/modal/custom-modal.component.html
+++ b/client/src/app/modal/custom-modal.component.html
@@ -1,6 +1,6 @@
<ng-template #modal let-hide="close">
<div class="modal-header">
- <h4 class="modal-title">{{title}}</h4>
+ <h4 class="modal-title">{{ title }}</h4>
<button *ngIf="close" class="border-0 p-0" title="Close this modal" i18n-title (click)="onCloseClick()">
<my-global-icon iconName="cross"></my-global-icon>
@@ -11,12 +11,12 @@
<div *ngIf="hasCancel() || hasConfirm()" class="modal-footer inputs">
<input
- *ngIf="hasCancel()" type="button" role="button" value="{{cancel.value}}" class="peertube-button secondary-button"
+ *ngIf="hasCancel()" type="button" role="button" [value]="cancel.value" class="peertube-button secondary-button"
(click)="onCancelClick()" (key.enter)="onCancelClick()"
>
<input
- *ngIf="hasConfirm()" type="button" role="button" value="{{confirm.value}}" class="peertube-button primary-button"
+ *ngIf="hasConfirm()" type="button" role="button" [value]="confirm.value" class="peertube-button primary-button"
(click)="onConfirmClick()" (key.enter)="onConfirmClick()"
>
</div>
diff --git a/client/src/app/modal/custom-modal.component.ts b/client/src/app/modal/custom-modal.component.ts
index fe20dbd9c2..bb4050b170 100644
--- a/client/src/app/modal/custom-modal.component.ts
+++ b/client/src/app/modal/custom-modal.component.ts
@@ -1,8 +1,8 @@
-import { Component, ElementRef, Input, ViewChild } from '@angular/core'
+import { NgIf } from '@angular/common'
+import { Component, ElementRef, inject, viewChild } from '@angular/core'
import { NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap'
import { logger } from '@root-helpers/logger'
import { GlobalIconComponent } from '../shared/shared-icons/global-icon.component'
-import { NgIf } from '@angular/common'
@Component({
selector: 'my-custom-modal',
@@ -11,19 +11,17 @@ import { NgIf } from '@angular/common'
imports: [ NgIf, GlobalIconComponent ]
})
export class CustomModalComponent {
- @ViewChild('modal', { static: true }) modal: ElementRef
+ private modalService = inject(NgbModal)
- @Input() title: string
- @Input() content: string
- @Input() close?: boolean
- @Input() cancel?: { value: string, action?: () => void }
- @Input() confirm?: { value: string, action?: () => void }
+ readonly modal = viewChild<ElementRef>('modal')
- private modalRef: NgbModalRef
+ title: string
+ content: string
+ close: boolean
+ cancel: { value: string, action?: () => void }
+ confirm: { value: string, action?: () => void }
- constructor (
- private modalService: NgbModal
- ) { }
+ private modalRef: NgbModalRef
show (input: {
title: string
@@ -45,7 +43,7 @@ export class CustomModalComponent {
this.cancel = cancel
this.confirm = confirm
- this.modalRef = this.modalService.open(this.modal, {
+ this.modalRef = this.modalService.open(this.modal(), {
centered: true,
backdrop: 'static',
keyboard: false,
@@ -56,8 +54,9 @@ export class CustomModalComponent {
onCancelClick () {
this.modalRef.close()
- if (typeof this.cancel.action === 'function') {
- this.cancel.action()
+ const cancel = this.cancel
+ if (typeof cancel.action === 'function') {
+ cancel.action()
}
this.destroy()
@@ -71,8 +70,9 @@ export class CustomModalComponent {
onConfirmClick () {
this.modalRef.close()
- if (typeof this.confirm.action === 'function') {
- this.confirm.action()
+ const confirm = this.confirm
+ if (typeof confirm.action === 'function') {
+ confirm.action()
}
this.destroy()
diff --git a/client/src/app/modal/instance-config-warning-modal.component.ts b/client/src/app/modal/instance-config-warning-modal.component.ts
index 0561267d26..6ecbd8d4b0 100644
--- a/client/src/app/modal/instance-config-warning-modal.component.ts
+++ b/client/src/app/modal/instance-config-warning-modal.component.ts
@@ -1,5 +1,5 @@
import { CommonModule, Location } from '@angular/common'
-import { Component, ElementRef, EventEmitter, OnInit, Output, ViewChild } from '@angular/core'
+import { Component, ElementRef, OnInit, inject, output, viewChild } from '@angular/core'
import { FormsModule } from '@angular/forms'
import { Notifier, User, UserService } from '@app/core'
import { PeertubeCheckboxComponent } from '@app/shared/shared-forms/peertube-checkbox.component'
@@ -16,9 +16,14 @@ import { peertubeLocalStorage } from '@root-helpers/peertube-web-storage'
imports: [ CommonModule, FormsModule, GlobalIconComponent, PeertubeCheckboxComponent ]
})
export class InstanceConfigWarningModalComponent implements OnInit {
- @ViewChild('modal', { static: true }) modal: ElementRef
+ private userService = inject(UserService)
+ private location = inject(Location)
+ private modalService = inject(NgbModal)
+ private notifier = inject(Notifier)
- @Output() created = new EventEmitter<void>()
+ readonly modal = viewChild<ElementRef>('modal')
+
+ readonly created = output()
stopDisplayModal = false
about: About
@@ -27,13 +32,6 @@ export class InstanceConfigWarningModalComponent implements OnInit {
NO_INSTANCE_CONFIG_WARNING_MODAL: 'no_instance_config_warning_modal'
}
- constructor (
- private userService: UserService,
- private location: Location,
- private modalService: NgbModal,
- private notifier: Notifier
- ) { }
-
ngOnInit (): void {
this.created.emit()
}
@@ -60,7 +58,7 @@ export class InstanceConfigWarningModalComponent implements OnInit {
this.about = about
- const ref = this.modalService.open(this.modal, { centered: true })
+ const ref = this.modalService.open(this.modal(), { centered: true })
ref.result.finally(() => {
if (this.stopDisplayModal === true) this.doNotOpenAgain()
@@ -75,10 +73,10 @@ export class InstanceConfigWarningModalComponent implements OnInit {
peertubeLocalStorage.setItem(this.LS_KEYS.NO_INSTANCE_CONFIG_WARNING_MODAL, 'true')
this.userService.updateMyProfile({ noInstanceConfigWarningModal: true })
- .subscribe({
- next: () => logger.info('We will not open the instance config warning modal again.'),
+ .subscribe({
+ next: () => logger.info('We will not open the instance config warning modal again.'),
- error: err => this.notifier.error(err.message)
- })
+ error: err => this.notifier.error(err.message)
+ })
}
}
diff --git a/client/src/app/shared/shared-abuse-list/abuse-details.component.html b/client/src/app/shared/shared-abuse-list/abuse-details.component.html
index b456aeed98..4b16b3d490 100644
--- a/client/src/app/shared/shared-abuse-list/abuse-details.component.html
+++ b/client/src/app/shared/shared-abuse-list/abuse-details.component.html
@@ -3,57 +3,57 @@
<div class="left">
<!-- report metadata -->
- <div class="d-flex" *ngIf="isAdminView && abuse.reporterAccount">
+ <div class="d-flex" *ngIf="isAdminView() && abuse().reporterAccount">
<span class="moderation-expanded-label" i18n>Reporter</span>
<span class="moderation-expanded-text">
- <a [routerLink]="[ '.' ]" [queryParams]="{ 'search': 'reporter:&quot;' + abuse.reporterAccount.displayName + '&quot;' }"
+ <a [routerLink]="[ '.' ]" [queryParams]="{ 'search': 'reporter:&quot;' + abuse().reporterAccount.displayName + '&quot;' }"
class="chip me-1"
>
- <my-actor-avatar size="18" [actor]="abuse.reporterAccount" actorType="account"></my-actor-avatar>
- <span class="muted">{{ abuse.reporterAccount.nameWithHost }}</span>
+ <my-actor-avatar size="18" [actor]="abuse().reporterAccount" actorType="account"></my-actor-avatar>
+ <span class="muted">{{ abuse().reporterAccount.nameWithHost }}</span>
</a>
- <a [routerLink]="[ '.' ]" [queryParams]="{ 'search': 'reporter:&quot;' + abuse.reporterAccount.displayName + '&quot;' }"
+ <a [routerLink]="[ '.' ]" [queryParams]="{ 'search': 'reporter:&quot;' + abuse().reporterAccount.displayName + '&quot;' }"
class="ms-auto muted abuse-details-links" i18n
>
- {abuse.countReportsForReporter, plural, =1 {1 report} other {{{ abuse.countReportsForReporter }} reports}}
+ {abuse().countReportsForReporter, plural, =1 {1 report} other {{{ abuse().countReportsForReporter }} reports}}
<my-global-icon iconName="flag"></my-global-icon>
</a>
</span>
</div>
- <div class="d-flex" *ngIf="abuse.flaggedAccount">
+ <div class="d-flex" *ngIf="abuse().flaggedAccount">
<span class="moderation-expanded-label" i18n>Reportee</span>
<span class="moderation-expanded-text">
- <a [routerLink]="[ '.' ]" [queryParams]="{ 'search': 'reportee:&quot;' +abuse.flaggedAccount.displayName + '&quot;' }"
+ <a [routerLink]="[ '.' ]" [queryParams]="{ 'search': 'reportee:&quot;' +abuse().flaggedAccount.displayName + '&quot;' }"
class="chip me-1"
>
- <my-actor-avatar size="18" [actor]="abuse.flaggedAccount" actorType="account"></my-actor-avatar>
- <span class="muted">{{ abuse.flaggedAccount ? abuse.flaggedAccount.nameWithHost : '' }}</span>
+ <my-actor-avatar size="18" [actor]="abuse().flaggedAccount" actorType="account"></my-actor-avatar>
+ <span class="muted">{{ abuse().flaggedAccount ? abuse().flaggedAccount.nameWithHost : '' }}</span>
</a>
- <a *ngIf="isAdminView" [routerLink]="[ '.' ]" [queryParams]="{ 'search': 'reportee:&quot;' +abuse.flaggedAccount.displayName + '&quot;' }"
+ <a *ngIf="isAdminView()" [routerLink]="[ '.' ]" [queryParams]="{ 'search': 'reportee:&quot;' +abuse().flaggedAccount.displayName + '&quot;' }"
class="ms-auto muted abuse-details-links" i18n
>
- {abuse.countReportsForReportee, plural, =1 {1 report} other {{{ abuse.countReportsForReportee }} reports}}
+ {abuse().countReportsForReportee, plural, =1 {1 report} other {{{ abuse().countReportsForReportee }} reports}}
<my-global-icon iconName="flag"></my-global-icon>
</a>
</span>
</div>
- <div class="d-flex" *ngIf="abuse.updatedAt">
+ <div class="d-flex" *ngIf="abuse().updatedAt">
<span class="moderation-expanded-label" i18n>Updated</span>
- <time class="moderation-expanded-text abuse-details-date-updated">{{ abuse.updatedAt | ptDate: 'medium' }}</time>
+ <time class="moderation-expanded-text abuse-details-date-updated">{{ abuse().updatedAt | ptDate: 'medium' }}</time>
</div>
<!-- report text -->
<div class="mt-3 d-flex">
<span class="moderation-expanded-label">
<ng-container i18n>Report</ng-container>
- <a [routerLink]="[ '.' ]" [queryParams]="{ 'search': '#' + abuse.id }" class="ms-1 muted">#{{ abuse.id }}</a>
+ <a [routerLink]="[ '.' ]" [queryParams]="{ 'search': '#' + abuse().id }" class="ms-1 muted">#{{ abuse().id }}</a>
</span>
- <span class="moderation-expanded-text" [innerHTML]="abuse.reasonHtml"></span>
+ <span class="moderation-expanded-text" [innerHTML]="abuse().reasonHtml"></span>
</div>
<div *ngIf="predefinedReasons" class="mt-2 d-flex">
@@ -66,33 +66,33 @@
</span>
</div>
- <div *ngIf="abuse.video?.startAt" class="mt-2 d-flex">
+ <div *ngIf="abuse().video?.startAt" class="mt-2 d-flex">
<span class="moderation-expanded-label" i18n>Reported part</span>
<span>
- {{ startAt }}<ng-container *ngIf="abuse.video.endAt"> - {{ endAt }}</ng-container>
+ {{ startAt }}<ng-container *ngIf="abuse().video.endAt"> - {{ endAt }}</ng-container>
</span>
</div>
- <div class="mt-3 d-flex" *ngIf="isAdminView && abuse.moderationComment">
+ <div class="mt-3 d-flex" *ngIf="isAdminView() && abuse().moderationComment">
<span class="moderation-expanded-label" i18n>Note</span>
- <span class="moderation-expanded-text d-block" [innerHTML]="abuse.moderationCommentHtml"></span>
+ <span class="moderation-expanded-text d-block" [innerHTML]="abuse().moderationCommentHtml"></span>
</div>
</div>
<!-- report right part (video/comment details) -->
<div class="right">
- <div *ngIf="abuse.video">
- <div *ngIf="abuse.video.deleted" i18n>The video was deleted</div>
- <my-embed *ngIf="!abuse.video.deleted" [video]="abuse.video"></my-embed>
+ <div *ngIf="abuse().video">
+ <div *ngIf="abuse().video.deleted" i18n>The video was deleted</div>
+ <my-embed *ngIf="!abuse().video.deleted" [video]="abuse().video"></my-embed>
</div>
- <div *ngIf="abuse.comment" class="comment-html">
+ <div *ngIf="abuse().comment" class="comment-html">
<div>
<strong i18n>Comment:</strong>
</div>
- <div [innerHTML]="abuse.commentHTML"></div>
+ <div [innerHTML]="abuse().commentHTML"></div>
</div>
</div>
</div>
diff --git a/client/src/app/shared/shared-abuse-list/abuse-details.component.ts b/client/src/app/shared/shared-abuse-list/abuse-details.component.ts
index 6947254e1f..d11b75dcfa 100644
--- a/client/src/app/shared/shared-abuse-list/abuse-details.component.ts
+++ b/client/src/app/shared/shared-abuse-list/abuse-details.component.ts
@@ -1,5 +1,5 @@
import { NgFor, NgIf } from '@angular/common'
-import { Component, Input, OnInit } from '@angular/core'
+import { Component, OnInit, input } from '@angular/core'
import { RouterLink } from '@angular/router'
import { durationToString } from '@app/helpers'
import { AbusePredefinedReasonsString } from '@peertube/peertube-models'
@@ -16,8 +16,8 @@ import { ProcessedAbuse } from './processed-abuse.model'
imports: [ NgIf, RouterLink, ActorAvatarComponent, GlobalIconComponent, NgFor, EmbedComponent, PTDatePipe ]
})
export class AbuseDetailsComponent implements OnInit {
- @Input() abuse: ProcessedAbuse
- @Input() isAdminView: boolean
+ readonly abuse = input<ProcessedAbuse>(undefined)
+ readonly isAdminView = input<boolean>(undefined)
predefinedReasons: { id: string, label: string }[]
private predefinedReasonsTranslations: { [key in AbusePredefinedReasonsString]: string }
@@ -36,19 +36,20 @@ export class AbuseDetailsComponent implements OnInit {
}
ngOnInit (): void {
- if (!this.abuse.predefinedReasons) return
+ const abuse = this.abuse()
+ if (!abuse.predefinedReasons) return
- this.predefinedReasons = this.abuse.predefinedReasons.map(r => ({
+ this.predefinedReasons = abuse.predefinedReasons.map(r => ({
id: r,
label: this.predefinedReasonsTranslations[r]
}))
}
get startAt () {
- return durationToString(this.abuse.video.startAt)
+ return durationToString(this.abuse().video.startAt)
}
get endAt () {
- return durationToString(this.abuse.video.endAt)
+ return durationToString(this.abuse().video.endAt)
}
}
diff --git a/client/src/app/shared/shared-abuse-list/abuse-list-table.component.ts b/client/src/app/shared/shared-abuse-list/abuse-list-table.component.ts
index ef97654cd6..b582b73677 100644
--- a/client/src/app/shared/shared-abuse-list/abuse-list-table.component.ts
+++ b/client/src/app/shared/shared-abuse-list/abuse-list-table.component.ts
@@ -1,5 +1,5 @@
import { NgClass, NgIf } from '@angular/common'
-import { Component, Input, OnDestroy, OnInit, ViewChild } from '@angular/core'
+import { Component, OnDestroy, OnInit, inject, input, viewChild } from '@angular/core'
import { ActivatedRoute, Router } from '@angular/router'
import { ConfirmService, HooksService, MarkdownService, Notifier, PluginService, RestPagination, RestTable } from '@app/core'
import { formatICU } from '@app/helpers'
@@ -57,10 +57,23 @@ const debugLogger = debug('peertube:moderation:AbuseListTableComponent')
]
})
export class AbuseListTableComponent extends RestTable implements OnInit, OnDestroy {
- @Input() viewType: 'admin' | 'user'
-
- @ViewChild('abuseMessagesModal', { static: true }) abuseMessagesModal: AbuseMessageModalComponent
- @ViewChild('moderationCommentModal', { static: true }) moderationCommentModal: ModerationCommentModalComponent
+ protected route = inject(ActivatedRoute)
+ protected router = inject(Router)
+ private notifier = inject(Notifier)
+ private abuseService = inject(AbuseService)
+ private blocklistService = inject(BlocklistService)
+ private commentService = inject(VideoCommentService)
+ private videoService = inject(VideoService)
+ private videoBlocklistService = inject(VideoBlockService)
+ private confirmService = inject(ConfirmService)
+ private markdownRenderer = inject(MarkdownService)
+ private hooks = inject(HooksService)
+ private pluginService = inject(PluginService)
+
+ readonly viewType = input<'admin' | 'user'>(undefined)
+
+ readonly abuseMessagesModal = viewChild<AbuseMessageModalComponent>('abuseMessagesModal')
+ readonly moderationCommentModal = viewChild<ModerationCommentModalComponent>('moderationCommentModal')
abuses: ProcessedAbuse[] = []
totalRecords = 0
@@ -97,25 +110,9 @@ export class AbuseListTableComponent extends RestTable implements OnInit, OnDest
}
]
- constructor (
- protected route: ActivatedRoute,
- protected router: Router,
- private notifier: Notifier,
- private abuseService: AbuseService,
- private blocklistService: BlocklistService,
- private commentService: VideoCommentService,
- private videoService: VideoService,
- private videoBlocklistService: VideoBlockService,
- private confirmService: ConfirmService,
- private markdownRenderer: MarkdownService,
- private hooks: HooksService,
- private pluginService: PluginService
- ) {
- super()
- }
-
async ngOnInit () {
- if (this.viewType === 'admin') {
+ const viewType = this.viewType()
+ if (viewType === 'admin') {
this.pluginService.addAction('admin-abuse-list:load-data', () => this.reloadDataInternal())
}
@@ -131,7 +128,7 @@ export class AbuseListTableComponent extends RestTable implements OnInit, OnDest
this.buildAccountActions()
]
- this.abuseActions = this.viewType === 'admin'
+ this.abuseActions = viewType === 'admin'
? await this.hooks.wrapObject(abuseActions, 'admin-comments', 'filter:admin-abuse-list.actions.create.result')
: abuseActions
@@ -139,13 +136,13 @@ export class AbuseListTableComponent extends RestTable implements OnInit, OnDest
}
ngOnDestroy () {
- if (this.viewType === 'admin') {
+ if (this.viewType() === 'admin') {
this.pluginService.removeAction('admin-abuse-list:load-data')
}
}
isAdminView () {
- return this.viewType === 'admin'
+ return this.viewType() === 'admin'
}
getIdentifier () {
@@ -153,7 +150,7 @@ export class AbuseListTableComponent extends RestTable implements OnInit, OnDest
}
openModerationCommentModal (abuse: AdminAbuse) {
- this.moderationCommentModal.openModal(abuse)
+ this.moderationCommentModal().openModal(abuse)
}
onModerationCommentUpdated () {
@@ -216,18 +213,18 @@ export class AbuseListTableComponent extends RestTable implements OnInit, OnDest
}
openAbuseMessagesModal (abuse: AdminAbuse) {
- this.abuseMessagesModal.openModal(abuse)
+ this.abuseMessagesModal().openModal(abuse)
}
isLocalAbuse (abuse: AdminAbuse) {
- if (this.viewType === 'user') return true
+ if (this.viewType() === 'user') return true
if (!abuse.reporterAccount) return false
return Actor.IS_LOCAL(abuse.reporterAccount.host)
}
getSendMessageButtonLabel (abuse: AdminAbuse) {
- if (this.viewType === 'admin') {
+ if (this.viewType() === 'admin') {
return formatICU(
$localize`Send a message to the reporter (currently {count, plural, =1 {{count} message} other {{count} messages}})`,
{ count: abuse.countMessages }
@@ -249,7 +246,7 @@ export class AbuseListTableComponent extends RestTable implements OnInit, OnDest
search: this.search
}
- const observable = this.viewType === 'admin'
+ const observable = this.viewType() === 'admin'
? this.abuseService.getAdminAbuses(options)
: this.abuseService.getUserAbuses(options)
diff --git a/client/src/app/shared/shared-abuse-list/abuse-message-modal.component.html b/client/src/app/shared/shared-abuse-list/abuse-message-modal.component.html
index 224db1ed9f..a5f6c48f8a 100644
--- a/client/src/app/shared/shared-abuse-list/abuse-message-modal.component.html
+++ b/client/src/app/shared/shared-abuse-list/abuse-message-modal.component.html
@@ -1,8 +1,8 @@
<ng-template #modal>
<div class="modal-header">
<h4 class="modal-title">
- <ng-container i18n *ngIf="isAdminView">Messages with the reporter</ng-container>
- <ng-container i18n *ngIf="!isAdminView">Messages with the moderation team</ng-container>
+ <ng-container i18n *ngIf="isAdminView()">Messages with the reporter</ng-container>
+ <ng-container i18n *ngIf="!isAdminView()">Messages with the moderation team</ng-container>
</h4>
<button class="border-0 p-0" title="Close this modal" i18n-title (click)="hide()">
diff --git a/client/src/app/shared/shared-abuse-list/abuse-message-modal.component.ts b/client/src/app/shared/shared-abuse-list/abuse-message-modal.component.ts
index 604dfafcd4..7dc8d3bbec 100644
--- a/client/src/app/shared/shared-abuse-list/abuse-message-modal.component.ts
+++ b/client/src/app/shared/shared-abuse-list/abuse-message-modal.component.ts
@@ -1,5 +1,5 @@
import { NgClass, NgFor, NgIf } from '@angular/common'
-import { Component, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core'
+import { Component, OnInit, inject, input, output, viewChild } from '@angular/core'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { AuthService, HtmlRendererService, Notifier } from '@app/core'
import { FormReactive } from '@app/shared/shared-forms/form-reactive'
@@ -20,11 +20,21 @@ import { AbuseService } from '../shared-moderation/abuse.service'
imports: [ NgIf, GlobalIconComponent, NgFor, NgClass, FormsModule, ReactiveFormsModule, PTDatePipe ]
})
export class AbuseMessageModalComponent extends FormReactive implements OnInit {
- @ViewChild('modal', { static: true }) modal: NgbModal
+ protected formReactiveService = inject(FormReactiveService)
+ private modalService = inject(NgbModal)
+ private htmlRenderer = inject(HtmlRendererService)
+ private auth = inject(AuthService)
+ private notifier = inject(Notifier)
+ private abuseService = inject(AbuseService)
- @Input() isAdminView: boolean
+ readonly modal = viewChild<NgbModal>('modal')
- @Output() countMessagesUpdated = new EventEmitter<{ abuseId: number, countMessages: number }>()
+ readonly isAdminView = input<boolean>(undefined)
+
+ readonly countMessagesUpdated = output<{
+ abuseId: number
+ countMessages: number
+ }>()
abuseMessages: (AbuseMessage & { messageHtml: string })[] = []
textareaMessage: string
@@ -34,17 +44,6 @@ export class AbuseMessageModalComponent extends FormReactive implements OnInit {
private openedModal: NgbModalRef
private abuse: UserAbuse
- constructor (
- protected formReactiveService: FormReactiveService,
- private modalService: NgbModal,
- private htmlRenderer: HtmlRendererService,
- private auth: AuthService,
- private notifier: Notifier,
- private abuseService: AbuseService
- ) {
- super()
- }
-
ngOnInit () {
this.buildForm({
message: ABUSE_MESSAGE_VALIDATOR
@@ -54,7 +53,7 @@ export class AbuseMessageModalComponent extends FormReactive implements OnInit {
openModal (abuse: UserAbuse) {
this.abuse = abuse
- this.openedModal = this.modalService.open(this.modal, { centered: true })
+ this.openedModal = this.modalService.open(this.modal(), { centered: true })
this.loadMessages()
}
@@ -103,7 +102,7 @@ export class AbuseMessageModalComponent extends FormReactive implements OnInit {
}
getPlaceholderMessage () {
- if (this.isAdminView) {
+ if (this.isAdminView()) {
return $localize`Add a message to communicate with the reporter`
}
@@ -134,5 +133,4 @@ export class AbuseMessageModalComponent extends FormReactive implements OnInit {
error: err => this.notifier.error(err.message)
})
}
-
}
diff --git a/client/src/app/shared/shared-abuse-list/moderation-comment-modal.component.ts b/client/src/app/shared/shared-abuse-list/moderation-comment-modal.component.ts
index 8c1d3f151f..684b5ce519 100644
--- a/client/src/app/shared/shared-abuse-list/moderation-comment-modal.component.ts
+++ b/client/src/app/shared/shared-abuse-list/moderation-comment-modal.component.ts
@@ -1,4 +1,4 @@
-import { Component, EventEmitter, OnInit, Output, ViewChild } from '@angular/core'
+import { Component, OnInit, inject, output, viewChild } from '@angular/core'
import { Notifier } from '@app/core'
import { FormReactive } from '@app/shared/shared-forms/form-reactive'
import { FormReactiveService } from '@app/shared/shared-forms/form-reactive.service'
@@ -18,21 +18,17 @@ import { AbuseService } from '../shared-moderation/abuse.service'
imports: [ GlobalIconComponent, FormsModule, ReactiveFormsModule, NgClass, NgIf ]
})
export class ModerationCommentModalComponent extends FormReactive implements OnInit {
- @ViewChild('modal', { static: true }) modal: NgbModal
- @Output() commentUpdated = new EventEmitter<string>()
+ protected formReactiveService = inject(FormReactiveService)
+ private modalService = inject(NgbModal)
+ private notifier = inject(Notifier)
+ private abuseService = inject(AbuseService)
+
+ readonly modal = viewChild<NgbModal>('modal')
+ readonly commentUpdated = output<string>()
private abuseToComment: AdminAbuse
private openedModal: NgbModalRef
- constructor (
- protected formReactiveService: FormReactiveService,
- private modalService: NgbModal,
- private notifier: Notifier,
- private abuseService: AbuseService
- ) {
- super()
- }
-
ngOnInit () {
this.buildForm({
moderationComment: ABUSE_MODERATION_COMMENT_VALIDATOR
@@ -41,7 +37,7 @@ export class ModerationCommentModalComponent extends FormReactive implements OnI
openModal (abuseToComment: AdminAbuse) {
this.abuseToComment = abuseToComment
- this.openedModal = this.modalService.open(this.modal, { centered: true })
+ this.openedModal = this.modalService.open(this.modal(), { centered: true })
this.form.patchValue({
moderationComment: this.abuseToComment.moderationComment
@@ -58,16 +54,15 @@ export class ModerationCommentModalComponent extends FormReactive implements OnI
const moderationComment: string = this.form.value['moderationComment']
this.abuseService.updateAbuse(this.abuseToComment, { moderationComment })
- .subscribe({
- next: () => {
- this.notifier.success($localize`Comment updated.`)
+ .subscribe({
+ next: () => {
+ this.notifier.success($localize`Comment updated.`)
- this.commentUpdated.emit(moderationComment)
- this.hide()
- },
+ this.commentUpdated.emit(moderationComment)
+ this.hide()
+ },
- error: err => this.notifier.error(err.message)
- })
+ error: err => this.notifier.error(err.message)
+ })
}
-
}
diff --git a/client/src/app/shared/shared-actor-image-edit/actor-avatar-edit.component.html b/client/src/app/shared/shared-actor-image-edit/actor-avatar-edit.component.html
index 58986d0136..1517fe7aa2 100644
--- a/client/src/app/shared/shared-actor-image-edit/actor-avatar-edit.component.html
+++ b/client/src/app/shared/shared-actor-image-edit/actor-avatar-edit.component.html
@@ -1,8 +1,8 @@
<div class="actor" *ngIf="actor">
<div class="position-relative me-3">
- <my-actor-avatar [actor]="actor" [actorType]="actorType" [previewImage]="preview" size="100"></my-actor-avatar>
+ <my-actor-avatar [actor]="actor" [actorType]="actorType()" [previewImage]="preview" size="100"></my-actor-avatar>
- @if (editable) {
+ @if (editable()) {
@if (hasAvatar()) {
<div ngbDropdown placement="right">
<button type="button" class="actor-img-edit-button button-file primary-button" i18n-arialLabel aria-label="Change your avatar" ngbDropdownToggle>
@@ -13,7 +13,7 @@
<div class="dropdown-item dropdown-file button-focus-within" [ngbTooltip]="avatarFormat">
<my-global-icon iconName="upload"></my-global-icon>
<label for="avatarfile" i18n>Upload a new avatar</label>
- <input #avatarfileInput type="file" name="avatarfile" id="avatarfile" [accept]="avatarExtensions" (change)="onAvatarChange(avatarfileInput)"/>
+ <input #avatarfileInput type="file" name="avatarfile" id="avatarfile" [accept]="avatarExtensions" (change)="onAvatarChange()"/>
</div>
<button type="button" class="dropdown-item" (click)="deleteAvatar()" (key.enter)="deleteAvatar()">
@@ -26,15 +26,15 @@
<div class="actor-img-edit-button button-file primary-button button-focus-within" [ngbTooltip]="avatarFormat" placement="right" container="body">
<my-global-icon iconName="upload"></my-global-icon>
<label class="visually-hidden" for="avatarfile" i18n>Upload a new avatar</label>
- <input #avatarfileInput type="file" name="avatarfile" id="avatarfile" [accept]="avatarExtensions" (change)="onAvatarChange(avatarfileInput)"/>
+ <input #avatarfileInput type="file" name="avatarfile" id="avatarfile" [accept]="avatarExtensions" (change)="onAvatarChange()"/>
</div>
}
}
</div>
<div class="actor-info">
- <div *ngIf="displayName" class="actor-info-display-name">{{ displayName }}</div>
- <div *ngIf="displayUsername && username" class="actor-info-username">{{ username }}</div>
- <div *ngIf="subscribers" i18n class="actor-info-followers">{{ subscribers }} subscribers</div>
+ <div *ngIf="displayName()" class="actor-info-display-name">{{ displayName() }}</div>
+ <div *ngIf="displayUsername() && username()" class="actor-info-username">{{ username() }}</div>
+ <div *ngIf="subscribers()" i18n class="actor-info-followers">{{ subscribers() }} subscribers</div>
</div>
</div>
diff --git a/client/src/app/shared/shared-actor-image-edit/actor-avatar-edit.component.ts b/client/src/app/shared/shared-actor-image-edit/actor-avatar-edit.component.ts
index 5f3319b362..d0bcbf5726 100644
--- a/client/src/app/shared/shared-actor-image-edit/actor-avatar-edit.component.ts
+++ b/client/src/app/shared/shared-actor-image-edit/actor-avatar-edit.component.ts
@@ -1,12 +1,12 @@
-import { Component, ElementRef, EventEmitter, Input, OnChanges, OnInit, Output, ViewChild, booleanAttribute } from '@angular/core'
+import { NgIf } from '@angular/common'
+import { Component, ElementRef, OnChanges, OnInit, booleanAttribute, inject, input, output, viewChild } from '@angular/core'
import { Notifier, ServerService } from '@app/core'
+import { NgbDropdown, NgbDropdownMenu, NgbDropdownToggle, NgbTooltip } from '@ng-bootstrap/ng-bootstrap'
+import { ActorImage } from '@peertube/peertube-models'
import { getBytes } from '@root-helpers/bytes'
import { imageToDataURL } from '@root-helpers/images'
-import { ActorAvatarInput, ActorAvatarComponent } from '../shared-actor-image/actor-avatar.component'
-import { ActorImage } from '@peertube/peertube-models'
+import { ActorAvatarComponent, ActorAvatarInput } from '../shared-actor-image/actor-avatar.component'
import { GlobalIconComponent } from '../shared-icons/global-icon.component'
-import { NgbTooltip, NgbDropdown, NgbDropdownToggle, NgbDropdownMenu } from '@ng-bootstrap/ng-bootstrap'
-import { NgIf } from '@angular/common'
@Component({
selector: 'my-actor-avatar-edit',
@@ -18,21 +18,24 @@ import { NgIf } from '@angular/common'
imports: [ NgIf, ActorAvatarComponent, NgbTooltip, GlobalIconComponent, NgbDropdown, NgbDropdownToggle, NgbDropdownMenu ]
})
export class ActorAvatarEditComponent implements OnInit, OnChanges {
- @ViewChild('avatarfileInput') avatarfileInput: ElementRef<HTMLInputElement>
+ private serverService = inject(ServerService)
+ private notifier = inject(Notifier)
- @Input({ required: true }) actorType: 'channel' | 'account'
- @Input({ required: true }) avatars: ActorImage[]
- @Input({ required: true }) username: string
+ readonly avatarfileInput = viewChild<ElementRef<HTMLInputElement>>('avatarfileInput')
- @Input() displayName: string
- @Input() subscribers: number
+ readonly actorType = input.required<'channel' | 'account'>()
+ readonly avatars = input.required<ActorImage[]>()
+ readonly username = input.required<string>()
- @Input({ transform: booleanAttribute }) displayUsername = true
- @Input({ transform: booleanAttribute }) editable = true
- @Input({ transform: booleanAttribute }) previewImage = false
+ readonly displayName = input<string>(undefined)
+ readonly subscribers = input<number>(undefined)
- @Output() avatarChange = new EventEmitter<FormData>()
- @Output() avatarDelete = new EventEmitter<void>()
+ readonly displayUsername = input(true, { transform: booleanAttribute })
+ readonly editable = input(true, { transform: booleanAttribute })
+ readonly previewImage = input(false, { transform: booleanAttribute })
+
+ readonly avatarChange = output<FormData>()
+ readonly avatarDelete = output()
avatarFormat = ''
maxAvatarSize = 0
@@ -42,11 +45,6 @@ export class ActorAvatarEditComponent implements OnInit, OnChanges {
actor: ActorAvatarInput
- constructor (
- private serverService: ServerService,
- private notifier: Notifier
- ) { }
-
ngOnInit (): void {
const config = this.serverService.getHTMLConfig()
@@ -58,15 +56,13 @@ export class ActorAvatarEditComponent implements OnInit, OnChanges {
ngOnChanges () {
this.actor = {
- avatars: this.avatars,
- name: this.username
+ avatars: this.avatars(),
+ name: this.username()
}
}
- onAvatarChange (input: HTMLInputElement) {
- this.avatarfileInput = new ElementRef(input)
-
- const avatarfile = this.avatarfileInput.nativeElement.files[0]
+ onAvatarChange () {
+ const avatarfile = this.avatarfileInput().nativeElement.files[0]
if (avatarfile.size > this.maxAvatarSize) {
this.notifier.error('Error', $localize`This image is too large.`)
return
@@ -76,7 +72,7 @@ export class ActorAvatarEditComponent implements OnInit, OnChanges {
formData.append('avatarfile', avatarfile)
this.avatarChange.emit(formData)
- if (this.previewImage) {
+ if (this.previewImage()) {
imageToDataURL(avatarfile).then(result => this.preview = result)
}
}
@@ -87,6 +83,6 @@ export class ActorAvatarEditComponent implements OnInit, OnChanges {
}
hasAvatar () {
- return !!this.preview || this.avatars.length !== 0
+ return !!this.preview || this.avatars().length !== 0
}
}
diff --git a/client/src/app/shared/shared-actor-image-edit/actor-banner-edit.component.html b/client/src/app/shared/shared-actor-image-edit/actor-banner-edit.component.html
index f739144a91..4f0d23808c 100644
--- a/client/src/app/shared/shared-actor-image-edit/actor-banner-edit.component.html
+++ b/client/src/app/shared/shared-actor-image-edit/actor-banner-edit.component.html
@@ -1,7 +1,7 @@
<div class="actor">
<div class="actor-img-edit-container">
<div class="banner-placeholder">
- <img *ngIf="hasBanner()" [src]="preview || bannerUrl" alt="Banner" />
+ <img *ngIf="hasBanner()" [src]="preview || bannerUrl()" alt="Banner" />
</div>
<div *ngIf="!hasBanner()" class="actor-img-edit-button button-file primary-button button-focus-within" [ngbTooltip]="bannerFormat" placement="right" container="body">
@@ -31,5 +31,5 @@
<ng-template #uploadNewBanner>
<my-global-icon iconName="upload"></my-global-icon>
<label for="bannerfile" i18n>Upload a new banner</label>
- <input #bannerfileInput type="file" name="bannerfile" id="bannerfile" [accept]="bannerExtensions" (change)="onBannerChange(bannerfileInput)"/>
+ <input #bannerfileInput type="file" name="bannerfile" id="bannerfile" [accept]="bannerExtensions" (change)="onBannerChange()"/>
</ng-template>
diff --git a/client/src/app/shared/shared-actor-image-edit/actor-banner-edit.component.ts b/client/src/app/shared/shared-actor-image-edit/actor-banner-edit.component.ts
index f78d283bcb..7a32c3f5ad 100644
--- a/client/src/app/shared/shared-actor-image-edit/actor-banner-edit.component.ts
+++ b/client/src/app/shared/shared-actor-image-edit/actor-banner-edit.component.ts
@@ -1,11 +1,11 @@
-import { Component, ElementRef, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core'
+import { NgIf, NgTemplateOutlet } from '@angular/common'
+import { Component, ElementRef, OnInit, inject, input, output, viewChild } from '@angular/core'
import { SafeResourceUrl } from '@angular/platform-browser'
import { Notifier, ServerService } from '@app/core'
-import { NgbPopover, NgbTooltip, NgbDropdown, NgbDropdownToggle, NgbDropdownMenu } from '@ng-bootstrap/ng-bootstrap'
+import { NgbDropdown, NgbDropdownMenu, NgbDropdownToggle, NgbPopover, NgbTooltip } from '@ng-bootstrap/ng-bootstrap'
import { getBytes } from '@root-helpers/bytes'
import { imageToDataURL } from '@root-helpers/images'
import { GlobalIconComponent } from '../shared-icons/global-icon.component'
-import { NgIf, NgTemplateOutlet } from '@angular/common'
@Component({
selector: 'my-actor-banner-edit',
@@ -17,14 +17,17 @@ import { NgIf, NgTemplateOutlet } from '@angular/common'
imports: [ NgIf, NgbTooltip, NgTemplateOutlet, NgbDropdown, NgbDropdownToggle, GlobalIconComponent, NgbDropdownMenu ]
})
export class ActorBannerEditComponent implements OnInit {
- @ViewChild('bannerfileInput') bannerfileInput: ElementRef<HTMLInputElement>
- @ViewChild('bannerPopover') bannerPopover: NgbPopover
+ private serverService = inject(ServerService)
+ private notifier = inject(Notifier)
+
+ readonly bannerfileInput = viewChild<ElementRef<HTMLInputElement>>('bannerfileInput')
+ readonly bannerPopover = viewChild<NgbPopover>('bannerPopover')
- @Input() bannerUrl: string
- @Input() previewImage = false
+ readonly bannerUrl = input<string>(undefined)
+ readonly previewImage = input(false)
- @Output() bannerChange = new EventEmitter<FormData>()
- @Output() bannerDelete = new EventEmitter<void>()
+ readonly bannerChange = output<FormData>()
+ readonly bannerDelete = output()
bannerFormat = ''
maxBannerSize = 0
@@ -32,24 +35,19 @@ export class ActorBannerEditComponent implements OnInit {
preview: SafeResourceUrl
- constructor (
- private serverService: ServerService,
- private notifier: Notifier
- ) { }
-
ngOnInit (): void {
const config = this.serverService.getHTMLConfig()
this.maxBannerSize = config.banner.file.size.max
this.bannerExtensions = config.banner.file.extensions.join(', ')
/* eslint-disable max-len */
- this.bannerFormat = $localize`ratio 6/1, recommended size: 1920x317, max size: ${getBytes(this.maxBannerSize)}, extensions: ${this.bannerExtensions}`
+ this.bannerFormat = $localize`ratio 6/1, recommended size: 1920x317, max size: ${
+ getBytes(this.maxBannerSize)
+ }, extensions: ${this.bannerExtensions}`
}
- onBannerChange (input: HTMLInputElement) {
- this.bannerfileInput = new ElementRef(input)
-
- const bannerfile = this.bannerfileInput.nativeElement.files[0]
+ onBannerChange () {
+ const bannerfile = this.bannerfileInput().nativeElement.files[0]
if (bannerfile.size > this.maxBannerSize) {
this.notifier.error('Error', $localize`This image is too large.`)
return
@@ -57,10 +55,10 @@ export class ActorBannerEditComponent implements OnInit {
const formData = new FormData()
formData.append('bannerfile', bannerfile)
- this.bannerPopover?.close()
+ this.bannerPopover()?.close()
this.bannerChange.emit(formData)
- if (this.previewImage) {
+ if (this.previewImage()) {
imageToDataURL(bannerfile).then(result => this.preview = result)
}
}
@@ -71,6 +69,6 @@ export class ActorBannerEditComponent implements OnInit {
}
hasBanner () {
- return !!this.preview || !!this.bannerUrl
+ return !!this.preview || !!this.bannerUrl()
}
}
diff --git a/client/src/app/shared/shared-actor-image/actor-avatar.component.html b/client/src/app/shared/shared-actor-image/actor-avatar.component.html
index 529297f661..39109c4960 100644
--- a/client/src/app/shared/shared-actor-image/actor-avatar.component.html
+++ b/client/src/app/shared/shared-actor-image/actor-avatar.component.html
@@ -1,5 +1,5 @@
<ng-template #img>
- <img #avatarEl *ngIf="displayImage()" [ngClass]="classes" [src]="previewImage || avatarUrl || defaultAvatarUrl" alt="" />
+ <img #avatarEl *ngIf="displayImage()" [ngClass]="classes" [src]="previewImage() || avatarUrl || defaultAvatarUrl" alt="" />
<div #avatarEl *ngIf="displayActorInitial()" [ngClass]="classes">
<span>{{ getActorInitial() }}</span>
@@ -8,14 +8,14 @@
<div #avatarEl *ngIf="displayPlaceholder()" [ngClass]="classes"></div>
</ng-template>
-<a *ngIf="actor && href" [href]="href" target="_blank" rel="noopener noreferrer" [title]="title">
+<a *ngIf="actor() && href()" [href]="href()" target="_blank" rel="noopener noreferrer" [title]="title">
<ng-template *ngTemplateOutlet="img"></ng-template>
</a>
-<a *ngIf="actor && internalHref" [routerLink]="internalHref" [title]="title">
+<a *ngIf="actor() && internalHref()" [routerLink]="internalHref()" [title]="title">
<ng-template *ngTemplateOutlet="img"></ng-template>
</a>
-<ng-container *ngIf="!actor || (!href && !internalHref)">
+<ng-container *ngIf="!actor() || (!href() && !internalHref())">
<ng-template *ngTemplateOutlet="img"></ng-template>
</ng-container>
diff --git a/client/src/app/shared/shared-actor-image/actor-avatar.component.ts b/client/src/app/shared/shared-actor-image/actor-avatar.component.ts
index 8f25a0ba7b..1e9895eb2e 100644
--- a/client/src/app/shared/shared-actor-image/actor-avatar.component.ts
+++ b/client/src/app/shared/shared-actor-image/actor-avatar.component.ts
@@ -1,4 +1,4 @@
-import { Component, ElementRef, Input, OnChanges, OnInit, ViewChild, booleanAttribute, numberAttribute } from '@angular/core'
+import { Component, ElementRef, Input, OnChanges, OnInit, booleanAttribute, numberAttribute, inject, input, viewChild } from '@angular/core'
import { Account } from '../shared-main/account/account.model'
import { objectKeysTyped } from '@peertube/peertube-core-utils'
import { RouterLink } from '@angular/router'
@@ -18,32 +18,35 @@ export type ActorAvatarInput = {
imports: [ NgIf, NgClass, NgTemplateOutlet, RouterLink ]
})
export class ActorAvatarComponent implements OnInit, OnChanges {
- @ViewChild('avatarEl') avatarEl: ElementRef
+ private el = inject(ElementRef)
- @Input() actor: ActorAvatarInput
- @Input() actorType: 'channel' | 'account' | 'instance' | 'unlogged'
+ readonly avatarEl = viewChild<ElementRef>('avatarEl')
- @Input() previewImage: string
+ readonly actor = input<ActorAvatarInput>(undefined)
+ readonly actorType = input<'channel' | 'account' | 'instance' | 'unlogged'>(undefined)
- @Input({ transform: numberAttribute }) size = 120
- @Input({ transform: booleanAttribute }) responseSize = false
+ readonly previewImage = input<string>(undefined)
+
+ readonly size = input(120, { transform: numberAttribute })
+ readonly responseSize = input(false, { transform: booleanAttribute })
// Use an external link
- @Input() href: string
+ readonly href = input<string>(undefined)
// Use routerLink
- @Input() internalHref: string | any[]
+ readonly internalHref = input<string | any[]>(undefined)
private _title: string
- @Input() set title (value) {
+ @Input()
+ set title (value) {
this._title = value
}
get title () {
if (this._title) return this._title
- if (this.isAccount()) return $localize`${this.actor.name} (account page)`
- if (this.isChannel()) return $localize`${this.actor.name} (channel page)`
- if (this.isInstance()) return $localize`${this.actor.name} (instance page)`
+ if (this.isAccount()) return $localize`${this.actor().name} (account page)`
+ if (this.isChannel()) return $localize`${this.actor().name} (channel page)`
+ if (this.isInstance()) return $localize`${this.actor().name} (instance page)`
return ''
}
@@ -52,10 +55,6 @@ export class ActorAvatarComponent implements OnInit, OnChanges {
defaultAvatarUrl: string
avatarUrl: string
- constructor (private el: ElementRef) {
-
- }
-
ngOnInit () {
this.buildDefaultAvatarUrl()
@@ -74,14 +73,15 @@ export class ActorAvatarComponent implements OnInit, OnChanges {
this.classes = [ 'avatar' ]
- if (this.size && !this.responseSize) {
- avatarSize = `${this.size}px`
+ const size = this.size()
+ if (size && !this.responseSize()) {
+ avatarSize = `${size}px`
- if (this.size <= 18) {
+ if (size <= 18) {
fontSize = '13px'
- } else if (this.size >= 100) {
+ } else if (size >= 100) {
fontSize = '40px'
- } else if (this.size >= 120) {
+ } else if (size >= 120) {
fontSize = '46px'
}
}
@@ -114,13 +114,14 @@ export class ActorAvatarComponent implements OnInit, OnChanges {
}
private buildAvatarUrl () {
- if (!this.actor) {
+ const actor = this.actor()
+ if (!actor) {
this.avatarUrl = ''
return
}
if (this.isAccount() || this.isChannel() || this.isInstance()) {
- this.avatarUrl = Actor.GET_ACTOR_AVATAR_URL(this.actor, this.getSizeNumber())
+ this.avatarUrl = Actor.GET_ACTOR_AVATAR_URL(actor, this.getSizeNumber())
return
}
@@ -128,41 +129,42 @@ export class ActorAvatarComponent implements OnInit, OnChanges {
}
displayImage () {
- if (this.actorType === 'unlogged') return true
- if (this.previewImage) return true
+ if (this.actorType() === 'unlogged') return true
+ if (this.previewImage()) return true
- return !!(this.actor && this.avatarUrl)
+ return !!(this.actor() && this.avatarUrl)
}
displayActorInitial () {
- return !this.displayImage() && this.actor && !this.avatarUrl
+ return !this.displayImage() && this.actor() && !this.avatarUrl
}
displayPlaceholder () {
- return this.actorType !== 'unlogged' && !this.actor
+ return this.actorType() !== 'unlogged' && !this.actor()
}
getActorInitial () {
- const name = this.actor?.name
+ const name = this.actor()?.name
if (!name) return ''
return name.slice(0, 1)
}
private isAccount () {
- return this.actorType === 'account'
+ return this.actorType() === 'account'
}
private isChannel () {
- return this.actorType === 'channel'
+ return this.actorType() === 'channel'
}
private isInstance () {
- return this.actorType === 'instance'
+ return this.actorType() === 'instance'
}
private getSizeNumber () {
- if (this.size) return +this.size
+ const size = this.size()
+ if (size) return +size
return undefined
}
diff --git a/client/src/app/shared/shared-custom-markup/custom-markup-container.component.ts b/client/src/app/shared/shared-custom-markup/custom-markup-container.component.ts
index a3726c00a4..53e09c9398 100644
--- a/client/src/app/shared/shared-custom-markup/custom-markup-container.component.ts
+++ b/client/src/app/shared/shared-custom-markup/custom-markup-container.component.ts
@@ -1,4 +1,4 @@
-import { Component, ElementRef, Input, OnChanges, ViewChild } from '@angular/core'
+import { Component, ElementRef, OnChanges, inject, input, viewChild } from '@angular/core'
import { CustomMarkupService } from './custom-markup.service'
@Component({
@@ -7,33 +7,32 @@ import { CustomMarkupService } from './custom-markup.service'
standalone: true
})
export class CustomMarkupContainerComponent implements OnChanges {
- @ViewChild('contentWrapper', { static: true }) contentWrapper: ElementRef<HTMLInputElement>
+ private customMarkupService = inject(CustomMarkupService)
- @Input() content: string | HTMLDivElement
+ readonly contentWrapper = viewChild<ElementRef<HTMLInputElement>>('contentWrapper')
- displayed = false
+ readonly content = input<string | HTMLDivElement>(undefined)
- constructor (
- private customMarkupService: CustomMarkupService
- ) { }
+ displayed = false
async ngOnChanges () {
await this.rebuild()
}
private async rebuild () {
- if (this.content instanceof HTMLDivElement) {
- return this.loadElement(this.content)
+ const content = this.content()
+ if (content instanceof HTMLDivElement) {
+ return this.loadElement(content)
}
- const { rootElement, componentsLoaded } = await this.customMarkupService.buildElement(this.content)
+ const { rootElement, componentsLoaded } = await this.customMarkupService.buildElement(content)
await componentsLoaded
return this.loadElement(rootElement)
}
private loadElement (el: HTMLDivElement) {
- this.contentWrapper.nativeElement.appendChild(el)
+ this.contentWrapper().nativeElement.appendChild(el)
this.displayed = true
}
diff --git a/client/src/app/shared/shared-custom-markup/custom-markup-help.component.html b/client/src/app/shared/shared-custom-markup/custom-markup-help.component.html
index 63d2508b41..631d47b9a1 100644
--- a/client/src/app/shared/shared-custom-markup/custom-markup-help.component.html
+++ b/client/src/app/shared/shared-custom-markup/custom-markup-help.component.html
@@ -2,7 +2,7 @@
<a class="text-decoration-underline" href="https://en.wikipedia.org/wiki/Markdown#Example" target="_blank" rel="noreferrer noopener">Markdown compatible</a> that also supports <a class="text-decoration-underline" href="https://docs.joinpeertube.org/api/custom-client-markup" target="_blank" rel="noreferrer noopener">custom PeerTube HTML tags</a>.
</ng-container>
-@if (supportRelMe) {
+@if (supportRelMe()) {
<br />
<ng-container i18n>
diff --git a/client/src/app/shared/shared-custom-markup/custom-markup-help.component.ts b/client/src/app/shared/shared-custom-markup/custom-markup-help.component.ts
index 43a8d7b31d..4262938163 100644
--- a/client/src/app/shared/shared-custom-markup/custom-markup-help.component.ts
+++ b/client/src/app/shared/shared-custom-markup/custom-markup-help.component.ts
@@ -1,4 +1,4 @@
-import { booleanAttribute, Component, Input } from '@angular/core'
+import { booleanAttribute, Component, input } from '@angular/core'
@Component({
selector: 'my-custom-markup-help',
@@ -6,5 +6,5 @@ import { booleanAttribute, Component, Input } from '@angular/core'
standalone: true
})
export class CustomMarkupHelpComponent {
- @Input({ transform: booleanAttribute }) supportRelMe = false
+ readonly supportRelMe = input(false, { transform: booleanAttribute })
}
diff --git a/client/src/app/shared/shared-custom-markup/custom-markup.service.ts b/client/src/app/shared/shared-custom-markup/custom-markup.service.ts
index 0387eeeece..7c7ae6ec6b 100644
--- a/client/src/app/shared/shared-custom-markup/custom-markup.service.ts
+++ b/client/src/app/shared/shared-custom-markup/custom-markup.service.ts
@@ -1,4 +1,4 @@
-import { ComponentRef, Injectable } from '@angular/core'
+import { ComponentRef, Injectable, inject } from '@angular/core'
import { MarkdownService } from '@app/core'
import {
ButtonMarkupData,
@@ -29,7 +29,10 @@ type HTMLBuilderFunction = (el: HTMLElement) => HTMLElement
@Injectable()
export class CustomMarkupService {
- private angularBuilders: { [ selector: string ]: AngularBuilderFunction } = {
+ private dynamicElementService = inject(DynamicElementService)
+ private markdown = inject(MarkdownService)
+
+ private angularBuilders: { [selector: string]: AngularBuilderFunction } = {
'peertube-instance-banner': el => this.instanceBannerBuilder(el),
'peertube-instance-avatar': el => this.instanceAvatarBuilder(el),
'peertube-button': el => this.buttonBuilder(el),
@@ -41,16 +44,13 @@ export class CustomMarkupService {
'peertube-videos-list': el => this.videosListBuilder(el)
}
- private htmlBuilders: { [ selector: string ]: HTMLBuilderFunction } = {
+ private htmlBuilders: { [selector: string]: HTMLBuilderFunction } = {
'peertube-container': el => this.containerBuilder(el)
}
private customMarkdownRenderer: (text: string) => Promise<HTMLElement>
- constructor (
- private dynamicElementService: DynamicElementService,
- private markdown: MarkdownService
- ) {
+ constructor () {
this.customMarkdownRenderer = (text: string) => {
return this.buildElement(text)
.then(({ rootElement }) => rootElement)
diff --git a/client/src/app/shared/shared-custom-markup/dynamic-element.service.ts b/client/src/app/shared/shared-custom-markup/dynamic-element.service.ts
index 1db610f944..a033283bbf 100644
--- a/client/src/app/shared/shared-custom-markup/dynamic-element.service.ts
+++ b/client/src/app/shared/shared-custom-markup/dynamic-element.service.ts
@@ -3,26 +3,28 @@ import {
ComponentRef,
createComponent,
EmbeddedViewRef,
+ inject,
Injectable,
Injector,
+ InputSignal,
OnChanges,
- SimpleChange,
SimpleChanges,
Type
} from '@angular/core'
-import { objectKeysTyped } from '@peertube/peertube-core-utils'
-import { CustomMarkupComponent } from './peertube-custom-tags/shared'
+import { outputToObservable } from '@angular/core/rxjs-interop'
import { firstValueFrom } from 'rxjs'
+import { CustomMarkupComponent } from './peertube-custom-tags/shared'
+
+type ComponentInputs<T> = {
+ [P in keyof T]: T[P] extends InputSignal<infer A> ? A : never
+}
@Injectable()
export class DynamicElementService {
+ private injector = inject(Injector)
+ private applicationRef = inject(ApplicationRef)
- constructor (
- private injector: Injector,
- private applicationRef: ApplicationRef
- ) { }
-
- createElement <T extends CustomMarkupComponent> (ofComponent: Type<T>) {
+ createElement<T extends CustomMarkupComponent> (ofComponent: Type<T>) {
const div = document.createElement('div')
const component = createComponent(ofComponent, {
@@ -32,33 +34,29 @@ export class DynamicElementService {
})
const loadedPromise = component.instance.loaded
- ? firstValueFrom(component.instance.loaded)
+ ? firstValueFrom(outputToObservable(component.instance.loaded))
: undefined
return { component, loadedPromise }
}
- injectElement <T> (wrapper: HTMLElement, componentRef: ComponentRef<T>) {
+ injectElement<T> (wrapper: HTMLElement, componentRef: ComponentRef<T>) {
const hostView = componentRef.hostView as EmbeddedViewRef<any>
this.applicationRef.attachView(hostView)
wrapper.appendChild(hostView.rootNodes[0])
}
- setModel <T> (componentRef: ComponentRef<T>, attributes: Partial<T>) {
+ setModel<T> (componentRef: ComponentRef<T>, attributes: Partial<ComponentInputs<T>>) {
const changes: SimpleChanges = {}
- for (const key of objectKeysTyped(attributes)) {
- const previousValue = componentRef.instance[key]
- const newValue = attributes[key]
-
- componentRef.instance[key] = newValue
- changes[key as string] = new SimpleChange(previousValue, newValue, previousValue === undefined)
+ for (const [ key, value ] of Object.entries(attributes)) {
+ componentRef.setInput(key, value)
}
const component = componentRef.instance
if (typeof (component as unknown as OnChanges).ngOnChanges === 'function') {
- (component as unknown as OnChanges).ngOnChanges(changes)
+ ;(component as unknown as OnChanges).ngOnChanges(changes)
}
componentRef.changeDetectorRef.detectChanges()
diff --git a/client/src/app/shared/shared-custom-markup/peertube-custom-tags/button-markup.component.html b/client/src/app/shared/shared-custom-markup/peertube-custom-tags/button-markup.component.html
index 619bb9d8c6..bf83761278 100644
--- a/client/src/app/shared/shared-custom-markup/peertube-custom-tags/button-markup.component.html
+++ b/client/src/app/shared/shared-custom-markup/peertube-custom-tags/button-markup.component.html
@@ -1 +1 @@
-<a [href]="href" [ngClass]="getClasses()" [target]="getTarget()">{{ label }}</a>
+<a [href]="href()" [ngClass]="getClasses()" [target]="getTarget()">{{ label() }}</a>
diff --git a/client/src/app/shared/shared-custom-markup/peertube-custom-tags/button-markup.component.ts b/client/src/app/shared/shared-custom-markup/peertube-custom-tags/button-markup.component.ts
index 0c0765d5f8..800270cddf 100644
--- a/client/src/app/shared/shared-custom-markup/peertube-custom-tags/button-markup.component.ts
+++ b/client/src/app/shared/shared-custom-markup/peertube-custom-tags/button-markup.component.ts
@@ -1,11 +1,11 @@
-import { ChangeDetectionStrategy, Component, Input } from '@angular/core'
+import { ChangeDetectionStrategy, Component, input } from '@angular/core'
import { CustomMarkupComponent } from './shared'
import { NgClass } from '@angular/common'
import { VideoChannel } from '@app/shared/shared-main/channel/video-channel.model'
/*
* Markup component that creates a button
-*/
+ */
@Component({
selector: 'my-button-markup',
@@ -15,22 +15,22 @@ import { VideoChannel } from '@app/shared/shared-main/channel/video-channel.mode
imports: [ NgClass ]
})
export class ButtonMarkupComponent implements CustomMarkupComponent {
- @Input() theme: 'primary' | 'secondary'
- @Input() href: string
- @Input() label: string
- @Input() blankTarget?: boolean
+ readonly theme = input<'primary' | 'secondary'>(undefined)
+ readonly href = input<string>(undefined)
+ readonly label = input<string>(undefined)
+ readonly blankTarget = input<boolean>(undefined)
channel: VideoChannel
loaded: undefined
getTarget () {
- if (this.blankTarget === true) return '_blank'
+ if (this.blankTarget() === true) return '_blank'
return ''
}
getClasses () {
- const additionalClass = this.theme === 'primary'
+ const additionalClass = this.theme() === 'primary'
? 'primary-button'
: 'secondary-button'
diff --git a/client/src/app/shared/shared-custom-markup/peertube-custom-tags/channel-miniature-markup.component.html b/client/src/app/shared/shared-custom-markup/peertube-custom-tags/channel-miniature-markup.component.html
index 395cc85620..6e5ac39a15 100644
--- a/client/src/app/shared/shared-custom-markup/peertube-custom-tags/channel-miniature-markup.component.html
+++ b/client/src/app/shared/shared-custom-markup/peertube-custom-tags/channel-miniature-markup.component.html
@@ -17,10 +17,10 @@
</span>
</div>
- <div *ngIf="displayDescription" class="description-html" [innerHTML]="descriptionHTML"></div>
+ <div *ngIf="displayDescription()" class="description-html" [innerHTML]="descriptionHTML"></div>
</div>
- <div class="video" *ngIf="video && displayLatestVideo">
+ <div class="video" *ngIf="video && displayLatestVideo()">
<div i18n class="video-label">Latest published video</div>
<my-video-miniature-markup [video]="video" [onlyDisplayTitle]="true"></my-video-miniature-markup>
diff --git a/client/src/app/shared/shared-custom-markup/peertube-custom-tags/channel-miniature-markup.component.ts b/client/src/app/shared/shared-custom-markup/peertube-custom-tags/channel-miniature-markup.component.ts
index 65500ec9d3..d63cd96f07 100644
--- a/client/src/app/shared/shared-custom-markup/peertube-custom-tags/channel-miniature-markup.component.ts
+++ b/client/src/app/shared/shared-custom-markup/peertube-custom-tags/channel-miniature-markup.component.ts
@@ -1,6 +1,6 @@
import { from } from 'rxjs'
import { finalize, map, switchMap, tap } from 'rxjs/operators'
-import { ChangeDetectionStrategy, ChangeDetectorRef, Component, EventEmitter, Input, OnInit, Output } from '@angular/core'
+import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit, inject, input, output } from '@angular/core'
import { MarkdownService, Notifier, UserService } from '@app/core'
import { VideoSortField } from '@peertube/peertube-models'
import { CustomMarkupComponent } from './shared'
@@ -15,7 +15,7 @@ import { FindInBulkService } from '@app/shared/shared-search/find-in-bulk.servic
/*
* Markup component that creates a channel miniature only
-*/
+ */
@Component({
selector: 'my-channel-miniature-markup',
@@ -25,37 +25,37 @@ import { FindInBulkService } from '@app/shared/shared-search/find-in-bulk.servic
imports: [ NgIf, ActorAvatarComponent, RouterLink, VideoMiniatureMarkupComponent ]
})
export class ChannelMiniatureMarkupComponent implements CustomMarkupComponent, OnInit {
- @Input() name: string
- @Input() displayLatestVideo: boolean
- @Input() displayDescription: boolean
+ private markdown = inject(MarkdownService)
+ private findInBulk = inject(FindInBulkService)
+ private videoService = inject(VideoService)
+ private userService = inject(UserService)
+ private notifier = inject(Notifier)
+ private cd = inject(ChangeDetectorRef)
- @Output() loaded = new EventEmitter<boolean>()
+ readonly name = input<string>(undefined)
+ readonly displayLatestVideo = input<boolean>(undefined)
+ readonly displayDescription = input<boolean>(undefined)
+
+ readonly loaded = output<boolean>()
channel: VideoChannel
descriptionHTML: string
totalVideos: number
video: Video
- constructor (
- private markdown: MarkdownService,
- private findInBulk: FindInBulkService,
- private videoService: VideoService,
- private userService: UserService,
- private notifier: Notifier,
- private cd: ChangeDetectorRef
- ) { }
-
ngOnInit () {
- this.findInBulk.getChannel(this.name)
+ this.findInBulk.getChannel(this.name())
.pipe(
tap(channel => {
this.channel = channel
}),
- switchMap(() => from(this.markdown.textMarkdownToHTML({
- markdown: this.channel.description,
- withEmoji: true,
- withHtml: true
- }))),
+ switchMap(() =>
+ from(this.markdown.textMarkdownToHTML({
+ markdown: this.channel.description,
+ withEmoji: true,
+ withHtml: true
+ }))
+ ),
tap(html => {
this.descriptionHTML = html
}),
diff --git a/client/src/app/shared/shared-custom-markup/peertube-custom-tags/embed-markup.component.ts b/client/src/app/shared/shared-custom-markup/peertube-custom-tags/embed-markup.component.ts
index 8b46597d73..64ef969c95 100644
--- a/client/src/app/shared/shared-custom-markup/peertube-custom-tags/embed-markup.component.ts
+++ b/client/src/app/shared/shared-custom-markup/peertube-custom-tags/embed-markup.component.ts
@@ -1,5 +1,5 @@
import { environment } from 'src/environments/environment'
-import { Component, ElementRef, Input, OnInit } from '@angular/core'
+import { Component, ElementRef, OnInit, inject, input } from '@angular/core'
import { buildVideoOrPlaylistEmbed } from '@root-helpers/video'
import { buildPlaylistEmbedLink, buildVideoEmbedLink } from '@peertube/peertube-core-utils'
import { CustomMarkupComponent } from './shared'
@@ -10,18 +10,18 @@ import { CustomMarkupComponent } from './shared'
standalone: true
})
export class EmbedMarkupComponent implements CustomMarkupComponent, OnInit {
- @Input() uuid: string
- @Input() type: 'video' | 'playlist' = 'video'
+ private el = inject(ElementRef)
- loaded: undefined
+ readonly uuid = input<string>(undefined)
+ readonly type = input<'video' | 'playlist'>('video')
- constructor (private el: ElementRef) { }
+ loaded: undefined
ngOnInit () {
- const link = this.type === 'video'
- ? buildVideoEmbedLink({ uuid: this.uuid }, environment.originServerUrl)
- : buildPlaylistEmbedLink({ uuid: this.uuid }, environment.originServerUrl)
+ const link = this.type() === 'video'
+ ? buildVideoEmbedLink({ uuid: this.uuid() }, environment.originServerUrl)
+ : buildPlaylistEmbedLink({ uuid: this.uuid() }, environment.originServerUrl)
- this.el.nativeElement.innerHTML = buildVideoOrPlaylistEmbed({ embedUrl: link, embedTitle: this.uuid })
+ this.el.nativeElement.innerHTML = buildVideoOrPlaylistEmbed({ embedUrl: link, embedTitle: this.uuid() })
}
}
diff --git a/client/src/app/shared/shared-custom-markup/peertube-custom-tags/instance-avatar-markup.component.html b/client/src/app/shared/shared-custom-markup/peertube-custom-tags/instance-avatar-markup.component.html
index e0f43913e5..c9b7d5fc31 100644
--- a/client/src/app/shared/shared-custom-markup/peertube-custom-tags/instance-avatar-markup.component.html
+++ b/client/src/app/shared/shared-custom-markup/peertube-custom-tags/instance-avatar-markup.component.html
@@ -1 +1 @@
-<my-actor-avatar *ngIf="actor" [actor]="actor" actorType="account" [size]="size"></my-actor-avatar>
+<my-actor-avatar *ngIf="actor" [actor]="actor" actorType="account" [size]="size()"></my-actor-avatar>
diff --git a/client/src/app/shared/shared-custom-markup/peertube-custom-tags/instance-avatar-markup.component.ts b/client/src/app/shared/shared-custom-markup/peertube-custom-tags/instance-avatar-markup.component.ts
index 49b033a9a4..18dbae0b58 100644
--- a/client/src/app/shared/shared-custom-markup/peertube-custom-tags/instance-avatar-markup.component.ts
+++ b/client/src/app/shared/shared-custom-markup/peertube-custom-tags/instance-avatar-markup.component.ts
@@ -1,4 +1,4 @@
-import { ChangeDetectionStrategy, ChangeDetectorRef, Component, Input, OnInit } from '@angular/core'
+import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit, inject, input } from '@angular/core'
import { CustomMarkupComponent } from './shared'
import { ActorAvatarInput } from '@app/shared/shared-actor-image/actor-avatar.component'
import { ServerService } from '@app/core'
@@ -7,7 +7,7 @@ import { NgIf } from '@angular/common'
/*
* Markup component that creates the img HTML element containing the instance avatar
-*/
+ */
@Component({
selector: 'my-instance-avatar-markup',
@@ -16,16 +16,14 @@ import { NgIf } from '@angular/common'
imports: [ NgIf, ActorAvatarComponent ]
})
export class InstanceAvatarMarkupComponent implements OnInit, CustomMarkupComponent {
- @Input() size: number
+ private cd = inject(ChangeDetectorRef)
+ private server = inject(ServerService)
+
+ readonly size = input<number>(undefined)
actor: ActorAvatarInput
loaded: undefined
- constructor (
- private cd: ChangeDetectorRef,
- private server: ServerService
- ) {}
-
ngOnInit () {
const { instance } = this.server.getHTMLConfig()
diff --git a/client/src/app/shared/shared-custom-markup/peertube-custom-tags/instance-banner-markup.component.ts b/client/src/app/shared/shared-custom-markup/peertube-custom-tags/instance-banner-markup.component.ts
index ddf1165c6b..a969914dd2 100644
--- a/client/src/app/shared/shared-custom-markup/peertube-custom-tags/instance-banner-markup.component.ts
+++ b/client/src/app/shared/shared-custom-markup/peertube-custom-tags/instance-banner-markup.component.ts
@@ -1,12 +1,12 @@
import { NgIf } from '@angular/common'
-import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit } from '@angular/core'
+import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit, inject } from '@angular/core'
import { ServerService } from '@app/core'
import { maxBy } from '@peertube/peertube-core-utils'
import { CustomMarkupComponent } from './shared'
/*
* Markup component that creates the img HTML element containing the instance banner
-*/
+ */
@Component({
selector: 'my-instance-banner-markup',
@@ -15,14 +15,12 @@ import { CustomMarkupComponent } from './shared'
imports: [ NgIf ]
})
export class InstanceBannerMarkupComponent implements OnInit, CustomMarkupComponent {
+ private cd = inject(ChangeDetectorRef)
+ private server = inject(ServerService)
+
instanceBannerUrl: string
loaded: undefined
- constructor (
- private cd: ChangeDetectorRef,
- private server: ServerService
- ) {}
-
ngOnInit () {
const { instance } = this.server.getHTMLConfig()
diff --git a/client/src/app/shared/shared-custom-markup/peertube-custom-tags/playlist-miniature-markup.component.ts b/client/src/app/shared/shared-custom-markup/peertube-custom-tags/playlist-miniature-markup.component.ts
index 3c1940df7e..e019d020e4 100644
--- a/client/src/app/shared/shared-custom-markup/peertube-custom-tags/playlist-miniature-markup.component.ts
+++ b/client/src/app/shared/shared-custom-markup/peertube-custom-tags/playlist-miniature-markup.component.ts
@@ -1,5 +1,5 @@
import { finalize } from 'rxjs/operators'
-import { ChangeDetectionStrategy, ChangeDetectorRef, Component, EventEmitter, Input, OnInit, Output } from '@angular/core'
+import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit, inject, input, output } from '@angular/core'
import { Notifier } from '@app/core'
import { CustomMarkupComponent } from './shared'
import { VideoPlaylistMiniatureComponent } from '../../shared-video-playlist/video-playlist-miniature.component'
@@ -10,7 +10,7 @@ import { VideoPlaylist } from '@app/shared/shared-video-playlist/video-playlist.
/*
* Markup component that creates a playlist miniature only
-*/
+ */
@Component({
selector: 'my-playlist-miniature-markup',
@@ -20,9 +20,13 @@ import { VideoPlaylist } from '@app/shared/shared-video-playlist/video-playlist.
imports: [ NgIf, VideoPlaylistMiniatureComponent ]
})
export class PlaylistMiniatureMarkupComponent implements CustomMarkupComponent, OnInit {
- @Input() uuid: string
+ private findInBulkService = inject(FindInBulkService)
+ private notifier = inject(Notifier)
+ private cd = inject(ChangeDetectorRef)
- @Output() loaded = new EventEmitter<boolean>()
+ readonly uuid = input<string>(undefined)
+
+ readonly loaded = output<boolean>()
playlist: VideoPlaylist
@@ -37,14 +41,8 @@ export class PlaylistMiniatureMarkupComponent implements CustomMarkupComponent,
blacklistInfo: false
}
- constructor (
- private findInBulkService: FindInBulkService,
- private notifier: Notifier,
- private cd: ChangeDetectorRef
- ) { }
-
ngOnInit () {
- this.findInBulkService.getPlaylist(this.uuid)
+ this.findInBulkService.getPlaylist(this.uuid())
.pipe(finalize(() => this.loaded.emit(true)))
.subscribe({
next: playlist => {
diff --git a/client/src/app/shared/shared-custom-markup/peertube-custom-tags/shared/custom-markup.component.ts b/client/src/app/shared/shared-custom-markup/peertube-custom-tags/shared/custom-markup.component.ts
index adfd48c558..6f9a015576 100644
--- a/client/src/app/shared/shared-custom-markup/peertube-custom-tags/shared/custom-markup.component.ts
+++ b/client/src/app/shared/shared-custom-markup/peertube-custom-tags/shared/custom-markup.component.ts
@@ -1,5 +1,5 @@
-import { EventEmitter } from '@angular/core'
+import { OutputEmitterRef } from '@angular/core'
export interface CustomMarkupComponent {
- loaded: EventEmitter<boolean> | undefined
+ loaded: OutputEmitterRef<boolean> | undefined
}
diff --git a/client/src/app/shared/shared-custom-markup/peertube-custom-tags/video-miniature-markup.component.html b/client/src/app/shared/shared-custom-markup/peertube-custom-tags/video-miniature-markup.component.html
index e383e0c75e..c9569b727d 100644
--- a/client/src/app/shared/shared-custom-markup/peertube-custom-tags/video-miniature-markup.component.html
+++ b/client/src/app/shared/shared-custom-markup/peertube-custom-tags/video-miniature-markup.component.html
@@ -1,6 +1,6 @@
<my-video-miniature
- *ngIf="video"
- [video]="video" [user]="getUser()" [displayAsRow]="false"
+ *ngIf="video()"
+ [video]="video()" [user]="getUser()" [displayAsRow]="false"
[displayVideoActions]="true" [displayOptions]="displayOptions"
>
</my-video-miniature>
diff --git a/client/src/app/shared/shared-custom-markup/peertube-custom-tags/video-miniature-markup.component.ts b/client/src/app/shared/shared-custom-markup/peertube-custom-tags/video-miniature-markup.component.ts
index b158f647f2..e7c82581ed 100644
--- a/client/src/app/shared/shared-custom-markup/peertube-custom-tags/video-miniature-markup.component.ts
+++ b/client/src/app/shared/shared-custom-markup/peertube-custom-tags/video-miniature-markup.component.ts
@@ -1,16 +1,16 @@
-import { finalize } from 'rxjs/operators'
-import { ChangeDetectionStrategy, ChangeDetectorRef, Component, EventEmitter, Input, OnInit, Output } from '@angular/core'
-import { AuthService, Notifier } from '@app/core'
-import { objectKeysTyped } from '@peertube/peertube-core-utils'
-import { CustomMarkupComponent } from './shared'
-import { MiniatureDisplayOptions, VideoMiniatureComponent } from '../../shared-video-miniature/video-miniature.component'
import { NgIf } from '@angular/common'
+import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit, inject, input, model, output } from '@angular/core'
+import { AuthService, Notifier } from '@app/core'
import { Video } from '@app/shared/shared-main/video/video.model'
import { FindInBulkService } from '@app/shared/shared-search/find-in-bulk.service'
+import { objectKeysTyped } from '@peertube/peertube-core-utils'
+import { finalize } from 'rxjs/operators'
+import { MiniatureDisplayOptions, VideoMiniatureComponent } from '../../shared-video-miniature/video-miniature.component'
+import { CustomMarkupComponent } from './shared'
/*
* Markup component that creates a video miniature only
-*/
+ */
@Component({
selector: 'my-video-miniature-markup',
@@ -20,11 +20,16 @@ import { FindInBulkService } from '@app/shared/shared-search/find-in-bulk.servic
imports: [ NgIf, VideoMiniatureComponent ]
})
export class VideoMiniatureMarkupComponent implements CustomMarkupComponent, OnInit {
- @Input() uuid: string
- @Input() onlyDisplayTitle: boolean
- @Input() video: Video
+ private auth = inject(AuthService)
+ private findInBulk = inject(FindInBulkService)
+ private notifier = inject(Notifier)
+ private cd = inject(ChangeDetectorRef)
+
+ readonly uuid = input<string>(undefined)
+ readonly onlyDisplayTitle = input<boolean>(undefined)
+ readonly video = model<Video>(undefined)
- @Output() loaded = new EventEmitter<boolean>()
+ readonly loaded = output<boolean>()
displayOptions: MiniatureDisplayOptions = {
date: true,
@@ -37,31 +42,24 @@ export class VideoMiniatureMarkupComponent implements CustomMarkupComponent, OnI
blacklistInfo: false
}
- constructor (
- private auth: AuthService,
- private findInBulk: FindInBulkService,
- private notifier: Notifier,
- private cd: ChangeDetectorRef
- ) { }
-
getUser () {
return this.auth.getUser()
}
ngOnInit () {
- if (this.onlyDisplayTitle) {
+ if (this.onlyDisplayTitle()) {
for (const key of objectKeysTyped(this.displayOptions)) {
this.displayOptions[key] = false
}
}
- if (this.video) return
+ if (this.video()) return
- this.findInBulk.getVideo(this.uuid)
+ this.findInBulk.getVideo(this.uuid())
.pipe(finalize(() => this.loaded.emit(true)))
.subscribe({
next: video => {
- this.video = video
+ this.video.set(video)
this.cd.markForCheck()
},
diff --git a/client/src/app/shared/shared-custom-markup/peertube-custom-tags/videos-list-markup.component.ts b/client/src/app/shared/shared-custom-markup/peertube-custom-tags/videos-list-markup.component.ts
index 83305d9a10..8f2b36bd3b 100644
--- a/client/src/app/shared/shared-custom-markup/peertube-custom-tags/videos-list-markup.component.ts
+++ b/client/src/app/shared/shared-custom-markup/peertube-custom-tags/videos-list-markup.component.ts
@@ -1,5 +1,5 @@
import { NgFor, NgStyle } from '@angular/common'
-import { ChangeDetectionStrategy, ChangeDetectorRef, Component, EventEmitter, Input, OnInit, Output } from '@angular/core'
+import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit, inject, input, output } from '@angular/core'
import { AuthService, Notifier } from '@app/core'
import { Video } from '@app/shared/shared-main/video/video.model'
import { CommonVideoParams, VideoService } from '@app/shared/shared-main/video/video.service'
@@ -12,7 +12,7 @@ import { CustomMarkupComponent } from './shared'
/*
* Markup component list videos depending on criteria
-*/
+ */
@Component({
selector: 'my-videos-list-markup',
@@ -22,19 +22,24 @@ import { CustomMarkupComponent } from './shared'
imports: [ NgStyle, NgFor, VideoMiniatureComponent ]
})
export class VideosListMarkupComponent implements CustomMarkupComponent, OnInit {
- @Input() sort: string
- @Input() categoryOneOf: number[]
- @Input() languageOneOf: string[]
- @Input() count: number
- @Input() onlyDisplayTitle: boolean
- @Input() isLocal: boolean
- @Input() isLive: boolean
- @Input() maxRows: number
- @Input() channelHandle: string
- @Input() accountHandle: string
- @Input() host: string
-
- @Output() loaded = new EventEmitter<boolean>()
+ private auth = inject(AuthService)
+ private videoService = inject(VideoService)
+ private notifier = inject(Notifier)
+ private cd = inject(ChangeDetectorRef)
+
+ readonly sort = input<string>(undefined)
+ readonly categoryOneOf = input<number[]>(undefined)
+ readonly languageOneOf = input<string[]>(undefined)
+ readonly count = input<number>(undefined)
+ readonly onlyDisplayTitle = input<boolean>(undefined)
+ readonly isLocal = input<boolean>(undefined)
+ readonly isLive = input<boolean>(undefined)
+ readonly maxRows = input<number>(undefined)
+ readonly channelHandle = input<string>(undefined)
+ readonly accountHandle = input<string>(undefined)
+ readonly host = input<string>(undefined)
+
+ readonly loaded = output<boolean>()
videos: Video[]
@@ -49,29 +54,22 @@ export class VideosListMarkupComponent implements CustomMarkupComponent, OnInit
blacklistInfo: false
}
- constructor (
- private auth: AuthService,
- private videoService: VideoService,
- private notifier: Notifier,
- private cd: ChangeDetectorRef
- ) { }
-
getUser () {
return this.auth.getUser()
}
limitRowsStyle () {
- if (this.maxRows <= 0) return {}
+ if (this.maxRows() <= 0) return {}
return {
- 'grid-template-rows': `repeat(${this.maxRows}, 1fr)`,
+ 'grid-template-rows': `repeat(${this.maxRows()}, 1fr)`,
'grid-auto-rows': '0', // Set height to 0 for autogenerated grid rows
'overflow-y': 'hidden' // Hide grid items that overflow
}
}
ngOnInit () {
- if (this.onlyDisplayTitle) {
+ if (this.onlyDisplayTitle()) {
for (const key of objectKeysTyped(this.displayOptions)) {
this.displayOptions[key] = false
}
@@ -93,30 +91,32 @@ export class VideosListMarkupComponent implements CustomMarkupComponent, OnInit
const options: CommonVideoParams = {
videoPagination: {
currentPage: 1,
- itemsPerPage: this.count
+ itemsPerPage: this.count()
},
- categoryOneOf: this.categoryOneOf,
- languageOneOf: this.languageOneOf,
- host: this.host,
- isLocal: this.isLocal,
- isLive: this.isLive,
- sort: this.sort as VideoSortField,
+ categoryOneOf: this.categoryOneOf(),
+ languageOneOf: this.languageOneOf(),
+ host: this.host(),
+ isLocal: this.isLocal(),
+ isLive: this.isLive(),
+ sort: this.sort() as VideoSortField,
skipCount: true
}
let obs: Observable<ResultList<Video>>
- if (this.channelHandle) {
+ const channelHandle = this.channelHandle()
+ const accountHandle = this.accountHandle()
+ if (channelHandle) {
obs = this.videoService.getVideoChannelVideos({
...options,
- videoChannel: { nameWithHost: this.channelHandle }
+ videoChannel: { nameWithHost: channelHandle }
})
- } else if (this.accountHandle) {
+ } else if (accountHandle) {
obs = this.videoService.getAccountVideos({
...options,
- account: { nameWithHost: this.accountHandle }
+ account: { nameWithHost: accountHandle }
})
} else {
obs = this.videoService.getVideos(options)
diff --git a/client/src/app/shared/shared-forms/advanced-input-filter.component.html b/client/src/app/shared/shared-forms/advanced-input-filter.component.html
index 0ef062fdd0..7c845890c1 100644
--- a/client/src/app/shared/shared-forms/advanced-input-filter.component.html
+++ b/client/src/app/shared/shared-forms/advanced-input-filter.component.html
@@ -5,7 +5,7 @@
</button>
<div role="menu" ngbDropdownMenu>
- <ng-container *ngFor="let group of filters">
+ <ng-container *ngFor="let group of filters()">
<h6 class="dropdown-header">{{ group.title }}</h6>
<button *ngFor="let filter of group.children" (click)="onFilterClick(filter)" class="dropdown-item">
diff --git a/client/src/app/shared/shared-forms/advanced-input-filter.component.ts b/client/src/app/shared/shared-forms/advanced-input-filter.component.ts
index 7d81fd72b8..385a212228 100644
--- a/client/src/app/shared/shared-forms/advanced-input-filter.component.ts
+++ b/client/src/app/shared/shared-forms/advanced-input-filter.component.ts
@@ -1,7 +1,7 @@
import debug from 'debug'
import { Subject } from 'rxjs'
import { debounceTime, distinctUntilChanged } from 'rxjs/operators'
-import { AfterViewInit, Component, EventEmitter, Input, OnInit, Output } from '@angular/core'
+import { AfterViewInit, Component, OnInit, inject, input, output } from '@angular/core'
import { ActivatedRoute, Params, Router } from '@angular/router'
import { RestService } from '@app/core'
import { FormsModule } from '@angular/forms'
@@ -29,10 +29,14 @@ const debugLogger = debug('peertube:AdvancedInputFilterComponent')
imports: [ NgbDropdown, NgIf, NgbDropdownToggle, NgbDropdownMenu, NgFor, GlobalIconComponent, NgClass, FormsModule ]
})
export class AdvancedInputFilterComponent implements OnInit, AfterViewInit {
- @Input() filters: AdvancedInputFilter[] = []
- @Input() emitOnInit = true
+ private route = inject(ActivatedRoute)
+ private restService = inject(RestService)
+ private router = inject(Router)
- @Output() search = new EventEmitter<string>()
+ readonly filters = input<AdvancedInputFilter[]>([])
+ readonly emitOnInit = input(true)
+
+ readonly search = output<string>()
searchValue: string
@@ -43,12 +47,6 @@ export class AdvancedInputFilterComponent implements OnInit, AfterViewInit {
private viewInitialized = false
private emitSearchAfterViewInit = false
- constructor (
- private route: ActivatedRoute,
- private restService: RestService,
- private router: Router
- ) { }
-
ngOnInit () {
this.initSearchStream()
this.listenToRouteSearchChange()
@@ -58,7 +56,7 @@ export class AdvancedInputFilterComponent implements OnInit, AfterViewInit {
this.viewInitialized = true
// Init after view init to not send an event too early
- if (this.emitOnInit && this.emitSearchAfterViewInit) this.emitSearch()
+ if (this.emitOnInit() && this.emitSearchAfterViewInit) this.emitSearch()
}
onInputSearch (event: Event) {
@@ -70,7 +68,8 @@ export class AdvancedInputFilterComponent implements OnInit, AfterViewInit {
}
hasFilters () {
- return this.filters && this.filters.length !== 0
+ const filters = this.filters()
+ return filters && filters.length !== 0
}
isFilterEnabled (filter: AdvancedInputFilterChild) {
@@ -146,7 +145,7 @@ export class AdvancedInputFilterComponent implements OnInit, AfterViewInit {
const queryParams: Params = {}
if (search) Object.assign(queryParams, { search })
- this.router.navigate([ ], { queryParams })
+ this.router.navigate([], { queryParams })
}
private removeFilterToSearch (search: string, removedFilter: AdvancedInputFilterChild) {
@@ -173,7 +172,7 @@ export class AdvancedInputFilterComponent implements OnInit, AfterViewInit {
this.enabledFilters = new Set()
- for (const group of this.filters) {
+ for (const group of this.filters()) {
for (const filter of group.children) {
const filterTokens = this.restService.tokenizeString(filter.value)
diff --git a/client/src/app/shared/shared-forms/dynamic-form-field.component.html b/client/src/app/shared/shared-forms/dynamic-form-field.component.html
index e5ac7e6fee..37e4bb509c 100644
--- a/client/src/app/shared/shared-forms/dynamic-form-field.component.html
+++ b/client/src/app/shared/shared-forms/dynamic-form-field.component.html
@@ -1,34 +1,34 @@
-<div *ngIf="form" [formGroup]="form">
- <label *ngIf="setting.label && setting.type !== 'input-checkbox'" [attr.for]="setting.name" [innerHTML]="setting.label"></label>
+<div *ngIf="form()" [formGroup]="form()">
+ <label *ngIf="setting().label && setting().type !== 'input-checkbox'" [attr.for]="setting().name" [innerHTML]="setting().label"></label>
<my-peertube-checkbox
- *ngIf="setting.type === 'input-checkbox'"
- [inputName]="setting.name"
- [formControlName]="setting.name"
- [labelInnerHTML]="setting.label"
+ *ngIf="setting().type === 'input-checkbox'"
+ [inputName]="setting().name"
+ [formControlName]="setting().name"
+ [labelInnerHTML]="setting().label"
></my-peertube-checkbox>
- <div *ngIf="setting.descriptionHTML" class="label-small-info" [innerHTML]="setting.descriptionHTML"></div>
+ <div *ngIf="setting().descriptionHTML" class="label-small-info" [innerHTML]="setting().descriptionHTML"></div>
- @switch (setting.type) {
+ @switch (setting().type) {
@case ('input') {
- <input type="text" [id]="setting.name" [formControlName]="setting.name" />
+ <input type="text" [id]="setting().name" [formControlName]="setting().name" />
}
@case ('select') {
<div class="peertube-select-container">
- <select [id]="setting.name" [formControlName]="setting.name" class="form-control">
- <option *ngFor="let option of setting.options" [value]="option.value">{{ option.label }}</option>
+ <select [id]="setting().name" [formControlName]="setting().name" class="form-control">
+ <option *ngFor="let option of setting().options" [value]="option.value">{{ option.label }}</option>
</select>
</div>
}
@case ('input-password') {
- <my-input-text [formError]="formErrors['settings.name']" [formControlName]="setting.name" [inputId]="setting.name"></my-input-text>
+ <my-input-text [formError]="formErrors()['settings.name']" [formControlName]="setting().name" [inputId]="setting().name"></my-input-text>
}
@case ('input-textarea') {
- <textarea type="text" [id]="setting.name" [formControlName]="setting.name"></textarea>
+ <textarea type="text" [id]="setting().name" [formControlName]="setting().name"></textarea>
}
@@ -36,8 +36,8 @@
<my-help helpType="markdownText"></my-help>
<my-markdown-textarea
- markdownType="text" [inputId]="setting.name" [formControlName]="setting.name"
- [formError]="formErrors['settings.name']"
+ markdownType="text" [inputId]="setting().name" [formControlName]="setting().name"
+ [formError]="formErrors()['settings.name']"
></my-markdown-textarea>
}
@@ -45,19 +45,19 @@
<my-help helpType="markdownEnhanced"></my-help>
<my-markdown-textarea
- markdownType="enhanced" [inputId]="setting.name" [formControlName]="setting.name"
- [formError]="formErrors['settings.name']"
+ markdownType="enhanced" [inputId]="setting().name" [formControlName]="setting().name"
+ [formError]="formErrors()['settings.name']"
></my-markdown-textarea>
}
@case ('html') {
- <div [innerHTML]="setting.html"></div>
+ <div [innerHTML]="setting().html"></div>
}
}
- <div *ngIf="hasDedicatedFormError() && formErrors[setting.name]" class="form-error" role="alert">
- {{ formErrors[setting.name] }}
+ <div *ngIf="hasDedicatedFormError() && formErrors()[setting().name]" class="form-error" role="alert">
+ {{ formErrors()[setting().name] }}
</div>
</div>
diff --git a/client/src/app/shared/shared-forms/dynamic-form-field.component.ts b/client/src/app/shared/shared-forms/dynamic-form-field.component.ts
index b2ff94042f..234974490a 100644
--- a/client/src/app/shared/shared-forms/dynamic-form-field.component.ts
+++ b/client/src/app/shared/shared-forms/dynamic-form-field.component.ts
@@ -1,4 +1,4 @@
-import { Component, Input } from '@angular/core'
+import { Component, input } from '@angular/core'
import { FormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms'
import { RegisterClientFormFieldOptions } from '@peertube/peertube-models'
import { MarkdownTextareaComponent } from './markdown-textarea.component'
@@ -22,11 +22,10 @@ import { NgIf, NgFor } from '@angular/common'
MarkdownTextareaComponent
]
})
-
export class DynamicFormFieldComponent {
- @Input() form: FormGroup
- @Input() formErrors: any
- @Input() setting: RegisterClientFormFieldOptions
+ readonly form = input<FormGroup>(undefined)
+ readonly formErrors = input<any>(undefined)
+ readonly setting = input<RegisterClientFormFieldOptions>(undefined)
hasDedicatedFormError () {
const dedicated = new Set<RegisterClientFormFieldOptions['type']>([
@@ -36,6 +35,6 @@ export class DynamicFormFieldComponent {
'input-textarea'
])
- return dedicated.has(this.setting.type)
+ return dedicated.has(this.setting().type)
}
}
diff --git a/client/src/app/shared/shared-forms/form-reactive.service.ts b/client/src/app/shared/shared-forms/form-reactive.service.ts
index 041687edd6..32e334d7e8 100644
--- a/client/src/app/shared/shared-forms/form-reactive.service.ts
+++ b/client/src/app/shared/shared-forms/form-reactive.service.ts
@@ -1,20 +1,17 @@
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { AbstractControl, FormGroup } from '@angular/forms'
import { wait } from '@root-helpers/utils'
import { BuildFormArgument, BuildFormDefaultValues } from '../form-validators/form-validator.model'
import { FormValidatorService } from './form-validator.service'
-export type FormReactiveErrors = { [ id: string ]: string | FormReactiveErrors | FormReactiveErrors[] }
+export type FormReactiveErrors = { [id: string]: string | FormReactiveErrors | FormReactiveErrors[] }
export type FormReactiveValidationMessages = {
- [ id: string ]: { [ name: string ]: string } | FormReactiveValidationMessages | FormReactiveValidationMessages[]
+ [id: string]: { [name: string]: string } | FormReactiveValidationMessages | FormReactiveValidationMessages[]
}
@Injectable()
export class FormReactiveService {
-
- constructor (private formValidatorService: FormValidatorService) {
-
- }
+ private formValidatorService = inject(FormValidatorService)
buildForm (obj: BuildFormArgument, defaultValues: BuildFormDefaultValues = {}) {
const { formErrors, validationMessages, form } = this.formValidatorService.buildForm(obj, defaultValues)
@@ -41,7 +38,7 @@ export class FormReactiveService {
} while (form.status === 'PENDING')
}
- markAllAsDirty (controlsArg: { [ key: string ]: AbstractControl }) {
+ markAllAsDirty (controlsArg: { [key: string]: AbstractControl }) {
const controls = controlsArg
for (const key of Object.keys(controls)) {
diff --git a/client/src/app/shared/shared-forms/form-validator.service.ts b/client/src/app/shared/shared-forms/form-validator.service.ts
index f83ac7454e..645c7aa896 100644
--- a/client/src/app/shared/shared-forms/form-validator.service.ts
+++ b/client/src/app/shared/shared-forms/form-validator.service.ts
@@ -1,4 +1,4 @@
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { AsyncValidatorFn, FormArray, FormBuilder, FormControl, FormGroup, ValidatorFn } from '@angular/forms'
import { objectKeysTyped } from '@peertube/peertube-core-utils'
import { BuildFormArgument, BuildFormDefaultValues } from '../form-validators/form-validator.model'
@@ -6,10 +6,7 @@ import { FormReactiveErrors, FormReactiveValidationMessages } from './form-react
@Injectable()
export class FormValidatorService {
-
- constructor (
- private formBuilder: FormBuilder
- ) {}
+ private formBuilder = inject(FormBuilder)
buildForm (obj: BuildFormArgument, defaultValues: BuildFormDefaultValues = {}) {
const formErrors: FormReactiveErrors = {}
@@ -29,7 +26,7 @@ export class FormValidatorService {
continue
}
- if (field?.MESSAGES) validationMessages[name] = field.MESSAGES as { [ name: string ]: string }
+ if (field?.MESSAGES) validationMessages[name] = field.MESSAGES as { [name: string]: string }
const defaultValue = defaultValues[name] ?? ''
@@ -67,7 +64,7 @@ export class FormValidatorService {
formErrors[name] = ''
- if (field?.MESSAGES) validationMessages[name] = field.MESSAGES as { [ name: string ]: string }
+ if (field?.MESSAGES) validationMessages[name] = field.MESSAGES as { [name: string]: string }
const defaultValue = defaultValues[name] ?? ''
diff --git a/client/src/app/shared/shared-forms/input-switch.component.html b/client/src/app/shared/shared-forms/input-switch.component.html
index 532470289d..5f29f58d14 100644
--- a/client/src/app/shared/shared-forms/input-switch.component.html
+++ b/client/src/app/shared/shared-forms/input-switch.component.html
@@ -1,2 +1,2 @@
-<input type="checkbox" role="switch" [checked]="checked" [name]="inputName" [id]="inputName" (change)="update()" [disabled]="preventUpdate" />
-<label [for]="inputName" class="ms-auto">{{ label }}</label>
+<input type="checkbox" role="switch" [checked]="checked()" [name]="inputName()" [id]="inputName()" (change)="update()" [disabled]="preventUpdate()" />
+<label [for]="inputName()" class="ms-auto">{{ label() }}</label>
diff --git a/client/src/app/shared/shared-forms/input-switch.component.ts b/client/src/app/shared/shared-forms/input-switch.component.ts
index 3b54cd27ec..21310d7444 100644
--- a/client/src/app/shared/shared-forms/input-switch.component.ts
+++ b/client/src/app/shared/shared-forms/input-switch.component.ts
@@ -1,4 +1,4 @@
-import { Component, forwardRef, Input } from '@angular/core'
+import { Component, forwardRef, input, model } from '@angular/core'
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'
@Component({
@@ -15,15 +15,17 @@ import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'
standalone: true
})
export class InputSwitchComponent implements ControlValueAccessor {
- @Input() checked = false
- @Input() inputName: string
- @Input() preventUpdate = false
- @Input() label = $localize`Toggle`
+ readonly checked = model(false)
+ readonly inputName = input<string>(undefined)
+ readonly preventUpdate = input(false)
+ readonly label = input($localize`Toggle`)
- propagateChange = (_: any) => { /* empty */ }
+ propagateChange = (_: any) => {
+ // empty
+ }
writeValue (checked: boolean) {
- this.checked = checked
+ this.checked.set(checked)
}
registerOnChange (fn: (_: any) => void) {
@@ -35,7 +37,7 @@ export class InputSwitchComponent implements ControlValueAccessor {
}
update () {
- this.checked = !this.checked
- this.propagateChange(this.checked)
+ this.checked.set(!this.checked())
+ this.propagateChange(this.checked())
}
}
diff --git a/client/src/app/shared/shared-forms/input-text.component.html b/client/src/app/shared/shared-forms/input-text.component.html
index 7f1ef7449c..1c613bcef1 100644
--- a/client/src/app/shared/shared-forms/input-text.component.html
+++ b/client/src/app/shared/shared-forms/input-text.component.html
@@ -1,23 +1,23 @@
<div class="input-group">
<input
- [id]="inputId" [name]="inputId" [autocomplete]="autocomplete" [value]="value" [placeholder]="placeholder" [tabindex]="tabindex"
- [(ngModel)]="value" (ngModelChange)="update()" [readonly]="readonly"
+ [id]="inputId()" [name]="inputId()" [autocomplete]="autocomplete()" [value]="value()" [placeholder]="placeholder()" [tabindex]="tabindex()"
+ [(ngModel)]="value" (ngModelChange)="update()" [readonly]="readonly()"
#input (click)="input.select()" (input)="update()" (change)="update()" [type]="inputType" class="form-control"
- [ngClass]="{ 'input-error': formError }"
- [attr.aria-label]="ariaLabel"
+ [ngClass]="{ 'input-error': formError() }"
+ [attr.aria-label]="ariaLabel()"
/>
- <button *ngIf="withToggle" (click)="toggle()" type="button" class="btn" [title]="toggleTitle">
- <my-global-icon *ngIf="show" iconName="eye-open"></my-global-icon>
- <my-global-icon *ngIf="!show" iconName="eye-close"></my-global-icon>
+ <button *ngIf="withToggle()" (click)="toggle()" type="button" class="btn" [title]="toggleTitle">
+ <my-global-icon *ngIf="show()" iconName="eye-open"></my-global-icon>
+ <my-global-icon *ngIf="!show()" iconName="eye-close"></my-global-icon>
</button>
<my-copy-button
- *ngIf="withCopy" [value]="input.value" i18n-notification notification="Copied"
+ *ngIf="withCopy()" [value]="input.value" i18n-notification notification="Copied"
[isInputGroup]="true" i18n
>
COPY
</my-copy-button>
</div>
-<div *ngIf="formError" class="form-error" role="alert">{{ formError }}</div>
+<div *ngIf="formError()" class="form-error" role="alert">{{ formError() }}</div>
diff --git a/client/src/app/shared/shared-forms/input-text.component.ts b/client/src/app/shared/shared-forms/input-text.component.ts
index 4b95129e4f..fb42012fee 100644
--- a/client/src/app/shared/shared-forms/input-text.component.ts
+++ b/client/src/app/shared/shared-forms/input-text.component.ts
@@ -1,9 +1,9 @@
-import { AfterViewInit, Component, ElementRef, forwardRef, Input, ViewChild } from '@angular/core'
-import { ControlValueAccessor, NG_VALUE_ACCESSOR, FormsModule } from '@angular/forms'
-import { FormReactiveErrors } from './form-reactive.service'
-import { CopyButtonComponent } from '../shared-main/buttons/copy-button.component'
-import { GlobalIconComponent } from '../shared-icons/global-icon.component'
import { NgClass, NgIf } from '@angular/common'
+import { AfterViewInit, Component, ElementRef, forwardRef, input, model, viewChild } from '@angular/core'
+import { ControlValueAccessor, FormsModule, NG_VALUE_ACCESSOR } from '@angular/forms'
+import { GlobalIconComponent } from '../shared-icons/global-icon.component'
+import { CopyButtonComponent } from '../shared-main/buttons/copy-button.component'
+import { FormReactiveErrors } from './form-reactive.service'
@Component({
selector: 'my-input-text',
@@ -19,48 +19,50 @@ import { NgClass, NgIf } from '@angular/common'
imports: [ FormsModule, NgClass, NgIf, GlobalIconComponent, CopyButtonComponent ]
})
export class InputTextComponent implements ControlValueAccessor, AfterViewInit {
- @ViewChild('input') inputElement: ElementRef
+ readonly inputElement = viewChild<ElementRef>('input')
- @Input({ required: true }) inputId: string
+ readonly inputId = input.required<string>()
- @Input() value = ''
- @Input() autocomplete = 'off'
- @Input() placeholder = ''
- @Input() tabindex = 0
- @Input() withToggle = true
- @Input() withCopy = false
- @Input() readonly = false
- @Input() show = false
- @Input() formError: string | FormReactiveErrors | FormReactiveErrors[]
- @Input() autofocus = false
- @Input() ariaLabel: string
+ readonly value = model('')
+ readonly autocomplete = input('off')
+ readonly placeholder = input('')
+ readonly tabindex = input(0)
+ readonly withToggle = input(true)
+ readonly withCopy = input(false)
+ readonly readonly = input(false)
+ readonly show = model(false)
+ readonly formError = input<string | FormReactiveErrors | FormReactiveErrors[]>(undefined)
+ readonly autofocus = input(false)
+ readonly ariaLabel = input<string>(undefined)
get inputType () {
- return this.show
+ return this.show()
? 'text'
: 'password'
}
get toggleTitle () {
- return this.show
+ return this.show()
? $localize`Hide`
: $localize`Show`
}
ngAfterViewInit () {
- if (this.autofocus !== true) return
+ if (this.autofocus() !== true) return
- this.inputElement.nativeElement.focus({ preventScroll: true })
+ this.inputElement().nativeElement.focus({ preventScroll: true })
}
toggle () {
- this.show = !this.show
+ this.show.set(!this.show())
}
- propagateChange = (_: any) => { /* empty */ }
+ propagateChange = (_: any) => {
+ // empty
+ }
writeValue (value: string) {
- this.value = value
+ this.value.set(value)
}
registerOnChange (fn: (_: any) => void) {
@@ -72,11 +74,11 @@ export class InputTextComponent implements ControlValueAccessor, AfterViewInit {
}
update () {
- this.propagateChange(this.value)
+ this.propagateChange(this.value())
}
focus () {
- const el: HTMLElement = this.inputElement.nativeElement
+ const el: HTMLElement = this.inputElement().nativeElement
el.focus({ preventScroll: true })
}
diff --git a/client/src/app/shared/shared-forms/markdown-textarea.component.html b/client/src/app/shared/shared-forms/markdown-textarea.component.html
index e52b55f8cf..ef92aae682 100644
--- a/client/src/app/shared/shared-forms/markdown-textarea.component.html
+++ b/client/src/app/shared/shared-forms/markdown-textarea.component.html
@@ -2,13 +2,13 @@
<textarea #textarea
[(ngModel)]="content" (ngModelChange)="onModelChange()"
- [ngClass]="{ 'input-error': formError }"
+ [ngClass]="{ 'input-error': formError() }"
[attr.disabled]="disabled || null"
- [id]="inputId" [name]="inputId" [dir]="dir">
+ [id]="inputId()" [name]="inputId()" [dir]="dir()">
</textarea>
<div ngbNav #nav="ngbNav" class="nav-pills nav-preview">
- <ng-container ngbNavItem *ngIf="truncateTo3Lines">
+ <ng-container ngbNavItem *ngIf="truncateTo3Lines()">
<a ngbNavLink i18n>Truncated preview</a>
<ng-template ngbNavContent>
@@ -38,5 +38,5 @@
<div [ngbNavOutlet]="nav"></div>
- <div *ngIf="!isMaximized && formError" class="form-error" role="alert">{{ formError }}</div>
+ <div *ngIf="!isMaximized && formError()" class="form-error" role="alert">{{ formError() }}</div>
</div>
diff --git a/client/src/app/shared/shared-forms/markdown-textarea.component.ts b/client/src/app/shared/shared-forms/markdown-textarea.component.ts
index b8c3a25bd6..43c76df822 100644
--- a/client/src/app/shared/shared-forms/markdown-textarea.component.ts
+++ b/client/src/app/shared/shared-forms/markdown-textarea.component.ts
@@ -1,5 +1,5 @@
import { NgClass, NgIf, ViewportScroller } from '@angular/common'
-import { booleanAttribute, Component, ElementRef, forwardRef, Input, OnDestroy, OnInit, ViewChild } from '@angular/core'
+import { booleanAttribute, Component, ElementRef, forwardRef, inject, input, model, OnDestroy, OnInit, viewChild } from '@angular/core'
import { ControlValueAccessor, FormsModule, NG_VALUE_ACCESSOR } from '@angular/forms'
import { SafeHtml } from '@angular/platform-browser'
import { MarkdownService, ScreenService } from '@app/core'
@@ -35,30 +35,33 @@ import { FormReactiveErrors } from './form-reactive.service'
NgbNavOutlet
]
})
-
export class MarkdownTextareaComponent implements ControlValueAccessor, OnInit, OnDestroy {
- @Input() content = ''
+ private viewportScroller = inject(ViewportScroller)
+ private screenService = inject(ScreenService)
+ private markdownService = inject(MarkdownService)
+
+ readonly content = model('')
- @Input() formError: string | FormReactiveErrors | FormReactiveErrors[]
+ readonly formError = input<string | FormReactiveErrors | FormReactiveErrors[]>(undefined)
- @Input({ transform: booleanAttribute }) truncateTo3Lines: boolean
+ readonly truncateTo3Lines = input<boolean, unknown>(undefined, { transform: booleanAttribute })
- @Input() markdownType: 'text' | 'enhanced' | 'to-unsafe-html' = 'text'
- @Input() customMarkdownRenderer?: (text: string) => Promise<string | HTMLElement>
+ readonly markdownType = input<'text' | 'enhanced' | 'to-unsafe-html'>('text')
+ readonly customMarkdownRenderer = input<(text: string) => Promise<string | HTMLElement>>(undefined)
- @Input() debounceTime = 150
+ readonly debounceTime = input(150)
- @Input() markdownVideo: Video
+ readonly markdownVideo = input<Video>(undefined)
- @Input({ required: true }) inputId: string
+ readonly inputId = input.required<string>()
- @Input() dir: string
+ readonly dir = input<string>(undefined)
- @Input({ transform: booleanAttribute }) withHtml = false
- @Input({ transform: booleanAttribute }) withEmoji = false
+ readonly withHtml = input(false, { transform: booleanAttribute })
+ readonly withEmoji = input(false, { transform: booleanAttribute })
- @ViewChild('textarea') textareaElement: ElementRef
- @ViewChild('previewElement') previewElement: ElementRef
+ readonly textareaElement = viewChild<ElementRef>('textarea')
+ readonly previewElement = viewChild<ElementRef>('previewElement')
previewHTML: SafeHtml | string = ''
@@ -71,33 +74,29 @@ export class MarkdownTextareaComponent implements ControlValueAccessor, OnInit,
private contentChanged = new Subject<string>()
private scrollPosition: [number, number]
- constructor (
- private viewportScroller: ViewportScroller,
- private screenService: ScreenService,
- private markdownService: MarkdownService
- ) { }
-
ngOnInit () {
this.contentChanged
- .pipe(
- debounceTime(this.debounceTime),
- distinctUntilChanged()
- )
- .subscribe(() => this.updatePreviews())
+ .pipe(
+ debounceTime(this.debounceTime()),
+ distinctUntilChanged()
+ )
+ .subscribe(() => this.updatePreviews())
- this.contentChanged.next(this.content)
+ this.contentChanged.next(this.content())
}
ngOnDestroy () {
this.unlockBodyScroll()
}
- propagateChange = (_: any) => { /* empty */ }
+ propagateChange = (_: any) => {
+ // empty
+ }
writeValue (description: string) {
- this.content = description
+ this.content.set(description)
- this.contentChanged.next(this.content)
+ this.contentChanged.next(this.content())
}
registerOnChange (fn: (_: any) => void) {
@@ -109,9 +108,10 @@ export class MarkdownTextareaComponent implements ControlValueAccessor, OnInit,
}
onModelChange () {
- this.propagateChange(this.content)
+ const content = this.content()
+ this.propagateChange(content)
- this.contentChanged.next(this.content)
+ this.contentChanged.next(content)
}
onMaximizeClick () {
@@ -122,7 +122,7 @@ export class MarkdownTextareaComponent implements ControlValueAccessor, OnInit,
// Make sure textarea have the focus
// Except on touchscreens devices, the virtual keyboard may move up and hide the textarea in maximized mode
if (!this.screenService.isInTouchScreen()) {
- this.textareaElement.nativeElement.focus()
+ this.textareaElement().nativeElement.focus()
}
// Make sure the window has no scrollbars
@@ -151,35 +151,39 @@ export class MarkdownTextareaComponent implements ControlValueAccessor, OnInit,
}
private async updatePreviews () {
- if (this.content === null || this.content === undefined) return
+ const content = this.content()
+ if (content === null || content === undefined) return
- this.previewHTML = await this.markdownRender(this.content)
+ this.previewHTML = await this.markdownRender(content)
}
private async markdownRender (text: string) {
let html: string
- if (this.customMarkdownRenderer) {
- const result = await this.customMarkdownRenderer(text)
+ const customMarkdownRenderer = this.customMarkdownRenderer()
+ const markdownType = this.markdownType()
+ if (customMarkdownRenderer) {
+ const result = await customMarkdownRenderer(text)
if (result instanceof HTMLElement) {
- const wrapperElement = this.previewElement.nativeElement as HTMLElement
+ const wrapperElement = this.previewElement().nativeElement as HTMLElement
wrapperElement.innerHTML = ''
wrapperElement.appendChild(result)
return
}
html = result
- } else if (this.markdownType === 'text') {
- html = await this.markdownService.textMarkdownToHTML({ markdown: text, withEmoji: this.withEmoji, withHtml: this.withHtml })
- } else if (this.markdownType === 'enhanced') {
- html = await this.markdownService.enhancedMarkdownToHTML({ markdown: text, withEmoji: this.withEmoji, withHtml: this.withHtml })
- } else if (this.markdownType === 'to-unsafe-html') {
+ } else if (markdownType === 'text') {
+ html = await this.markdownService.textMarkdownToHTML({ markdown: text, withEmoji: this.withEmoji(), withHtml: this.withHtml() })
+ } else if (markdownType === 'enhanced') {
+ html = await this.markdownService.enhancedMarkdownToHTML({ markdown: text, withEmoji: this.withEmoji(), withHtml: this.withHtml() })
+ } else if (markdownType === 'to-unsafe-html') {
html = await this.markdownService.markdownToUnsafeHTML({ markdown: text })
}
- if (this.markdownVideo) {
- html = this.markdownService.processVideoTimestamps(this.markdownVideo.shortUUID, html)
+ const markdownVideo = this.markdownVideo()
+ if (markdownVideo) {
+ html = this.markdownService.processVideoTimestamps(markdownVideo.shortUUID, html)
}
return html
diff --git a/client/src/app/shared/shared-forms/peertube-checkbox.component.html b/client/src/app/shared/shared-forms/peertube-checkbox.component.html
index 62d17e8015..cd10e21262 100644
--- a/client/src/app/shared/shared-forms/peertube-checkbox.component.html
+++ b/client/src/app/shared/shared-forms/peertube-checkbox.component.html
@@ -5,15 +5,15 @@
type="checkbox"
[(ngModel)]="checked"
(ngModelChange)="onModelChange()"
- [id]="inputName"
- [disabled]="disabled"
- [attr.aria-describedby]="inputName + '-description'"
+ [id]="inputName()"
+ [disabled]="disabled()"
+ [attr.aria-describedby]="inputName() + '-description'"
/>
<span></span>
- <span *ngIf="labelText">{{ labelText }}</span>
+ <span *ngIf="labelText()">{{ labelText() }}</span>
<span
- *ngIf="!labelText && labelInnerHTML"
- [innerHTML]="labelInnerHTML"
+ *ngIf="!labelText() && labelInnerHTML()"
+ [innerHTML]="labelInnerHTML()"
></span>
<span *ngIf="labelTemplate">
@@ -23,7 +23,7 @@
<my-help
*ngIf="helpTemplate"
- [tooltipPlacement]="helpPlacement"
+ [tooltipPlacement]="helpPlacement()"
helpType="custom"
>
<ng-template ptTemplate="customHtml">
@@ -31,11 +31,11 @@
</ng-template>
</my-help>
- <div *ngIf="recommended" class="ms-2 pt-badge badge-secondary" i18n>Recommended</div>
+ <div *ngIf="recommended()" class="ms-2 pt-badge badge-secondary" i18n>Recommended</div>
</div>
<div class="d-flex flex-column extra-container ms-4">
- <div class="wrapper form-group-description" [id]="inputName + '-description'">
+ <div class="wrapper form-group-description" [id]="inputName() + '-description'">
<ng-content select="description"></ng-content>
</div>
diff --git a/client/src/app/shared/shared-forms/peertube-checkbox.component.ts b/client/src/app/shared/shared-forms/peertube-checkbox.component.ts
index b0ce620371..1fea342a00 100644
--- a/client/src/app/shared/shared-forms/peertube-checkbox.component.ts
+++ b/client/src/app/shared/shared-forms/peertube-checkbox.component.ts
@@ -1,4 +1,4 @@
-import { AfterContentInit, Component, ContentChildren, forwardRef, Input, QueryList, TemplateRef } from '@angular/core'
+import { AfterContentInit, Component, forwardRef, TemplateRef, input, model, contentChildren } from '@angular/core'
import { ControlValueAccessor, NG_VALUE_ACCESSOR, FormsModule } from '@angular/forms'
import { HelpComponent } from '../shared-main/buttons/help.component'
import { NgIf, NgTemplateOutlet } from '@angular/common'
@@ -18,37 +18,39 @@ import { PeerTubeTemplateDirective } from '../shared-main/common/peertube-templa
imports: [ FormsModule, NgIf, NgTemplateOutlet, HelpComponent, PeerTubeTemplateDirective ]
})
export class PeertubeCheckboxComponent implements ControlValueAccessor, AfterContentInit {
- @Input() checked = false
- @Input() inputName: string
- @Input() labelText: string
- @Input() labelInnerHTML: string
- @Input() helpPlacement = 'top auto'
- @Input() disabled = false
- @Input() recommended = false
+ readonly checked = model(false)
+ readonly inputName = input<string>(undefined)
+ readonly labelText = input<string>(undefined)
+ readonly labelInnerHTML = input<string>(undefined)
+ readonly helpPlacement = input('top auto')
+ readonly disabled = model(false)
+ readonly recommended = input(false)
describedby: string
- @ContentChildren(PeerTubeTemplateDirective) templates: QueryList<PeerTubeTemplateDirective<'label' | 'help'>>
+ readonly templates = contentChildren(PeerTubeTemplateDirective)
labelTemplate: TemplateRef<any>
helpTemplate: TemplateRef<any>
ngAfterContentInit () {
{
- const t = this.templates.find(t => t.name === 'label')
+ const t = this.templates().find(t => t.name() === 'label')
if (t) this.labelTemplate = t.template
}
{
- const t = this.templates.find(t => t.name === 'help')
+ const t = this.templates().find(t => t.name() === 'help')
if (t) this.helpTemplate = t.template
}
}
- propagateChange = (_: any) => { /* empty */ }
+ propagateChange = (_: any) => {
+ // empty
+ }
writeValue (checked: boolean) {
- this.checked = checked
+ this.checked.set(checked)
}
registerOnChange (fn: (_: any) => void) {
@@ -60,10 +62,10 @@ export class PeertubeCheckboxComponent implements ControlValueAccessor, AfterCon
}
onModelChange () {
- this.propagateChange(this.checked)
+ this.propagateChange(this.checked())
}
setDisabledState (isDisabled: boolean) {
- this.disabled = isDisabled
+ this.disabled.set(isDisabled)
}
}
diff --git a/client/src/app/shared/shared-forms/preview-upload.component.html b/client/src/app/shared/shared-forms/preview-upload.component.html
index 8fa1e7e4ca..302051940f 100644
--- a/client/src/app/shared/shared-forms/preview-upload.component.html
+++ b/client/src/app/shared/shared-forms/preview-upload.component.html
@@ -1,11 +1,11 @@
<div class="root">
<div class="preview-container">
<my-reactive-file
- [inputName]="inputName" [inputLabel]="inputLabel" [extensions]="videoImageExtensions" [maxFileSize]="maxVideoImageSize" placement="right"
+ [inputName]="inputName()" [inputLabel]="inputLabel()" [extensions]="videoImageExtensions" [maxFileSize]="maxVideoImageSize" placement="right"
icon="edit" (fileChanged)="onFileChanged($event)" [buttonTooltip]="getReactiveFileButtonTooltip()" theme="primary"
></my-reactive-file>
- <img *ngIf="imageSrc" [ngStyle]="{ width: previewWidth, height: previewHeight }" [src]="imageSrc" class="preview" alt="Preview" i18n-alt />
- <div *ngIf="!imageSrc" [ngStyle]="{ width: previewWidth, height: previewHeight }" class="preview no-image"></div>
+ <img *ngIf="imageSrc" [ngStyle]="{ width: previewWidth(), height: previewHeight() }" [src]="imageSrc" class="preview" alt="Preview" i18n-alt />
+ <div *ngIf="!imageSrc" [ngStyle]="{ width: previewWidth(), height: previewHeight() }" class="preview no-image"></div>
</div>
</div>
diff --git a/client/src/app/shared/shared-forms/preview-upload.component.ts b/client/src/app/shared/shared-forms/preview-upload.component.ts
index 1410d7a7c2..a3e83bd1da 100644
--- a/client/src/app/shared/shared-forms/preview-upload.component.ts
+++ b/client/src/app/shared/shared-forms/preview-upload.component.ts
@@ -1,4 +1,4 @@
-import { Component, forwardRef, Input, OnInit } from '@angular/core'
+import { Component, forwardRef, OnInit, inject, input } from '@angular/core'
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'
import { ServerService } from '@app/core'
import { imageToDataURL } from '@root-helpers/images'
@@ -21,10 +21,12 @@ import { BytesPipe } from '../shared-main/common/bytes.pipe'
imports: [ ReactiveFileComponent, NgIf, NgStyle ]
})
export class PreviewUploadComponent implements OnInit, ControlValueAccessor {
- @Input() inputLabel: string
- @Input() inputName: string
- @Input() previewWidth: string
- @Input() previewHeight: string
+ private serverService = inject(ServerService)
+
+ readonly inputLabel = input<string>(undefined)
+ readonly inputName = input<string>(undefined)
+ readonly previewWidth = input<string>(undefined)
+ readonly previewHeight = input<string>(undefined)
imageSrc: string
allowedExtensionsMessage = ''
@@ -34,9 +36,7 @@ export class PreviewUploadComponent implements OnInit, ControlValueAccessor {
private bytesPipe: BytesPipe
private file: Blob
- constructor (
- private serverService: ServerService
- ) {
+ constructor () {
this.bytesPipe = new BytesPipe()
this.maxSizeText = $localize`max size`
}
@@ -70,7 +70,9 @@ export class PreviewUploadComponent implements OnInit, ControlValueAccessor {
this.updatePreview()
}
- propagateChange = (_: any) => { /* empty */ }
+ propagateChange = (_: any) => {
+ // empty
+ }
writeValue (file: any) {
this.file = file
diff --git a/client/src/app/shared/shared-forms/reactive-file.component.html b/client/src/app/shared/shared-forms/reactive-file.component.html
index 33bb88f1f2..5db05b0caf 100644
--- a/client/src/app/shared/shared-forms/reactive-file.component.html
+++ b/client/src/app/shared/shared-forms/reactive-file.component.html
@@ -1,19 +1,19 @@
<div class="root">
- <div class="button-file" [ngClass]="classes" [ngbTooltip]="buttonTooltip">
- <my-global-icon *ngIf="icon" [iconName]="icon"></my-global-icon>
+ <div class="button-file" [ngClass]="classes" [ngbTooltip]="buttonTooltip()">
+ <my-global-icon *ngIf="icon()" [iconName]="icon()"></my-global-icon>
- <span>{{ inputLabel }}</span>
+ <span>{{ inputLabel() }}</span>
<input
type="file"
- [name]="inputName" [id]="inputName" [accept]="extensions"
+ [name]="inputName()" [id]="inputName()" [accept]="extensions()"
(change)="fileChange($event)" [(ngModel)]="fileInputValue"
/>
</div>
- <div class="filename" *ngIf="displayFilename === true && filename">{{ filename }}</div>
+ <div class="filename" *ngIf="displayFilename() === true && filename">{{ filename }}</div>
- <button *ngIf="displayReset && filename" i18n class="reset-button reset-button-small ms-2" (click)="reset()">
+ <button *ngIf="displayReset() && filename" i18n class="reset-button reset-button-small ms-2" (click)="reset()">
Reset
</button>
</div>
diff --git a/client/src/app/shared/shared-forms/reactive-file.component.ts b/client/src/app/shared/shared-forms/reactive-file.component.ts
index 4ba0124980..43fe1866ce 100644
--- a/client/src/app/shared/shared-forms/reactive-file.component.ts
+++ b/client/src/app/shared/shared-forms/reactive-file.component.ts
@@ -1,4 +1,4 @@
-import { Component, EventEmitter, forwardRef, Input, OnChanges, OnInit, Output } from '@angular/core'
+import { Component, forwardRef, OnChanges, OnInit, inject, input, output } from '@angular/core'
import { ControlValueAccessor, NG_VALUE_ACCESSOR, FormsModule } from '@angular/forms'
import { Notifier } from '@app/core'
import { GlobalIconName } from '@app/shared/shared-icons/global-icon.component'
@@ -20,19 +20,21 @@ import { NgClass, NgIf } from '@angular/common'
imports: [ NgClass, NgbTooltip, NgIf, GlobalIconComponent, FormsModule ]
})
export class ReactiveFileComponent implements OnInit, OnChanges, ControlValueAccessor {
- @Input() theme: 'primary' | 'secondary' = 'secondary'
- @Input() inputLabel: string
- @Input() inputName: string
- @Input() extensions: string[] = []
- @Input() maxFileSize: number
+ private notifier = inject(Notifier)
- @Input() displayFilename = false
- @Input() displayReset = false
+ readonly theme = input<'primary' | 'secondary'>('secondary')
+ readonly inputLabel = input<string>(undefined)
+ readonly inputName = input<string>(undefined)
+ readonly extensions = input<string[]>([])
+ readonly maxFileSize = input<number>(undefined)
- @Input() icon: GlobalIconName
- @Input() buttonTooltip: string
+ readonly displayFilename = input(false)
+ readonly displayReset = input(false)
- @Output() fileChanged = new EventEmitter<Blob>()
+ readonly icon = input<GlobalIconName>(undefined)
+ readonly buttonTooltip = input<string>(undefined)
+
+ readonly fileChanged = output<Blob>()
classes: { [id: string]: boolean } = {}
allowedExtensionsMessage = ''
@@ -40,8 +42,6 @@ export class ReactiveFileComponent implements OnInit, OnChanges, ControlValueAcc
private file: File
- constructor (private notifier: Notifier) { }
-
get filename () {
if (!this.file) return ''
@@ -49,7 +49,7 @@ export class ReactiveFileComponent implements OnInit, OnChanges, ControlValueAcc
}
ngOnInit () {
- this.allowedExtensionsMessage = this.extensions.join(', ')
+ this.allowedExtensionsMessage = this.extensions().join(', ')
this.buildClasses()
}
@@ -60,9 +60,9 @@ export class ReactiveFileComponent implements OnInit, OnChanges, ControlValueAcc
buildClasses () {
this.classes = {
- 'with-icon': !!this.icon,
- 'primary-button': this.theme === 'primary',
- 'secondary-button': this.theme === 'secondary'
+ 'with-icon': !!this.icon(),
+ 'primary-button': this.theme() === 'primary',
+ 'secondary-button': this.theme() === 'secondary'
}
}
@@ -70,13 +70,13 @@ export class ReactiveFileComponent implements OnInit, OnChanges, ControlValueAcc
if (event.target.files?.length) {
const [ file ] = event.target.files
- if (file.size > this.maxFileSize) {
+ if (file.size > this.maxFileSize()) {
this.notifier.error($localize`This file is too large.`)
return
}
const extension = '.' + file.name.split('.').pop()
- if (this.extensions.includes(extension.toLowerCase()) === false) {
+ if (this.extensions().includes(extension.toLowerCase()) === false) {
const message = $localize`PeerTube cannot handle this kind of file. Accepted extensions are ${this.allowedExtensionsMessage}.`
this.notifier.error(message)
@@ -96,7 +96,9 @@ export class ReactiveFileComponent implements OnInit, OnChanges, ControlValueAcc
this.fileChanged.emit(undefined)
}
- propagateChange = (_: any) => { /* empty */ }
+ propagateChange = (_: any) => {
+ // empty
+ }
writeValue (file: any) {
this.file = file
diff --git a/client/src/app/shared/shared-forms/select/select-categories.component.ts b/client/src/app/shared/shared-forms/select/select-categories.component.ts
index 585a76c41f..abf8a3e442 100644
--- a/client/src/app/shared/shared-forms/select/select-categories.component.ts
+++ b/client/src/app/shared/shared-forms/select/select-categories.component.ts
@@ -1,4 +1,4 @@
-import { Component, forwardRef, Input, OnInit } from '@angular/core'
+import { Component, forwardRef, OnInit, inject, input } from '@angular/core'
import { ControlValueAccessor, FormsModule, NG_VALUE_ACCESSOR } from '@angular/forms'
import { ServerService } from '@app/core'
import { SelectOptionsItem } from '../../../../types/select-options-item.model'
@@ -10,7 +10,7 @@ import { NgIf } from '@angular/common'
template: `
<my-select-checkbox-default-all
*ngIf="availableCategories"
- [inputId]="inputId"
+ [inputId]="inputId()"
[(ngModel)]="selectedCategories"
(ngModelChange)="onModelChange()"
[availableItems]="availableCategories"
@@ -30,17 +30,13 @@ import { NgIf } from '@angular/common'
imports: [ SelectCheckboxDefaultAllComponent, FormsModule, NgIf ]
})
export class SelectCategoriesComponent implements ControlValueAccessor, OnInit {
- @Input({ required: true }) inputId: string
+ private server = inject(ServerService)
+
+ readonly inputId = input.required<string>()
selectedCategories: string[]
availableCategories: SelectOptionsItem[]
- constructor (
- private server: ServerService
- ) {
-
- }
-
ngOnInit () {
this.server.getVideoCategories()
.subscribe(
@@ -50,7 +46,9 @@ export class SelectCategoriesComponent implements ControlValueAccessor, OnInit {
)
}
- propagateChange = (_: any) => { /* empty */ }
+ propagateChange = (_: any) => {
+ // empty
+ }
writeValue (categories: string[] | number[]) {
this.selectedCategories = categories
diff --git a/client/src/app/shared/shared-forms/select/select-channel.component.ts b/client/src/app/shared/shared-forms/select/select-channel.component.ts
index 866f6df699..2a4914b7e5 100644
--- a/client/src/app/shared/shared-forms/select/select-channel.component.ts
+++ b/client/src/app/shared/shared-forms/select/select-channel.component.ts
@@ -1,5 +1,5 @@
import { CommonModule } from '@angular/common'
-import { Component, forwardRef, Input, OnChanges } from '@angular/core'
+import { Component, forwardRef, OnChanges, input } from '@angular/core'
import { ControlValueAccessor, FormsModule, NG_VALUE_ACCESSOR } from '@angular/forms'
import { VideoChannel } from '@app/shared/shared-main/channel/video-channel.model'
import { DropdownModule } from 'primeng/dropdown'
@@ -10,7 +10,7 @@ import { SelectOptionsComponent } from './select-options.component'
selector: 'my-select-channel',
template: `
<my-select-options
- [inputId]="inputId"
+ [inputId]="inputId()"
[items]="channels"
@@ -30,14 +30,14 @@ import { SelectOptionsComponent } from './select-options.component'
imports: [ DropdownModule, FormsModule, CommonModule, SelectOptionsComponent ]
})
export class SelectChannelComponent implements ControlValueAccessor, OnChanges {
- @Input({ required: true }) inputId: string
- @Input() items: SelectChannelItem[] = []
+ readonly inputId = input.required<string>()
+ readonly items = input<SelectChannelItem[]>([])
channels: SelectOptionsItem[]
selectedId: number
ngOnChanges () {
- this.channels = this.items.map(c => {
+ this.channels = this.items().map(c => {
const avatarPath = c.avatarPath
? c.avatarPath
: VideoChannel.GET_DEFAULT_AVATAR_URL(21)
@@ -46,7 +46,9 @@ export class SelectChannelComponent implements ControlValueAccessor, OnChanges {
})
}
- propagateChange = (_: any) => { /* empty */ }
+ propagateChange = (_: any) => {
+ // empty
+ }
writeValue (id: number | string) {
this.selectedId = typeof id === 'string'
diff --git a/client/src/app/shared/shared-forms/select/select-checkbox-default-all.component.ts b/client/src/app/shared/shared-forms/select/select-checkbox-default-all.component.ts
index dea91b136b..da13402632 100644
--- a/client/src/app/shared/shared-forms/select/select-checkbox-default-all.component.ts
+++ b/client/src/app/shared/shared-forms/select/select-checkbox-default-all.component.ts
@@ -1,4 +1,4 @@
-import { booleanAttribute, Component, forwardRef, Input } from '@angular/core'
+import { booleanAttribute, Component, forwardRef, inject, input } from '@angular/core'
import { ControlValueAccessor, FormsModule, NG_VALUE_ACCESSOR } from '@angular/forms'
import { Notifier } from '@app/core'
import { formatICU } from '@app/helpers'
@@ -11,15 +11,15 @@ import { SelectCheckboxComponent } from './select-checkbox.component'
<my-select-checkbox
[(ngModel)]="selectedItems"
(ngModelChange)="onModelChange()"
- [availableItems]="availableItems"
- [placeholder]="placeholder"
- [inputId]="inputId"
+ [availableItems]="availableItems()"
+ [placeholder]="placeholder()"
+ [inputId]="inputId()"
[selectedItemsLabel]="selectedItemsLabel"
showClear="false"
- [virtualScroll]="virtualScroll"
+ [virtualScroll]="virtualScroll()"
(panelHide)="onPanelHide()"
>
@@ -34,26 +34,26 @@ import { SelectCheckboxComponent } from './select-checkbox.component'
imports: [ SelectCheckboxComponent, FormsModule ]
})
export class SelectCheckboxDefaultAllComponent implements ControlValueAccessor {
- @Input({ required: true }) inputId: string
- @Input() availableItems: SelectOptionsItem[] = []
+ private notifier = inject(Notifier)
- @Input() placeholder: string
- @Input() maxIndividualItems: number
+ readonly inputId = input.required<string>()
+ readonly availableItems = input<SelectOptionsItem[]>([])
- @Input() allSelectedLabel: string
- @Input() selectedLabel: string
+ readonly placeholder = input<string>(undefined)
+ readonly maxIndividualItems = input<number>(undefined)
- @Input({ transform: booleanAttribute }) virtualScroll = false
+ readonly allSelectedLabel = input<string>(undefined)
+ readonly selectedLabel = input<string>(undefined)
+
+ readonly virtualScroll = input(false, { transform: booleanAttribute })
selectedItemsLabel: string
selectedItems: string[]
- constructor (private notifier: Notifier) {
-
+ propagateChange = (_: any) => {
+ // empty
}
- propagateChange = (_: any) => { /* empty */ }
-
writeValue (items: string[]) {
if (items) this.selectedItems = items
else this.selectAll()
@@ -85,12 +85,13 @@ export class SelectCheckboxDefaultAllComponent implements ControlValueAccessor {
}
private isMaxItemsValid () {
- if (!this.maxIndividualItems) return true
+ const maxIndividualItems = this.maxIndividualItems()
+ if (!maxIndividualItems) return true
const outputItems = this.buildOutputItems()
if (!outputItems) return true
- if (outputItems.length >= this.maxIndividualItems) return false
+ if (outputItems.length >= maxIndividualItems) return false
return true
}
@@ -100,7 +101,7 @@ export class SelectCheckboxDefaultAllComponent implements ControlValueAccessor {
this.notifier.error(
formatICU(
$localize`You can't select more than {maxItems, plural, =1 {1 item} other {{maxItems} items}}`,
- { maxItems: this.maxIndividualItems }
+ { maxItems: this.maxIndividualItems() }
)
)
@@ -109,16 +110,17 @@ export class SelectCheckboxDefaultAllComponent implements ControlValueAccessor {
}
private selectAll () {
- this.selectedItems = this.availableItems.map(i => i.id + '')
+ this.selectedItems = this.availableItems().map(i => i.id + '')
this.updateLabel()
}
private updateLabel () {
- if (this.selectedItems && this.availableItems && this.selectedItems.length === this.availableItems.length) {
- this.selectedItemsLabel = this.allSelectedLabel
+ const availableItems = this.availableItems()
+ if (this.selectedItems && availableItems && this.selectedItems.length === availableItems.length) {
+ this.selectedItemsLabel = this.allSelectedLabel()
} else {
- this.selectedItemsLabel = this.selectedLabel
+ this.selectedItemsLabel = this.selectedLabel()
}
}
@@ -126,7 +128,7 @@ export class SelectCheckboxDefaultAllComponent implements ControlValueAccessor {
if (!Array.isArray(this.selectedItems)) return undefined
// null means "All"
- if (this.selectedItems.length === 0 || this.selectedItems.length === this.availableItems.length) {
+ if (this.selectedItems.length === 0 || this.selectedItems.length === this.availableItems().length) {
return null
}
diff --git a/client/src/app/shared/shared-forms/select/select-checkbox.component.html b/client/src/app/shared/shared-forms/select/select-checkbox.component.html
index d5a0f72191..115c3870aa 100644
--- a/client/src/app/shared/shared-forms/select/select-checkbox.component.html
+++ b/client/src/app/shared/shared-forms/select/select-checkbox.component.html
@@ -1,21 +1,21 @@
<p-multiSelect
- [inputId]="inputId"
+ [inputId]="inputId()"
- [options]="availableItems"
+ [options]="availableItems()"
[(ngModel)]="selectedItems"
(ngModelChange)="onModelChange()"
- [placeholder]="placeholder"
+ [placeholder]="placeholder()"
- [showClear]="showClear"
+ [showClear]="showClear()"
optionValue="id"
- [selectedItemsLabel]="selectedItemsLabel"
- [selectionLimit]="selectionLimit"
+ [selectedItemsLabel]="selectedItemsLabel()"
+ [selectionLimit]="selectionLimit()"
- [virtualScroll]="virtualScroll"
- [virtualScrollItemSize]="virtualScrollItemSize"
+ [virtualScroll]="virtualScroll()"
+ [virtualScrollItemSize]="virtualScrollItemSize()"
(onPanelHide)="panelHide.emit()"
>
diff --git a/client/src/app/shared/shared-forms/select/select-checkbox.component.ts b/client/src/app/shared/shared-forms/select/select-checkbox.component.ts
index 4d52a49b93..c3409b77df 100644
--- a/client/src/app/shared/shared-forms/select/select-checkbox.component.ts
+++ b/client/src/app/shared/shared-forms/select/select-checkbox.component.ts
@@ -1,5 +1,5 @@
import { CommonModule } from '@angular/common'
-import { booleanAttribute, Component, EventEmitter, forwardRef, Input, numberAttribute, Output } from '@angular/core'
+import { booleanAttribute, Component, forwardRef, input, model, numberAttribute, output } from '@angular/core'
import { ControlValueAccessor, FormsModule, NG_VALUE_ACCESSOR } from '@angular/forms'
import { MultiSelectModule } from 'primeng/multiselect'
import { SelectOptionsItem } from '../../../../types/select-options-item.model'
@@ -17,32 +17,34 @@ import { SelectOptionsItem } from '../../../../types/select-options-item.model'
imports: [ MultiSelectModule, FormsModule, CommonModule ]
})
export class SelectCheckboxComponent implements ControlValueAccessor {
- @Input({ required: true }) inputId: string
+ readonly inputId = input.required<string>()
- @Input() availableItems: SelectOptionsItem[] = []
- @Input() selectedItems: string[] = []
+ readonly availableItems = input<SelectOptionsItem[]>([])
+ readonly selectedItems = model<string[]>([])
- @Input() selectableGroup: boolean
- @Input() selectableGroupAsModel: boolean
- @Input() placeholder: string
+ readonly selectableGroup = input<boolean>(undefined)
+ readonly selectableGroupAsModel = input<boolean>(undefined)
+ readonly placeholder = input<string>(undefined)
- @Input() selectionLimit: number
+ readonly selectionLimit = input<number>(undefined)
- @Input() selectedItemsLabel: string
+ readonly selectedItemsLabel = input<string>(undefined)
- @Input({ transform: booleanAttribute }) virtualScroll = false
- @Input({ transform: numberAttribute }) virtualScrollItemSize = 33
+ readonly virtualScroll = input(false, { transform: booleanAttribute })
+ readonly virtualScrollItemSize = input(33, { transform: numberAttribute })
- @Input({ transform: booleanAttribute }) showClear: boolean
+ readonly showClear = input<boolean, unknown>(undefined, { transform: booleanAttribute })
- @Output() panelHide = new EventEmitter()
+ readonly panelHide = output()
disabled = false
- propagateChange = (_: any) => { /* empty */ }
+ propagateChange = (_: any) => {
+ // empty
+ }
writeValue (items: string[]) {
- this.selectedItems = items
+ this.selectedItems.set(items)
}
registerOnChange (fn: (_: any) => void) {
@@ -54,7 +56,7 @@ export class SelectCheckboxComponent implements ControlValueAccessor {
}
onModelChange () {
- this.propagateChange(this.selectedItems)
+ this.propagateChange(this.selectedItems())
}
setDisabledState (isDisabled: boolean) {
diff --git a/client/src/app/shared/shared-forms/select/select-custom-value.component.html b/client/src/app/shared/shared-forms/select/select-custom-value.component.html
index f4db19141e..e8b8048f56 100644
--- a/client/src/app/shared/shared-forms/select/select-custom-value.component.html
+++ b/client/src/app/shared/shared-forms/select/select-custom-value.component.html
@@ -2,7 +2,7 @@
<my-select-options
class="flex-grow-1"
- [inputId]="inputId"
+ [inputId]="inputId()"
[disabled]="disabled"
[items]="itemsWithCustom"
@@ -12,10 +12,10 @@
@if (isCustomValue()) {
<input
- [attr.aria-labelledby]="labelId" [(ngModel)]="customValue" (ngModelChange)="onModelChange()"
- [type]="inputType" class="ms-2 form-control pt-input-text"
+ [attr.aria-labelledby]="labelId()" [(ngModel)]="customValue" (ngModelChange)="onModelChange()"
+ [type]="inputType()" class="ms-2 form-control pt-input-text"
/>
- <span *ngIf="inputSuffix" class="ms-1">{{ inputSuffix }}</span>
+ <span *ngIf="inputSuffix()" class="ms-1">{{ inputSuffix() }}</span>
}
</div>
diff --git a/client/src/app/shared/shared-forms/select/select-custom-value.component.ts b/client/src/app/shared/shared-forms/select/select-custom-value.component.ts
index 1203caa38b..edee364e6f 100644
--- a/client/src/app/shared/shared-forms/select/select-custom-value.component.ts
+++ b/client/src/app/shared/shared-forms/select/select-custom-value.component.ts
@@ -1,4 +1,4 @@
-import { Component, forwardRef, Input, OnChanges } from '@angular/core'
+import { Component, forwardRef, OnChanges, input } from '@angular/core'
import { ControlValueAccessor, NG_VALUE_ACCESSOR, FormsModule } from '@angular/forms'
import { SelectOptionsItem } from '../../../../types/select-options-item.model'
import { NgIf } from '@angular/common'
@@ -17,16 +17,16 @@ import { SelectOptionsComponent } from './select-options.component'
imports: [ SelectOptionsComponent, FormsModule, NgIf ]
})
export class SelectCustomValueComponent implements ControlValueAccessor, OnChanges {
- @Input({ required: true }) inputId: string
- @Input({ required: true }) labelId: string
+ readonly inputId = input.required<string>()
+ readonly labelId = input.required<string>()
- @Input() items: SelectOptionsItem[] = []
+ readonly items = input<SelectOptionsItem[]>([])
- @Input() clearable = false
- @Input() searchable = false
+ readonly clearable = input(false)
+ readonly searchable = input(false)
- @Input() inputSuffix: string
- @Input() inputType = 'text'
+ readonly inputSuffix = input<string>(undefined)
+ readonly inputType = input('text')
customValue: number | string = ''
selectedId: number | string
@@ -38,7 +38,9 @@ export class SelectCustomValueComponent implements ControlValueAccessor, OnChang
this.itemsWithCustom = this.getItems()
}
- propagateChange = (_: any) => { /* empty */ }
+ propagateChange = (_: any) => {
+ // empty
+ }
writeValue (id: number | string) {
this.selectedId = id
@@ -66,7 +68,7 @@ export class SelectCustomValueComponent implements ControlValueAccessor, OnChang
}
isSelectedIdInItems () {
- return !!this.items.find(i => i.id === this.selectedId)
+ return !!this.items().find(i => i.id === this.selectedId)
}
getItems () {
@@ -75,7 +77,7 @@ export class SelectCustomValueComponent implements ControlValueAccessor, OnChang
label: $localize`Custom value...`
}
- return this.items.concat([ other ])
+ return this.items().concat([ other ])
}
isCustomValue () {
diff --git a/client/src/app/shared/shared-forms/select/select-languages.component.ts b/client/src/app/shared/shared-forms/select/select-languages.component.ts
index 661eb2e176..462d58a247 100644
--- a/client/src/app/shared/shared-forms/select/select-languages.component.ts
+++ b/client/src/app/shared/shared-forms/select/select-languages.component.ts
@@ -1,5 +1,5 @@
import { NgIf } from '@angular/common'
-import { Component, forwardRef, Input, OnInit } from '@angular/core'
+import { Component, forwardRef, OnInit, inject, input } from '@angular/core'
import { ControlValueAccessor, FormsModule, NG_VALUE_ACCESSOR } from '@angular/forms'
import { ServerService } from '@app/core'
import { SelectOptionsItem } from '../../../../types/select-options-item.model'
@@ -15,9 +15,9 @@ import { SelectCheckboxDefaultAllComponent } from './select-checkbox-default-all
[(ngModel)]="selectedLanguages"
(ngModelChange)="onModelChange()"
- [inputId]="inputId"
+ [inputId]="inputId()"
- [maxIndividualItems]="maxLanguages"
+ [maxIndividualItems]="maxLanguages()"
virtualScroll="true"
virtualScrollItemSize="37"
@@ -38,18 +38,14 @@ import { SelectCheckboxDefaultAllComponent } from './select-checkbox-default-all
imports: [ SelectCheckboxDefaultAllComponent, FormsModule, NgIf ]
})
export class SelectLanguagesComponent implements ControlValueAccessor, OnInit {
- @Input({ required: true }) inputId: string
- @Input() maxLanguages: number
+ private server = inject(ServerService)
+
+ readonly inputId = input.required<string>()
+ readonly maxLanguages = input<number>(undefined)
selectedLanguages: string[]
availableLanguages: SelectOptionsItem[]
- constructor (
- private server: ServerService
- ) {
-
- }
-
ngOnInit () {
this.server.getVideoLanguages()
.subscribe(
@@ -72,7 +68,9 @@ export class SelectLanguagesComponent implements ControlValueAccessor, OnInit {
)
}
- propagateChange = (_: any) => { /* empty */ }
+ propagateChange = (_: any) => {
+ // empty
+ }
writeValue (languages: string[]) {
this.selectedLanguages = languages
diff --git a/client/src/app/shared/shared-forms/select/select-options.component.html b/client/src/app/shared/shared-forms/select/select-options.component.html
index 917d90c714..e07b43be3c 100644
--- a/client/src/app/shared/shared-forms/select/select-options.component.html
+++ b/client/src/app/shared/shared-forms/select/select-options.component.html
@@ -1,24 +1,24 @@
<p-dropdown
- [inputId]="inputId"
+ [inputId]="inputId()"
- [options]="items"
+ [options]="items()"
[(ngModel)]="selectedId"
(ngModelChange)="onModelChange()"
optionValue="id"
- [showClear]="clearable"
+ [showClear]="clearable()"
- [filter]="filter"
+ [filter]="filter()"
filterBy="label"
i18n-filterPlaceholder filterPlaceholder="Search"
i18n-emptyFilterMessage emptyFilterMessage="No results found"
i18n-emptyMessage emptyMessage="No items available"
- [virtualScroll]="virtualScroll"
- [virtualScrollItemSize]="virtualScrollItemSize"
+ [virtualScroll]="virtualScroll()"
+ [virtualScrollItemSize]="virtualScrollItemSize()"
>
<ng-template #itemTemplate let-item let-description="description">
@if (customItemTemplate) {
diff --git a/client/src/app/shared/shared-forms/select/select-options.component.ts b/client/src/app/shared/shared-forms/select/select-options.component.ts
index fff8b68e32..e4d30de33e 100644
--- a/client/src/app/shared/shared-forms/select/select-options.component.ts
+++ b/client/src/app/shared/shared-forms/select/select-options.component.ts
@@ -4,13 +4,13 @@ import {
booleanAttribute,
ChangeDetectorRef,
Component,
- ContentChildren,
forwardRef,
HostListener,
- Input,
numberAttribute,
- QueryList,
- TemplateRef
+ TemplateRef,
+ inject,
+ input,
+ contentChildren
} from '@angular/core'
import { ControlValueAccessor, FormsModule, NG_VALUE_ACCESSOR } from '@angular/forms'
import { PeerTubeTemplateDirective } from '@app/shared/shared-main/common/peertube-template.directive'
@@ -33,17 +33,19 @@ import { SelectOptionsItem } from '../../../../types/select-options-item.model'
imports: [ DropdownModule, FormsModule, CommonModule ]
})
export class SelectOptionsComponent implements AfterContentInit, ControlValueAccessor {
- @Input() items: SelectOptionsItem[] = []
+ private cd = inject(ChangeDetectorRef)
- @Input({ required: true }) inputId: string
+ readonly items = input<SelectOptionsItem[]>([])
- @Input({ transform: booleanAttribute }) clearable = false
- @Input({ transform: booleanAttribute }) filter = false
+ readonly inputId = input.required<string>()
- @Input({ transform: booleanAttribute }) virtualScroll = false
- @Input({ transform: numberAttribute }) virtualScrollItemSize = 39
+ readonly clearable = input(false, { transform: booleanAttribute })
+ readonly filter = input(false, { transform: booleanAttribute })
- @ContentChildren(PeerTubeTemplateDirective) templates: QueryList<PeerTubeTemplateDirective<'item'>>
+ readonly virtualScroll = input(false, { transform: booleanAttribute })
+ readonly virtualScrollItemSize = input(39, { transform: numberAttribute })
+
+ readonly templates = contentChildren(PeerTubeTemplateDirective)
customItemTemplate: TemplateRef<any>
@@ -52,18 +54,16 @@ export class SelectOptionsComponent implements AfterContentInit, ControlValueAcc
wroteValue: number | string
- constructor (private cd: ChangeDetectorRef) {
-
- }
-
ngAfterContentInit () {
{
- const t = this.templates.find(t => t.name === 'item')
+ const t = this.templates().find(t => t.name() === 'item')
if (t) this.customItemTemplate = t.template
}
}
- propagateChange = (_: any) => { /* empty */ }
+ propagateChange = (_: any) => {
+ // empty
+ }
// Allow plugins to update our value
@HostListener('change', [ '$event.target' ])
@@ -106,6 +106,6 @@ export class SelectOptionsComponent implements AfterContentInit, ControlValueAcc
}
getSelectedItem () {
- return this.items.find(i => i.id === this.selectedId)
+ return this.items().find(i => i.id === this.selectedId)
}
}
diff --git a/client/src/app/shared/shared-forms/select/select-tags.component.html b/client/src/app/shared/shared-forms/select/select-tags.component.html
index 6d8dd6d864..e1b1285884 100644
--- a/client/src/app/shared/shared-forms/select/select-tags.component.html
+++ b/client/src/app/shared/shared-forms/select/select-tags.component.html
@@ -1,8 +1,8 @@
<p-chips
[(ngModel)]="selectedItems"
(ngModelChange)="onModelChange()"
- [placeholder]="placeholder"
- [inputId]="inputId"
+ [placeholder]="placeholder()"
+ [inputId]="inputId()"
[allowDuplicate]="false"
[caseSensitiveDuplication]="false"
[separator]="separator"
diff --git a/client/src/app/shared/shared-forms/select/select-tags.component.ts b/client/src/app/shared/shared-forms/select/select-tags.component.ts
index 30d5330cc2..4ccb7a39b5 100644
--- a/client/src/app/shared/shared-forms/select/select-tags.component.ts
+++ b/client/src/app/shared/shared-forms/select/select-tags.component.ts
@@ -1,5 +1,5 @@
import { CommonModule } from '@angular/common'
-import { Component, Input, OnInit, forwardRef } from '@angular/core'
+import { Component, OnInit, forwardRef, input, model } from '@angular/core'
import { ControlValueAccessor, FormsModule, NG_VALUE_ACCESSOR } from '@angular/forms'
import { isMobile } from '@root-helpers/web-browser'
import { ChipsModule } from 'primeng/chips'
@@ -17,10 +17,10 @@ import { ChipsModule } from 'primeng/chips'
imports: [ CommonModule, ChipsModule, FormsModule ]
})
export class SelectTagsComponent implements OnInit, ControlValueAccessor {
- @Input({ required: true }) inputId: string
- @Input() availableItems: string[] = []
- @Input() selectedItems: string[] = []
- @Input() placeholder = $localize`Enter a new tag`
+ readonly inputId = input.required<string>()
+ readonly availableItems = input<string[]>([])
+ readonly selectedItems = model<string[]>([])
+ readonly placeholder = model($localize`Enter a new tag`)
separator: string
@@ -28,14 +28,16 @@ export class SelectTagsComponent implements OnInit, ControlValueAccessor {
// FIXME: workaround for https://github.com/primefaces/primeng/issues/13981
if (isMobile()) {
this.separator = ','
- this.placeholder = $localize`Use a comma (,) to add a tag`
+ this.placeholder.set($localize`Use a comma (,) to add a tag`)
}
}
- propagateChange = (_: any) => { /* empty */ }
+ propagateChange = (_: any) => {
+ // empty
+ }
writeValue (items: string[]) {
- this.selectedItems = items
+ this.selectedItems.set(items)
}
registerOnChange (fn: (_: any) => void) {
@@ -47,6 +49,6 @@ export class SelectTagsComponent implements OnInit, ControlValueAccessor {
}
onModelChange () {
- this.propagateChange(this.selectedItems)
+ this.propagateChange(this.selectedItems())
}
}
diff --git a/client/src/app/shared/shared-forms/textarea-autoresize.directive.ts b/client/src/app/shared/shared-forms/textarea-autoresize.directive.ts
index 5943ad55f6..c38cf4d8a2 100644
--- a/client/src/app/shared/shared-forms/textarea-autoresize.directive.ts
+++ b/client/src/app/shared/shared-forms/textarea-autoresize.directive.ts
@@ -1,15 +1,17 @@
// Thanks: https://github.com/evseevdev/ngx-textarea-autosize
-import { AfterViewInit, Directive, ElementRef, HostBinding, HostListener } from '@angular/core'
+import { AfterViewInit, Directive, ElementRef, HostBinding, HostListener, inject } from '@angular/core'
@Directive({
selector: 'textarea[myAutoResize]',
standalone: true
})
export class TextareaAutoResizeDirective implements AfterViewInit {
- @HostBinding('attr.rows') rows = '1'
- @HostBinding('style.overflow') overflow = 'hidden'
+ private elem = inject(ElementRef)
- constructor (private elem: ElementRef) { }
+ @HostBinding('attr.rows')
+ rows = '1'
+ @HostBinding('style.overflow')
+ overflow = 'hidden'
public ngAfterViewInit () {
this.resize()
diff --git a/client/src/app/shared/shared-forms/timestamp-input.component.html b/client/src/app/shared/shared-forms/timestamp-input.component.html
index b097377a91..88047eab0b 100644
--- a/client/src/app/shared/shared-forms/timestamp-input.component.html
+++ b/client/src/app/shared/shared-forms/timestamp-input.component.html
@@ -1,5 +1,5 @@
<p-inputMask
- [disabled]="disabled" [(ngModel)]="timestampString" (onBlur)="onBlur()"
- [ngClass]="{ 'with-border': enableBorder }"
- [mask]="mask" slotChar="0" (ngModelChange)="onModelChange()" [inputId]="inputName"
+ [disabled]="disabled()" [(ngModel)]="timestampString" (onBlur)="onBlur()"
+ [ngClass]="{ 'with-border': enableBorder() }"
+ [mask]="mask()" slotChar="0" (ngModelChange)="onModelChange()" [inputId]="inputName()"
></p-inputMask>
diff --git a/client/src/app/shared/shared-forms/timestamp-input.component.ts b/client/src/app/shared/shared-forms/timestamp-input.component.ts
index 241443a60b..8c93366b1c 100644
--- a/client/src/app/shared/shared-forms/timestamp-input.component.ts
+++ b/client/src/app/shared/shared-forms/timestamp-input.component.ts
@@ -1,5 +1,5 @@
import { NgClass } from '@angular/common'
-import { booleanAttribute, ChangeDetectorRef, Component, EventEmitter, forwardRef, Input, OnInit, Output } from '@angular/core'
+import { booleanAttribute, ChangeDetectorRef, Component, forwardRef, OnInit, inject, input, model, output } from '@angular/core'
import { ControlValueAccessor, FormsModule, NG_VALUE_ACCESSOR } from '@angular/forms'
import { secondsToTime, timeToInt } from '@peertube/peertube-core-utils'
import { InputMaskModule } from 'primeng/inputmask'
@@ -18,33 +18,35 @@ import { InputMaskModule } from 'primeng/inputmask'
imports: [ InputMaskModule, FormsModule, NgClass ]
})
export class TimestampInputComponent implements ControlValueAccessor, OnInit {
- @Input() maxTimestamp: number
- @Input() timestamp: number
+ private changeDetector = inject(ChangeDetectorRef)
- @Input({ transform: booleanAttribute }) disabled = false
- @Input({ transform: booleanAttribute }) enableBorder = false
+ readonly maxTimestamp = input<number>(undefined)
+ readonly timestamp = model<number>(undefined)
- @Input() inputName: string
- @Input() mask = '99:99:99'
+ readonly disabled = input(false, { transform: booleanAttribute })
+ readonly enableBorder = input(false, { transform: booleanAttribute })
- @Input() formatter = (timestamp: number) => secondsToTime({ seconds: timestamp, format: 'full', symbol: ':' })
- @Input() parser = (timestampString: string) => timeToInt(timestampString)
+ readonly inputName = input<string>(undefined)
+ readonly mask = input('99:99:99')
- @Output() inputBlur = new EventEmitter()
+ readonly formatter = input((timestamp: number) => secondsToTime({ seconds: timestamp, format: 'full', symbol: ':' }))
+ readonly parser = input((timestampString: string) => timeToInt(timestampString))
- timestampString: string
+ readonly inputBlur = output()
- constructor (private changeDetector: ChangeDetectorRef) {}
+ timestampString: string
ngOnInit () {
- this.writeValue(this.timestamp || 0)
+ this.writeValue(this.timestamp() || 0)
}
- propagateChange = (_: any) => { /* empty */ }
+ propagateChange = (_: any) => {
+ // empty
+ }
writeValue (timestamp: number) {
- this.timestamp = timestamp
- this.timestampString = this.formatter(this.timestamp)
+ this.timestamp.set(timestamp)
+ this.timestampString = this.formatter()(this.timestamp())
}
registerOnChange (fn: (_: any) => void) {
@@ -56,18 +58,19 @@ export class TimestampInputComponent implements ControlValueAccessor, OnInit {
}
onModelChange () {
- this.timestamp = this.parser(this.timestampString)
+ this.timestamp.set(this.parser()(this.timestampString))
- this.propagateChange(this.timestamp)
+ this.propagateChange(this.timestamp())
}
onBlur () {
- if (this.maxTimestamp && this.timestamp > this.maxTimestamp) {
- this.writeValue(this.maxTimestamp)
+ const maxTimestamp = this.maxTimestamp()
+ if (maxTimestamp && this.timestamp() > maxTimestamp) {
+ this.writeValue(maxTimestamp)
this.changeDetector.detectChanges()
- this.propagateChange(this.timestamp)
+ this.propagateChange(this.timestamp())
}
this.inputBlur.emit()
diff --git a/client/src/app/shared/shared-icons/global-icon.component.ts b/client/src/app/shared/shared-icons/global-icon.component.ts
index 779a00f834..6779ca25e7 100644
--- a/client/src/app/shared/shared-icons/global-icon.component.ts
+++ b/client/src/app/shared/shared-icons/global-icon.component.ts
@@ -1,4 +1,4 @@
-import { ChangeDetectionStrategy, Component, ElementRef, Input, OnInit } from '@angular/core'
+import { ChangeDetectionStrategy, Component, ElementRef, OnInit, inject, input } from '@angular/core'
import { HooksService } from '@app/core/plugins/hooks.service'
const icons = {
@@ -102,19 +102,17 @@ export type GlobalIconName = keyof typeof icons
standalone: true
})
export class GlobalIconComponent implements OnInit {
- @Input({ required: true }) iconName: GlobalIconName
+ private el = inject(ElementRef)
+ private hooks = inject(HooksService)
- constructor (
- private el: ElementRef,
- private hooks: HooksService
- ) { }
+ readonly iconName = input.required<GlobalIconName>()
async ngOnInit () {
const nativeElement = this.el.nativeElement as HTMLElement
nativeElement.innerHTML = await this.hooks.wrapFun(
this.getSVGContent.bind(this),
- { name: this.iconName },
+ { name: this.iconName() },
'common',
'filter:internal.common.svg-icons.get-content.params',
'filter:internal.common.svg-icons.get-content.result'
diff --git a/client/src/app/shared/shared-instance/feature-boolean.component.html b/client/src/app/shared/shared-instance/feature-boolean.component.html
index 9ae89429be..f84adca262 100644
--- a/client/src/app/shared/shared-instance/feature-boolean.component.html
+++ b/client/src/app/shared/shared-instance/feature-boolean.component.html
@@ -1,4 +1,4 @@
-@if (value === true) {
+@if (value() === true) {
<span class="visually-hidden" i18n>yes</span>
<my-global-icon iconName="tick"></my-global-icon>
} @else {
diff --git a/client/src/app/shared/shared-instance/feature-boolean.component.ts b/client/src/app/shared/shared-instance/feature-boolean.component.ts
index f34d941882..3ff9887cc1 100644
--- a/client/src/app/shared/shared-instance/feature-boolean.component.ts
+++ b/client/src/app/shared/shared-instance/feature-boolean.component.ts
@@ -1,13 +1,12 @@
-import { Component, Input } from '@angular/core'
+import { Component, input } from '@angular/core'
import { GlobalIconComponent } from '../shared-icons/global-icon.component'
-import { NgIf } from '@angular/common'
@Component({
selector: 'my-feature-boolean',
templateUrl: './feature-boolean.component.html',
styleUrls: [ './feature-boolean.component.scss' ],
- imports: [ NgIf, GlobalIconComponent ]
+ imports: [ GlobalIconComponent ]
})
export class FeatureBooleanComponent {
- @Input() value: boolean
+ readonly value = input<boolean>(undefined)
}
diff --git a/client/src/app/shared/shared-instance/instance-about-accordion.component.html b/client/src/app/shared/shared-instance/instance-about-accordion.component.html
index 5d27bc437c..0c25564180 100644
--- a/client/src/app/shared/shared-instance/instance-about-accordion.component.html
+++ b/client/src/app/shared/shared-instance/instance-about-accordion.component.html
@@ -1,9 +1,9 @@
-<h2 *ngIf="displayInstanceName" class="instance-name">{{ about?.instance.name }}</h2>
+<h2 *ngIf="displayInstanceName()" class="instance-name">{{ about?.instance.name }}</h2>
-<div *ngIf="displayInstanceShortDescription" class="instance-short-description ellipsis-multiline-3">{{ about?.instance.shortDescription }}</div>
+<div *ngIf="displayInstanceShortDescription()" class="instance-short-description ellipsis-multiline-3">{{ about?.instance.shortDescription }}</div>
<div ngbAccordion #accordion="ngbAccordion" [closeOthers]="true">
- <div ngbAccordionItem="instance-features" *ngIf="panels.features">
+ <div ngbAccordionItem="instance-features" *ngIf="panels().features">
<div ngbAccordionHeader>
<button ngbAccordionButton>
<my-global-icon iconName="playlists"></my-global-icon>
diff --git a/client/src/app/shared/shared-instance/instance-about-accordion.component.ts b/client/src/app/shared/shared-instance/instance-about-accordion.component.ts
index 29ffe422d4..830ee91a54 100644
--- a/client/src/app/shared/shared-instance/instance-about-accordion.component.ts
+++ b/client/src/app/shared/shared-instance/instance-about-accordion.component.ts
@@ -1,4 +1,4 @@
-import { Component, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core'
+import { Component, OnInit, inject, input, output, viewChild } from '@angular/core'
import { HooksService, Notifier } from '@app/core'
import {
NgbAccordionDirective,
@@ -36,23 +36,27 @@ import { NgIf, NgFor } from '@angular/common'
]
})
export class InstanceAboutAccordionComponent implements OnInit {
- @ViewChild('accordion', { static: true }) accordion: NgbAccordionDirective
+ private instanceService = inject(InstanceService)
+ private notifier = inject(Notifier)
+ private hookService = inject(HooksService)
- @Output() init: EventEmitter<InstanceAboutAccordionComponent> = new EventEmitter<InstanceAboutAccordionComponent>()
+ readonly accordion = viewChild<NgbAccordionDirective>('accordion')
- @Input() displayInstanceName = true
- @Input() displayInstanceShortDescription = true
+ readonly init = output<InstanceAboutAccordionComponent>()
- @Input() pluginScope: PluginClientScope
- @Input() pluginHook: ClientFilterHookName
+ readonly displayInstanceName = input(true)
+ readonly displayInstanceShortDescription = input(true)
- @Input() panels = {
+ readonly pluginScope = input<PluginClientScope>(undefined)
+ readonly pluginHook = input<ClientFilterHookName>(undefined)
+
+ readonly panels = input({
features: true,
administrators: true,
moderation: true,
codeOfConduct: true,
terms: true
- }
+ })
about: About
aboutHtml = {
@@ -64,12 +68,6 @@ export class InstanceAboutAccordionComponent implements OnInit {
pluginPanels: { id: string, title: string, html: string }[] = []
- constructor (
- private instanceService: InstanceService,
- private notifier: Notifier,
- private hookService: HooksService
- ) { }
-
async ngOnInit () {
this.instanceService.getAbout()
.subscribe({
@@ -84,20 +82,20 @@ export class InstanceAboutAccordionComponent implements OnInit {
error: err => this.notifier.error(err.message)
})
- this.pluginPanels = await this.hookService.wrapObject([], this.pluginScope, this.pluginHook)
+ this.pluginPanels = await this.hookService.wrapObject([], this.pluginScope(), this.pluginHook())
}
expandTerms () {
- this.accordion.expand('terms')
+ this.accordion().expand('terms')
}
expandCodeOfConduct () {
- this.accordion.expand('code-of-conduct')
+ this.accordion().expand('code-of-conduct')
}
getAdministratorsPanel () {
if (!this.about) return false
- if (!this.panels.administrators) return false
+ if (!this.panels().administrators) return false
return !!(this.aboutHtml?.administrator || this.about?.instance.maintenanceLifetime || this.about?.instance.businessModel)
}
@@ -107,14 +105,14 @@ export class InstanceAboutAccordionComponent implements OnInit {
}
get moderationPanel () {
- return this.panels.moderation && !!this.aboutHtml.moderationInformation
+ return this.panels().moderation && !!this.aboutHtml.moderationInformation
}
get codeOfConductPanel () {
- return this.panels.codeOfConduct && !!this.aboutHtml.codeOfConduct
+ return this.panels().codeOfConduct && !!this.aboutHtml.codeOfConduct
}
get termsPanel () {
- return this.panels.terms && !!this.aboutHtml.terms
+ return this.panels().terms && !!this.aboutHtml.terms
}
}
diff --git a/client/src/app/shared/shared-instance/instance-banner.component.html b/client/src/app/shared/shared-instance/instance-banner.component.html
index b0121cf2e8..61c1d0acd5 100644
--- a/client/src/app/shared/shared-instance/instance-banner.component.html
+++ b/client/src/app/shared/shared-instance/instance-banner.component.html
@@ -1,3 +1,3 @@
-<div *ngIf="instanceBannerUrl" class="banner" [ngClass]="{ rounded }">
+<div *ngIf="instanceBannerUrl" class="banner" [ngClass]="{ rounded: rounded() }">
<img class="rounded" [src]="instanceBannerUrl" alt="">
</div>
diff --git a/client/src/app/shared/shared-instance/instance-banner.component.ts b/client/src/app/shared/shared-instance/instance-banner.component.ts
index ff36679069..cc89dee5ad 100644
--- a/client/src/app/shared/shared-instance/instance-banner.component.ts
+++ b/client/src/app/shared/shared-instance/instance-banner.component.ts
@@ -1,5 +1,5 @@
import { NgClass, NgIf } from '@angular/common'
-import { Component, Input, OnInit, booleanAttribute } from '@angular/core'
+import { Component, OnInit, booleanAttribute, inject, input } from '@angular/core'
import { ServerService } from '@app/core'
import { maxBy } from '@peertube/peertube-core-utils'
@@ -9,13 +9,11 @@ import { maxBy } from '@peertube/peertube-core-utils'
imports: [ NgIf, NgClass ]
})
export class InstanceBannerComponent implements OnInit {
- @Input({ transform: booleanAttribute }) rounded = false
+ private server = inject(ServerService)
- instanceBannerUrl: string
-
- constructor (private server: ServerService) {
+ readonly rounded = input(false, { transform: booleanAttribute })
- }
+ instanceBannerUrl: string
ngOnInit () {
const { instance } = this.server.getHTMLConfig()
diff --git a/client/src/app/shared/shared-instance/instance-features-table.component.html b/client/src/app/shared/shared-instance/instance-features-table.component.html
index 611abd81f5..7bc073824f 100644
--- a/client/src/app/shared/shared-instance/instance-features-table.component.html
+++ b/client/src/app/shared/shared-instance/instance-features-table.component.html
@@ -1,6 +1,6 @@
-<div *ngIf="serverConfig" class="feature-table">
+<div *ngIf="serverConfig()" class="feature-table">
- <table *ngIf="serverConfig">
+ <table *ngIf="serverConfig()">
<caption i18n>Features found on this instance</caption>
<tr>
<th i18n class="t-label" scope="row">PeerTube version</th>
@@ -30,22 +30,22 @@
<tr>
<th i18n class="t-sub-label" scope="row">Transcoding in multiple resolutions</th>
<td>
- <my-feature-boolean [value]="serverConfig.transcoding.enabledResolutions.length !== 0"></my-feature-boolean>
+ <my-feature-boolean [value]="serverConfig().transcoding.enabledResolutions.length !== 0"></my-feature-boolean>
</td>
</tr>
<tr>
<th i18n class="t-sub-label" scope="row">Automatic transcription</th>
<td>
- <my-feature-boolean [value]="serverConfig.videoTranscription.enabled"></my-feature-boolean>
+ <my-feature-boolean [value]="serverConfig().videoTranscription.enabled"></my-feature-boolean>
</td>
</tr>
<tr>
<th i18n class="t-sub-label" scope="row">Video uploads</th>
<td>
- <span i18n *ngIf="serverConfig.autoBlacklist.videos.ofUsers.enabled">Requires manual validation by moderators</span>
- <span i18n *ngIf="!serverConfig.autoBlacklist.videos.ofUsers.enabled">Automatically published</span>
+ <span i18n *ngIf="serverConfig().autoBlacklist.videos.ofUsers.enabled">Requires manual validation by moderators</span>
+ <span i18n *ngIf="!serverConfig().autoBlacklist.videos.ofUsers.enabled">Automatically published</span>
</td>
</tr>
@@ -76,18 +76,18 @@
<tr>
<th i18n class="t-sub-label" scope="row">Live streaming enabled</th>
<td>
- <my-feature-boolean [value]="serverConfig.live.enabled"></my-feature-boolean>
+ <my-feature-boolean [value]="serverConfig().live.enabled"></my-feature-boolean>
</td>
</tr>
- <tr *ngIf="serverConfig.live.enabled">
+ <tr *ngIf="serverConfig().live.enabled">
<th i18n class="t-sub-label" scope="row">Transcode live video in multiple resolutions</th>
<td>
- <my-feature-boolean [value]="serverConfig.live.transcoding.enabled && serverConfig.live.transcoding.enabledResolutions.length > 1"></my-feature-boolean>
+ <my-feature-boolean [value]="serverConfig().live.transcoding.enabled && serverConfig().live.transcoding.enabledResolutions.length > 1"></my-feature-boolean>
</td>
</tr>
- <tr *ngIf="serverConfig.live.enabled">
+ <tr *ngIf="serverConfig().live.enabled">
<th i18n class="t-sub-label" scope="row">Max parallel lives</th>
<td i18n>
{{ maxUserLives }} per user / {{ maxInstanceLives }} per instance
@@ -101,21 +101,21 @@
<tr>
<th i18n class="t-sub-label" scope="row">HTTP import (YouTube, Vimeo, direct URL...)</th>
<td>
- <my-feature-boolean [value]="serverConfig.import.videos.http.enabled"></my-feature-boolean>
+ <my-feature-boolean [value]="serverConfig().import.videos.http.enabled"></my-feature-boolean>
</td>
</tr>
<tr>
<th i18n class="t-sub-label" scope="row">Torrent import</th>
<td>
- <my-feature-boolean [value]="serverConfig.import.videos.torrent.enabled"></my-feature-boolean>
+ <my-feature-boolean [value]="serverConfig().import.videos.torrent.enabled"></my-feature-boolean>
</td>
</tr>
<tr>
<th i18n class="t-sub-label" scope="row">Channel synchronization with other platforms (YouTube, Vimeo, ...)</th>
<td>
- <my-feature-boolean [value]="serverConfig.import.videoChannelSynchronization.enabled"></my-feature-boolean>
+ <my-feature-boolean [value]="serverConfig().import.videoChannelSynchronization.enabled"></my-feature-boolean>
</td>
</tr>
@@ -126,14 +126,14 @@
<tr>
<th i18n class="t-sub-label" scope="row">Users can export their data</th>
<td>
- <my-feature-boolean [value]="serverConfig.export.users.enabled"></my-feature-boolean>
+ <my-feature-boolean [value]="serverConfig().export.users.enabled"></my-feature-boolean>
</td>
</tr>
<tr>
<th i18n class="t-sub-label" scope="row">Users can import their data</th>
<td>
- <my-feature-boolean [value]="serverConfig.import.users.enabled"></my-feature-boolean>
+ <my-feature-boolean [value]="serverConfig().import.users.enabled"></my-feature-boolean>
</td>
</tr>
@@ -144,7 +144,7 @@
<tr>
<th i18n class="t-sub-label" scope="row">Users can resolve distant content</th>
<td>
- <my-feature-boolean [value]="serverConfig.search.remoteUri.users"></my-feature-boolean>
+ <my-feature-boolean [value]="serverConfig().search.remoteUri.users"></my-feature-boolean>
</td>
</tr>
@@ -155,7 +155,7 @@
<tr>
<th i18n class="t-sub-label" scope="row">Available themes</th>
<td>
- <span class="theme" *ngFor="let theme of serverConfig.theme.registered">
+ <span class="theme" *ngFor="let theme of serverConfig().theme.registered">
{{ theme.name }}
</span>
</td>
@@ -164,7 +164,7 @@
<tr>
<th i18n class="t-sub-label" scope="row">Plugins enabled</th>
<td>
- <span class="plugin" *ngFor="let plugin of serverConfig.plugin.registered">
+ <span class="plugin" *ngFor="let plugin of serverConfig().plugin.registered">
{{ plugin.name }}
</span>
</td>
diff --git a/client/src/app/shared/shared-instance/instance-features-table.component.ts b/client/src/app/shared/shared-instance/instance-features-table.component.ts
index e59ee9491d..93b624bbfb 100644
--- a/client/src/app/shared/shared-instance/instance-features-table.component.ts
+++ b/client/src/app/shared/shared-instance/instance-features-table.component.ts
@@ -1,5 +1,5 @@
import { NgFor, NgIf } from '@angular/common'
-import { Component, Input, OnInit } from '@angular/core'
+import { Component, OnInit, inject, model } from '@angular/core'
import { ServerService } from '@app/core'
import { formatICU } from '@app/helpers'
import { ServerConfig, ServerStats } from '@peertube/peertube-models'
@@ -17,55 +17,54 @@ import { FeatureBooleanComponent } from './feature-boolean.component'
imports: [ NgIf, FeatureBooleanComponent, HelpComponent, PeerTubeTemplateDirective, NgFor, BytesPipe ]
})
export class InstanceFeaturesTableComponent implements OnInit {
- @Input() serverConfig: ServerConfig
- @Input() serverStats: ServerStats
+ private serverService = inject(ServerService)
- quotaHelpIndication = ''
+ readonly serverConfig = model<ServerConfig>(undefined)
+ readonly serverStats = model<ServerStats>(undefined)
- constructor (
- private serverService: ServerService
- ) { }
+ quotaHelpIndication = ''
get initialUserVideoQuota () {
- return this.serverConfig.user.videoQuota
+ return this.serverConfig().user.videoQuota
}
get dailyUserVideoQuota () {
- return Math.min(this.initialUserVideoQuota, this.serverConfig.user.videoQuotaDaily)
+ return Math.min(this.initialUserVideoQuota, this.serverConfig().user.videoQuotaDaily)
}
get maxInstanceLives () {
- const value = this.serverConfig.live.maxInstanceLives
+ const value = this.serverConfig().live.maxInstanceLives
if (value === -1) return $localize`Unlimited`
return value
}
get maxUserLives () {
- const value = this.serverConfig.live.maxUserLives
+ const value = this.serverConfig().live.maxUserLives
if (value === -1) return $localize`Unlimited`
return value
}
ngOnInit () {
- const serverConfigObs = this.serverConfig
- ? of(this.serverConfig)
+ const serverConfig = this.serverConfig()
+ const serverConfigObs = serverConfig
+ ? of(serverConfig)
: this.serverService.getConfig()
serverConfigObs.subscribe(config => {
- this.serverConfig = config
+ this.serverConfig.set(config)
this.buildQuotaHelpIndication()
})
- if (!this.serverStats) {
- this.serverService.getServerStats().subscribe(stats => this.serverStats = stats)
+ if (!this.serverStats()) {
+ this.serverService.getServerStats().subscribe(stats => this.serverStats.set(stats))
}
}
buildNSFWLabel () {
- const policy = this.serverConfig.instance.defaultNSFWPolicy
+ const policy = this.serverConfig().instance.defaultNSFWPolicy
if (policy === 'do_not_list') return $localize`Hidden`
if (policy === 'blur') return $localize`Blurred with confirmation request`
@@ -73,12 +72,12 @@ export class InstanceFeaturesTableComponent implements OnInit {
}
buildRegistrationLabel () {
- const config = this.serverConfig.signup
+ const config = this.serverConfig().signup
if (config.allowed !== true) return $localize`Disabled`
if (config.requiresApproval === true) {
- const responseTimeMS = this.serverStats?.averageRegistrationRequestResponseTimeMs
+ const responseTimeMS = this.serverStats()?.averageRegistrationRequestResponseTimeMs
if (!responseTimeMS) {
return $localize`Requires approval by moderators`
diff --git a/client/src/app/shared/shared-instance/instance-follow.service.ts b/client/src/app/shared/shared-instance/instance-follow.service.ts
index 0f6d24ee42..5109f79dff 100644
--- a/client/src/app/shared/shared-instance/instance-follow.service.ts
+++ b/client/src/app/shared/shared-instance/instance-follow.service.ts
@@ -2,7 +2,7 @@ import { SortMeta } from 'primeng/api'
import { from, Observable } from 'rxjs'
import { catchError, concatMap, toArray } from 'rxjs/operators'
import { HttpClient, HttpParams } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { RestExtractor, RestPagination, RestService } from '@app/core'
import { arrayify } from '@peertube/peertube-core-utils'
import { ActivityPubActorType, ActorFollow, FollowState, ResultList, ServerFollowCreate } from '@peertube/peertube-models'
@@ -11,14 +11,11 @@ import { AdvancedInputFilter } from '../shared-forms/advanced-input-filter.compo
@Injectable()
export class InstanceFollowService {
- private static BASE_APPLICATION_URL = environment.apiUrl + '/api/v1/server'
+ private authHttp = inject(HttpClient)
+ private restService = inject(RestService)
+ private restExtractor = inject(RestExtractor)
- constructor (
- private authHttp: HttpClient,
- private restService: RestService,
- private restExtractor: RestExtractor
- ) {
- }
+ private static BASE_APPLICATION_URL = environment.apiUrl + '/api/v1/server'
getFollowing (options: {
pagination: RestPagination
@@ -40,7 +37,7 @@ export class InstanceFollowService {
if (actorType) params = params.append('actorType', actorType)
return this.authHttp.get<ResultList<ActorFollow>>(InstanceFollowService.BASE_APPLICATION_URL + '/following', { params })
- .pipe(catchError(res => this.restExtractor.handleError(res)))
+ .pipe(catchError(res => this.restExtractor.handleError(res)))
}
getFollowers (options: {
@@ -63,7 +60,7 @@ export class InstanceFollowService {
if (actorType) params = params.append('actorType', actorType)
return this.authHttp.get<ResultList<ActorFollow>>(InstanceFollowService.BASE_APPLICATION_URL + '/followers', { params })
- .pipe(catchError(res => this.restExtractor.handleError(res)))
+ .pipe(catchError(res => this.restExtractor.handleError(res)))
}
follow (hostsOrHandles: string[]) {
@@ -73,7 +70,7 @@ export class InstanceFollowService {
}
return this.authHttp.post(InstanceFollowService.BASE_APPLICATION_URL + '/following', body)
- .pipe(catchError(res => this.restExtractor.handleError(res)))
+ .pipe(catchError(res => this.restExtractor.handleError(res)))
}
unfollow (followsArg: ActorFollow[] | ActorFollow) {
diff --git a/client/src/app/shared/shared-main/account/account.service.ts b/client/src/app/shared/shared-main/account/account.service.ts
index 2eb0723778..4f3e42dfa6 100644
--- a/client/src/app/shared/shared-main/account/account.service.ts
+++ b/client/src/app/shared/shared-main/account/account.service.ts
@@ -1,7 +1,7 @@
import { Observable, ReplaySubject } from 'rxjs'
import { catchError, map, tap } from 'rxjs/operators'
import { HttpClient } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { RestExtractor } from '@app/core'
import { Account as ServerAccount } from '@peertube/peertube-models'
import { environment } from '../../../../environments/environment'
@@ -9,21 +9,19 @@ import { Account } from './account.model'
@Injectable()
export class AccountService {
+ private authHttp = inject(HttpClient)
+ private restExtractor = inject(RestExtractor)
+
static BASE_ACCOUNT_URL = environment.apiUrl + '/api/v1/accounts/'
accountLoaded = new ReplaySubject<Account>(1)
- constructor (
- private authHttp: HttpClient,
- private restExtractor: RestExtractor
- ) { }
-
getAccount (id: number | string): Observable<Account> {
return this.authHttp.get<ServerAccount>(AccountService.BASE_ACCOUNT_URL + id)
- .pipe(
- map(accountHash => new Account(accountHash)),
- tap(account => this.accountLoaded.next(account)),
- catchError(res => this.restExtractor.handleError(res))
- )
+ .pipe(
+ map(accountHash => new Account(accountHash)),
+ tap(account => this.accountLoaded.next(account)),
+ catchError(res => this.restExtractor.handleError(res))
+ )
}
}
diff --git a/client/src/app/shared/shared-main/auth/auth-interceptor.service.ts b/client/src/app/shared/shared-main/auth/auth-interceptor.service.ts
index 9df9ced0a3..8038069725 100644
--- a/client/src/app/shared/shared-main/auth/auth-interceptor.service.ts
+++ b/client/src/app/shared/shared-main/auth/auth-interceptor.service.ts
@@ -1,17 +1,17 @@
import { Observable, of, throwError as observableThrowError } from 'rxjs'
import { catchError, switchMap } from 'rxjs/operators'
import { HTTP_INTERCEPTORS, HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http'
-import { Injectable, Injector } from '@angular/core'
+import { Injectable, Injector, inject } from '@angular/core'
import { Router } from '@angular/router'
import { AuthService } from '@app/core/auth/auth.service'
import { HttpStatusCode, OAuth2ErrorCode, PeerTubeProblemDocument, ServerErrorCode } from '@peertube/peertube-models'
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
- private authService: AuthService
+ private injector = inject(Injector)
+ private router = inject(Router)
- // https://github.com/angular/angular/issues/18224#issuecomment-316957213
- constructor (private injector: Injector, private router: Router) {}
+ private authService: AuthService
intercept (req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (this.authService === undefined) {
@@ -49,13 +49,13 @@ export class AuthInterceptor implements HttpInterceptor {
private handleTokenExpired (req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return this.authService.refreshAccessToken()
- .pipe(
- switchMap(() => {
- const authReq = this.cloneRequestWithAuth(req)
+ .pipe(
+ switchMap(() => {
+ const authReq = this.cloneRequestWithAuth(req)
- return next.handle(authReq)
- })
- )
+ return next.handle(authReq)
+ })
+ )
}
private cloneRequestWithAuth (req: HttpRequest<any>) {
diff --git a/client/src/app/shared/shared-main/buttons/action-dropdown.component.html b/client/src/app/shared/shared-main/buttons/action-dropdown.component.html
index 6f3ea41da3..afe1d8d4a0 100644
--- a/client/src/app/shared/shared-main/buttons/action-dropdown.component.html
+++ b/client/src/app/shared/shared-main/buttons/action-dropdown.component.html
@@ -1,17 +1,17 @@
<div
- *ngIf="areActionsDisplayed(actions, entry)" class="dropdown-root"
- ngbDropdown (openChange)="openChange.emit($event)" [placement]="placement" [container]="container"
+ *ngIf="areActionsDisplayed(actions(), entry())" class="dropdown-root"
+ ngbDropdown (openChange)="openChange.emit($event)" [placement]="placement()" [container]="container()"
>
<button
class="action-button peertube-button border-0"
- [ngClass]="{ 'icon-only': !label, 'peertube-button-small': buttonSize === 'small', 'secondary-button': buttonStyled && theme === 'secondary', 'primary-button': buttonStyled && theme === 'primary' }"
+ [ngClass]="{ 'icon-only': !label(), 'peertube-button-small': buttonSize() === 'small', 'secondary-button': buttonStyled() && theme() === 'secondary', 'primary-button': buttonStyled() && theme() === 'primary' }"
ngbDropdownToggle aria-label="Open actions" i18n-aria-label
>
- @if (label) {
- <span class="dropdown-toggle">{{ label }}</span>
- } @else if (buttonDirection === 'horizontal') {
+ @if (label()) {
+ <span class="dropdown-toggle">{{ label() }}</span>
+ } @else if (buttonDirection() === 'horizontal') {
<my-global-icon class="more-icon" iconName="more-horizontal"></my-global-icon>
- } @else if (buttonDirection === 'vertical') {
+ } @else if (buttonDirection() === 'vertical') {
<my-global-icon class="more-icon" iconName="more-vertical"></my-global-icon>
}
</button>
@@ -20,7 +20,7 @@
<ng-container *ngFor="let actions of getActions()">
<ng-container *ngFor="let action of actions">
- <div [ngClass]="action.class" *ngIf="isBlockDisplayed(actions, action, entry)">
+ <div [ngClass]="action.class" *ngIf="isBlockDisplayed(actions, action, entry())">
<ng-template #templateActionLabel let-action>
<my-global-icon *ngIf="action.iconName" [iconName]="action.iconName" [ngClass]="'icon-' + action.iconName" aria-hidden="true"></my-global-icon>
@@ -44,7 +44,7 @@
@if (!action.isHeader) {
<a
[ngClass]="{ 'with-icon': !!action.iconName }"
- class="dropdown-item" [routerLink]="action.linkBuilder(entry)" [queryParams]="getQueryParams(action, entry)" [title]="action.title || ''"
+ class="dropdown-item" [routerLink]="action.linkBuilder(entry())" [queryParams]="getQueryParams(action, entry())" [title]="action.title || ''"
>
<ng-container *ngTemplateOutlet="templateActionLabel; context:{ $implicit: action }"></ng-container>
</a>
@@ -54,11 +54,11 @@
<span
[ngClass]="{ 'with-icon': !!action.iconName }"
class="custom-action dropdown-item" tabindex="0" role="button" [title]="action.title || ''"
- (click)="action.handler(entry)" (keyup.enter)="action.handler(entry)"
+ (click)="action.handler(entry())" (keyup.enter)="action.handler(entry())"
>
<ng-container *ngTemplateOutlet="templateActionLabel; context:{ $implicit: action }"></ng-container>
</span>
- } @else if (areActionsDisplayed(actions, entry)) {
+ } @else if (areActionsDisplayed(actions, entry())) {
<h6 [ngClass]="{ 'with-icon': !!action.iconName }" class="dropdown-header" [title]="action.title || ''">
<ng-container *ngTemplateOutlet="templateActionLabel; context:{ $implicit: action }"></ng-container>
</h6>
@@ -67,7 +67,7 @@
</div>
</ng-container>
- <div *ngIf="areActionsDisplayed(actions, entry)" class="dropdown-divider"></div>
+ <div *ngIf="areActionsDisplayed(actions, entry())" class="dropdown-divider"></div>
</ng-container>
</div>
diff --git a/client/src/app/shared/shared-main/buttons/action-dropdown.component.ts b/client/src/app/shared/shared-main/buttons/action-dropdown.component.ts
index a136a84957..55ba604184 100644
--- a/client/src/app/shared/shared-main/buttons/action-dropdown.component.ts
+++ b/client/src/app/shared/shared-main/buttons/action-dropdown.component.ts
@@ -1,4 +1,4 @@
-import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core'
+import { ChangeDetectionStrategy, Component, input, output } from '@angular/core'
import { Params, RouterLink } from '@angular/router'
import { GlobalIconName } from '@app/shared/shared-icons/global-icon.component'
import { GlobalIconComponent } from '../../shared-icons/global-icon.component'
@@ -45,27 +45,27 @@ export type DropdownDirection = 'horizontal' | 'vertical'
NgTemplateOutlet
]
})
-
export class ActionDropdownComponent<T> {
- @Input() actions: DropdownAction<T>[] | DropdownAction<T>[][] = []
- @Input() entry: T
+ readonly actions = input<DropdownAction<T>[] | DropdownAction<T>[][]>([])
+ readonly entry = input<T>(undefined)
- @Input() placement = 'bottom-left auto'
- @Input() container: null | 'body'
+ readonly placement = input('bottom-left auto')
+ readonly container = input<null | 'body'>(undefined)
- @Input() buttonSize: DropdownButtonSize = 'normal'
- @Input() buttonDirection: DropdownDirection = 'horizontal'
- @Input() buttonStyled = true
+ readonly buttonSize = input<DropdownButtonSize>('normal')
+ readonly buttonDirection = input<DropdownDirection>('horizontal')
+ readonly buttonStyled = input(true)
- @Input() label: string
- @Input() theme: DropdownTheme = 'secondary'
+ readonly label = input<string>(undefined)
+ readonly theme = input<DropdownTheme>('secondary')
- @Output() openChange = new EventEmitter<boolean>()
+ readonly openChange = output<boolean>()
getActions (): DropdownAction<T>[][] {
- if (this.actions.length !== 0 && Array.isArray(this.actions[0])) return this.actions as DropdownAction<T>[][]
+ const actions = this.actions()
+ if (actions.length !== 0 && Array.isArray(actions[0])) return actions as DropdownAction<T>[][]
- return [ this.actions as DropdownAction<T>[] ]
+ return [ actions as DropdownAction<T>[] ]
}
getQueryParams (action: DropdownAction<T>, entry: T) {
diff --git a/client/src/app/shared/shared-main/buttons/button.component.html b/client/src/app/shared/shared-main/buttons/button.component.html
index d5ab791b79..2c2a8594d8 100644
--- a/client/src/app/shared/shared-main/buttons/button.component.html
+++ b/client/src/app/shared/shared-main/buttons/button.component.html
@@ -1,32 +1,32 @@
-@if (ptRouterLink || ptQueryParams) {
+@if (ptRouterLink() || ptQueryParams()) {
<a
class="action-button ellipsis"
- [ngClass]="classes" [ngbTooltip]="tooltip" [attr.title]="title"
- [routerLink]="ptRouterLink" [queryParams]="ptQueryParams" [queryParamsHandling]="ptQueryParamsHandling" [routerLinkActive]="ptRouterLinkActive"
+ [ngClass]="classes" [ngbTooltip]="tooltip()" [attr.title]="title()"
+ [routerLink]="ptRouterLink()" [queryParams]="ptQueryParams()" [queryParamsHandling]="ptQueryParamsHandling()" [routerLinkActive]="ptRouterLinkActive()"
>
<ng-container *ngTemplateOutlet="content"></ng-container>
</a>
-} @else if (href) {
+} @else if (href()) {
<a
class="action-button ellipsis"
- [ngClass]="classes" [ngbTooltip]="tooltip" [attr.title]="title"
- [href]="href" target="_blank"
+ [ngClass]="classes" [ngbTooltip]="tooltip()" [attr.title]="title()"
+ [href]="href()" target="_blank"
>
<ng-container *ngTemplateOutlet="content"></ng-container>
</a>
} @else {
- <button type="button" class="action-button ellipsis" [ngClass]="classes" [disabled]="disabled" [ngbTooltip]="tooltip" [attr.title]="title">
+ <button type="button" class="action-button ellipsis" [ngClass]="classes" [disabled]="disabled()" [ngbTooltip]="tooltip()" [attr.title]="title()">
<ng-container *ngTemplateOutlet="content"></ng-container>
</button>
}
<ng-template #content>
- <my-loader size="sm" [ngClass]="{ displayed: loading }" [loading]="loading"></my-loader>
- <my-global-icon *ngIf="icon && !loading" [iconName]="icon"></my-global-icon>
+ <my-loader size="sm" [ngClass]="{ displayed: loading() }" [loading]="loading()"></my-loader>
+ <my-global-icon *ngIf="icon() && !loading()" [iconName]="icon()"></my-global-icon>
<span class="button-label" #labelContent (cdkObserveContent)="ngOnChanges()">
- @if (label) {
- {{ label }}
+ @if (label()) {
+ {{ label() }}
} @else {
<ng-content></ng-content>
}
diff --git a/client/src/app/shared/shared-main/buttons/button.component.ts b/client/src/app/shared/shared-main/buttons/button.component.ts
index 061fe0d594..cdabbc1e59 100644
--- a/client/src/app/shared/shared-main/buttons/button.component.ts
+++ b/client/src/app/shared/shared-main/buttons/button.component.ts
@@ -6,10 +6,11 @@ import {
ChangeDetectorRef,
Component,
ElementRef,
- Input,
OnChanges,
- ViewChild,
- booleanAttribute
+ booleanAttribute,
+ inject,
+ input,
+ viewChild
} from '@angular/core'
import { Params, QueryParamsHandling, RouterLink, RouterLinkActive } from '@angular/router'
import { GlobalIconName } from '@app/shared/shared-icons/global-icon.component'
@@ -37,32 +38,31 @@ const debugLogger = debug('peertube:button')
RouterLinkActive
]
})
-
export class ButtonComponent implements OnChanges, AfterViewInit {
- @Input() label = ''
- @Input() theme: 'primary' | 'secondary' | 'tertiary' = 'secondary'
- @Input() icon: GlobalIconName
+ private cd = inject(ChangeDetectorRef)
- @Input() href: string
- @Input() ptRouterLink: string[] | string
- @Input() ptQueryParams: Params
- @Input() ptQueryParamsHandling: QueryParamsHandling
- @Input() ptRouterLinkActive = ''
+ readonly label = input('')
+ readonly theme = input<'primary' | 'secondary' | 'tertiary'>('secondary')
+ readonly icon = input<GlobalIconName>(undefined)
- @Input() title: string
- @Input() tooltip: string
- @Input({ transform: booleanAttribute }) active = false
+ readonly href = input<string>(undefined)
+ readonly ptRouterLink = input<string[] | string>(undefined)
+ readonly ptQueryParams = input<Params>(undefined)
+ readonly ptQueryParamsHandling = input<QueryParamsHandling>(undefined)
+ readonly ptRouterLinkActive = input('')
- @Input({ transform: booleanAttribute }) loading = false
- @Input({ transform: booleanAttribute }) disabled = false
- @Input({ transform: booleanAttribute }) responsiveLabel = false
- @Input({ transform: booleanAttribute }) rounded = false
+ readonly title = input<string>(undefined)
+ readonly tooltip = input<string>(undefined)
+ readonly active = input(false, { transform: booleanAttribute })
- @ViewChild('labelContent') labelContent: ElementRef
+ readonly loading = input(false, { transform: booleanAttribute })
+ readonly disabled = input(false, { transform: booleanAttribute })
+ readonly responsiveLabel = input(false, { transform: booleanAttribute })
+ readonly rounded = input(false, { transform: booleanAttribute })
- classes: { [id: string]: boolean } = {}
+ readonly labelContent = viewChild<ElementRef>('labelContent')
- constructor (private cd: ChangeDetectorRef) {}
+ classes: { [id: string]: boolean } = {}
ngOnChanges () {
this.buildClasses()
@@ -73,22 +73,22 @@ export class ButtonComponent implements OnChanges, AfterViewInit {
}
private buildClasses () {
- const isButtonLink = !!this.ptRouterLink || !!this.href
+ const isButtonLink = !!this.ptRouterLink() || !!this.href()
this.classes = {
- 'active': this.active,
+ 'active': this.active(),
'peertube-button': !isButtonLink,
'peertube-button-link': isButtonLink,
- 'primary-button': this.theme === 'primary',
- 'secondary-button': this.theme === 'secondary',
- 'tertiary-button': this.theme === 'tertiary',
- 'has-icon': !!this.icon,
- 'rounded-icon-button': !!this.rounded,
- 'icon-only': !this.label && !(this.labelContent?.nativeElement as HTMLElement)?.innerText,
- 'responsive-label': this.responsiveLabel
+ 'primary-button': this.theme() === 'primary',
+ 'secondary-button': this.theme() === 'secondary',
+ 'tertiary-button': this.theme() === 'tertiary',
+ 'has-icon': !!this.icon(),
+ 'rounded-icon-button': !!this.rounded(),
+ 'icon-only': !this.label() && !(this.labelContent()?.nativeElement as HTMLElement)?.innerText,
+ 'responsive-label': this.responsiveLabel()
}
- debugLogger('Built button classes', { classes: this.classes, labelContent: this.labelContent })
+ debugLogger('Built button classes', { classes: this.classes, labelContent: this.labelContent() })
this.cd.markForCheck()
}
diff --git a/client/src/app/shared/shared-main/buttons/copy-button.component.html b/client/src/app/shared/shared-main/buttons/copy-button.component.html
index 5be8c2e1dc..54f12e82f8 100644
--- a/client/src/app/shared/shared-main/buttons/copy-button.component.html
+++ b/client/src/app/shared/shared-main/buttons/copy-button.component.html
@@ -2,7 +2,7 @@
type="button"
class="btn copy-button"
(click)="copy()"
- [attr.title]="title" [ngClass]="{ 'is-input-group': isInputGroup, 'with-border': withBorder }"
+ [attr.title]="title()" [ngClass]="{ 'is-input-group': isInputGroup(), 'with-border': withBorder() }"
>
<my-global-icon iconName="copy"></my-global-icon>
diff --git a/client/src/app/shared/shared-main/buttons/copy-button.component.ts b/client/src/app/shared/shared-main/buttons/copy-button.component.ts
index aa58277e69..6b41d9b518 100644
--- a/client/src/app/shared/shared-main/buttons/copy-button.component.ts
+++ b/client/src/app/shared/shared-main/buttons/copy-button.component.ts
@@ -1,6 +1,6 @@
import { Clipboard } from '@angular/cdk/clipboard'
import { NgClass } from '@angular/common'
-import { booleanAttribute, Component, Input } from '@angular/core'
+import { booleanAttribute, Component, inject, input } from '@angular/core'
import { Notifier } from '@app/core'
import { GlobalIconComponent } from '../../shared-icons/global-icon.component'
@@ -12,22 +12,22 @@ import { GlobalIconComponent } from '../../shared-icons/global-icon.component'
imports: [ NgClass, GlobalIconComponent ]
})
export class CopyButtonComponent {
- @Input() value: string
- @Input() elementContent: HTMLElement
+ private notifier = inject(Notifier)
+ private clipboard = inject(Clipboard)
- @Input() title: string
- @Input() notification: string
+ readonly value = input<string>(undefined)
+ readonly elementContent = input<HTMLElement>(undefined)
- @Input({ transform: booleanAttribute }) withBorder = false
- @Input({ transform: booleanAttribute }) isInputGroup = false
+ readonly title = input<string>(undefined)
+ readonly notification = input<string>(undefined)
- constructor (private notifier: Notifier, private clipboard: Clipboard) {
-
- }
+ readonly withBorder = input(false, { transform: booleanAttribute })
+ readonly isInputGroup = input(false, { transform: booleanAttribute })
copy () {
- this.clipboard.copy(this.value || this.elementContent?.innerText)
+ this.clipboard.copy(this.value() || this.elementContent()?.innerText)
- if (this.notification) this.notifier.success(this.notification)
+ const notification = this.notification()
+ if (notification) this.notifier.success(notification)
}
}
diff --git a/client/src/app/shared/shared-main/buttons/delete-button.component.ts b/client/src/app/shared/shared-main/buttons/delete-button.component.ts
index 65785925ec..13a911f276 100644
--- a/client/src/app/shared/shared-main/buttons/delete-button.component.ts
+++ b/client/src/app/shared/shared-main/buttons/delete-button.component.ts
@@ -1,4 +1,4 @@
-import { ChangeDetectionStrategy, Component, Input, OnChanges } from '@angular/core'
+import { ChangeDetectionStrategy, Component, OnChanges, input, model } from '@angular/core'
import { ButtonComponent } from './button.component'
@Component({
@@ -6,27 +6,28 @@ import { ButtonComponent } from './button.component'
template: `
<my-button
icon="delete" theme="secondary"
- [disabled]="disabled" [label]="label" [title]="title"
- [responsiveLabel]="responsiveLabel"
+ [disabled]="disabled()" [label]="label()" [title]="title()"
+ [responsiveLabel]="responsiveLabel()"
></my-button>
`,
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [ ButtonComponent ]
})
export class DeleteButtonComponent implements OnChanges {
- @Input() label: string
- @Input() title: string
- @Input() responsiveLabel = false
- @Input() disabled: boolean
+ readonly label = model<string>(undefined)
+ readonly title = model<string>(undefined)
+ readonly responsiveLabel = input(false)
+ readonly disabled = input<boolean>(undefined)
ngOnChanges () {
- if (this.label === undefined && !this.title) {
- this.title = $localize`Delete`
+ const label = this.label()
+ if (label === undefined && !this.title()) {
+ this.title.set($localize`Delete`)
}
// <my-delete-button label /> Use default label
- if (this.label === '') {
- this.label = $localize`Delete`
+ if (label === '') {
+ this.label.set($localize`Delete`)
}
}
}
diff --git a/client/src/app/shared/shared-main/buttons/edit-button.component.ts b/client/src/app/shared/shared-main/buttons/edit-button.component.ts
index c97cfd39f9..b367475c1f 100644
--- a/client/src/app/shared/shared-main/buttons/edit-button.component.ts
+++ b/client/src/app/shared/shared-main/buttons/edit-button.component.ts
@@ -1,32 +1,33 @@
-import { ChangeDetectionStrategy, Component, Input, OnChanges } from '@angular/core'
+import { ChangeDetectionStrategy, Component, OnChanges, input, model } from '@angular/core'
import { ButtonComponent } from './button.component'
@Component({
selector: 'my-edit-button',
template: `
<my-button
- icon="edit" [label]="label" [title]="title" [responsiveLabel]="responsiveLabel"
- [ptRouterLink]="ptRouterLink"
+ icon="edit" [label]="label()" [title]="title()" [responsiveLabel]="responsiveLabel()"
+ [ptRouterLink]="ptRouterLink()"
></my-button>
`,
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [ ButtonComponent ]
})
export class EditButtonComponent implements OnChanges {
- @Input() label: string
- @Input() title: string
- @Input() ptRouterLink: string[] | string = []
- @Input() responsiveLabel = false
+ readonly label = model<string>(undefined)
+ readonly title = model<string>(undefined)
+ readonly ptRouterLink = input<string[] | string>([])
+ readonly responsiveLabel = input(false)
ngOnChanges () {
// <my-edit-button /> No label
- if (this.label === undefined && !this.title) {
- this.title = $localize`Update`
+ const label = this.label()
+ if (label === undefined && !this.title()) {
+ this.title.set($localize`Update`)
}
// <my-edit-button label /> Use default label
- if (this.label === '') {
- this.label = $localize`Update`
+ if (label === '') {
+ this.label.set($localize`Update`)
}
}
}
diff --git a/client/src/app/shared/shared-main/buttons/help.component.html b/client/src/app/shared/shared-main/buttons/help.component.html
index 0c69d55e74..8ce8f1af8c 100644
--- a/client/src/app/shared/shared-main/buttons/help.component.html
+++ b/client/src/app/shared/shared-main/buttons/help.component.html
@@ -20,15 +20,15 @@
<button
class="help-tooltip-button p-0 border-0 mx-1"
- [title]="title"
+ [title]="title()"
popoverClass="help-popover"
[attr.aria-pressed]="isPopoverOpened"
[ngbPopover]="tooltipTemplate"
- [placement]="tooltipPlacement"
- [autoClose]="autoClose"
+ [placement]="tooltipPlacement()"
+ [autoClose]="autoClose()"
(onHidden)="onPopoverHidden()"
(onShown)="onPopoverShown()"
type="button"
>
- <my-global-icon [iconName]="iconName"></my-global-icon>
+ <my-global-icon [iconName]="iconName()"></my-global-icon>
</button>
diff --git a/client/src/app/shared/shared-main/buttons/help.component.ts b/client/src/app/shared/shared-main/buttons/help.component.ts
index c138e9101e..f9c5b655b3 100644
--- a/client/src/app/shared/shared-main/buttons/help.component.ts
+++ b/client/src/app/shared/shared-main/buttons/help.component.ts
@@ -3,11 +3,10 @@ import {
AfterContentInit,
booleanAttribute,
Component,
- ContentChildren,
- Input,
+ contentChildren,
+ input,
OnChanges,
OnInit,
- QueryList,
TemplateRef
} from '@angular/core'
import { GlobalIconName } from '@app/shared/shared-icons/global-icon.component'
@@ -22,16 +21,15 @@ import { PeerTubeTemplateDirective } from '../common/peertube-template.directive
templateUrl: './help.component.html',
imports: [ NgIf, NgTemplateOutlet, NgbPopover, GlobalIconComponent ]
})
-
export class HelpComponent implements OnInit, OnChanges, AfterContentInit {
- @Input() helpType: 'custom' | 'markdownText' | 'markdownEnhanced' = 'custom'
- @Input() tooltipPlacement = 'right auto'
- @Input() iconName: GlobalIconName = 'help'
- @Input() title = $localize`Get help`
- @Input() autoClose = 'outside'
- @Input({ transform: booleanAttribute }) supportRelMe = false
+ readonly helpType = input<'custom' | 'markdownText' | 'markdownEnhanced'>('custom')
+ readonly tooltipPlacement = input('right auto')
+ readonly iconName = input<GlobalIconName>('help')
+ readonly title = input($localize`Get help`)
+ readonly autoClose = input('outside')
+ readonly supportRelMe = input(false, { transform: booleanAttribute })
- @ContentChildren(PeerTubeTemplateDirective) templates: QueryList<PeerTubeTemplateDirective<'preHtml' | 'customHtml' | 'postHtml'>>
+ readonly templates = contentChildren(PeerTubeTemplateDirective)
isPopoverOpened = false
mainHtml = ''
@@ -46,17 +44,17 @@ export class HelpComponent implements OnInit, OnChanges, AfterContentInit {
ngAfterContentInit () {
{
- const t = this.templates.find(t => t.name === 'preHtml')
+ const t = this.templates().find(t => t.name() === 'preHtml')
if (t) this.preHtmlTemplate = t.template
}
{
- const t = this.templates.find(t => t.name === 'customHtml')
+ const t = this.templates().find(t => t.name() === 'customHtml')
if (t) this.customHtmlTemplate = t.template
}
{
- const t = this.templates.find(t => t.name === 'postHtml')
+ const t = this.templates().find(t => t.name() === 'postHtml')
if (t) this.postHtmlTemplate = t.template
}
}
@@ -74,12 +72,13 @@ export class HelpComponent implements OnInit, OnChanges, AfterContentInit {
}
private init () {
- if (this.helpType === 'markdownText') {
+ const helpType = this.helpType()
+ if (helpType === 'markdownText') {
this.mainHtml = this.formatMarkdownSupport(TEXT_RULES)
return
}
- if (this.helpType === 'markdownEnhanced') {
+ if (helpType === 'markdownEnhanced') {
this.mainHtml = this.formatMarkdownSupport(ENHANCED_RULES)
return
}
@@ -91,9 +90,10 @@ export class HelpComponent implements OnInit, OnChanges, AfterContentInit {
$localize`<a href="https://en.wikipedia.org/wiki/Markdown#Example" target="_blank" rel="noopener noreferrer">Markdown</a> compatible that supports:` +
this.createMarkdownList(rules)
- if (this.supportRelMe) {
- // eslint-disable-next-line max-len
- str += $localize`<a href="https://docs.joinmastodon.org/user/profile/#verification" target="_blank" rel="noopener noreferrer">Mastodon verification link</a> is also supported.`
+ if (this.supportRelMe()) {
+ str +=
+ // eslint-disable-next-line max-len
+ $localize`<a href="https://docs.joinmastodon.org/user/profile/#verification" target="_blank" rel="noopener noreferrer">Mastodon verification link</a> is also supported.`
}
return str
diff --git a/client/src/app/shared/shared-main/channel/channels-setup-message.component.html b/client/src/app/shared/shared-main/channel/channels-setup-message.component.html
index 178db914a3..7806514b7b 100644
--- a/client/src/app/shared/shared-main/channel/channels-setup-message.component.html
+++ b/client/src/app/shared/shared-main/channel/channels-setup-message.component.html
@@ -3,5 +3,5 @@
<div i18n>Some of your channels are not fully set up. Make them welcoming and explicit about what you publish by adding a <strong>banner</strong>, an <strong>avatar</strong> and a <strong>description</strong>.</div>
- <a *ngIf="!hideLink" class="peertube-button-link secondary-button mt-2" routerLink="/my-library/video-channels" i18n>Set up my channels</a>
+ <a *ngIf="!hideLink()" class="peertube-button-link secondary-button mt-2" routerLink="/my-library/video-channels" i18n>Set up my channels</a>
</my-alert>
diff --git a/client/src/app/shared/shared-main/channel/channels-setup-message.component.ts b/client/src/app/shared/shared-main/channel/channels-setup-message.component.ts
index c3dd250f08..7b66ef98a1 100644
--- a/client/src/app/shared/shared-main/channel/channels-setup-message.component.ts
+++ b/client/src/app/shared/shared-main/channel/channels-setup-message.component.ts
@@ -1,5 +1,5 @@
import { NgIf } from '@angular/common'
-import { Component, Input, OnInit } from '@angular/core'
+import { Component, OnInit, inject, input } from '@angular/core'
import { RouterLink } from '@angular/router'
import { AuthService, User } from '@app/core'
import { GlobalIconComponent } from '../../shared-icons/global-icon.component'
@@ -13,13 +13,11 @@ import { VideoChannel } from './video-channel.model'
imports: [ NgIf, GlobalIconComponent, RouterLink, AlertComponent ]
})
export class ChannelsSetupMessageComponent implements OnInit {
- @Input() hideLink = false
+ private authService = inject(AuthService)
- user: User = null
+ readonly hideLink = input(false)
- constructor (
- private authService: AuthService
- ) {}
+ user: User = null
hasChannelNotConfigured () {
if (!this.user.videoChannels) return false
diff --git a/client/src/app/shared/shared-main/channel/video-channel-sync.service.ts b/client/src/app/shared/shared-main/channel/video-channel-sync.service.ts
index 81b6826a87..f23480d254 100644
--- a/client/src/app/shared/shared-main/channel/video-channel-sync.service.ts
+++ b/client/src/app/shared/shared-main/channel/video-channel-sync.service.ts
@@ -2,7 +2,7 @@ import { SortMeta } from 'primeng/api'
import { catchError, Observable } from 'rxjs'
import { environment } from 'src/environments/environment'
import { HttpClient, HttpParams } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { RestExtractor, RestPagination, RestService } from '@app/core'
import { ResultList, VideoChannelSync, VideoChannelSyncCreate } from '@peertube/peertube-models'
import { Account } from '../account/account.model'
@@ -12,13 +12,11 @@ import { AccountService } from '../account/account.service'
providedIn: 'root'
})
export class VideoChannelSyncService {
- static BASE_VIDEO_CHANNEL_URL = environment.apiUrl + '/api/v1/video-channel-syncs'
+ private authHttp = inject(HttpClient)
+ private restExtractor = inject(RestExtractor)
+ private restService = inject(RestService)
- constructor (
- private authHttp: HttpClient,
- private restExtractor: RestExtractor,
- private restService: RestService
- ) { }
+ static BASE_VIDEO_CHANNEL_URL = environment.apiUrl + '/api/v1/video-channel-syncs'
listAccountVideoChannelsSyncs (parameters: {
sort: SortMeta
@@ -33,18 +31,18 @@ export class VideoChannelSyncService {
const url = AccountService.BASE_ACCOUNT_URL + account.nameWithHost + '/video-channel-syncs'
return this.authHttp.get<ResultList<VideoChannelSync>>(url, { params })
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
createSync (body: VideoChannelSyncCreate) {
return this.authHttp.post<{ videoChannelSync: VideoChannelSync }>(VideoChannelSyncService.BASE_VIDEO_CHANNEL_URL, body)
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
deleteSync (videoChannelsSyncId: number) {
const url = `${VideoChannelSyncService.BASE_VIDEO_CHANNEL_URL}/${videoChannelsSyncId}`
return this.authHttp.delete(url)
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
}
diff --git a/client/src/app/shared/shared-main/channel/video-channel.service.ts b/client/src/app/shared/shared-main/channel/video-channel.service.ts
index 61f4b7058f..23b3153ebc 100644
--- a/client/src/app/shared/shared-main/channel/video-channel.service.ts
+++ b/client/src/app/shared/shared-main/channel/video-channel.service.ts
@@ -1,7 +1,7 @@
import { Observable, ReplaySubject } from 'rxjs'
import { catchError, map, tap } from 'rxjs/operators'
import { HttpClient, HttpParams } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { ComponentPaginationLight, RestExtractor, RestService, ServerService } from '@app/core'
import {
ActorImage,
@@ -18,17 +18,15 @@ import { Account } from '../account/account.model'
@Injectable({ providedIn: 'root' })
export class VideoChannelService {
+ private authHttp = inject(HttpClient)
+ private restService = inject(RestService)
+ private restExtractor = inject(RestExtractor)
+ private serverService = inject(ServerService)
+
static BASE_VIDEO_CHANNEL_URL = environment.apiUrl + '/api/v1/video-channels/'
videoChannelLoaded = new ReplaySubject<VideoChannel>(1)
- constructor (
- private authHttp: HttpClient,
- private restService: RestService,
- private restExtractor: RestExtractor,
- private serverService: ServerService
- ) { }
-
static extractVideoChannels (result: ResultList<VideoChannelServer>) {
const videoChannels: VideoChannel[] = []
@@ -41,11 +39,11 @@ export class VideoChannelService {
getVideoChannel (videoChannelName: string) {
return this.authHttp.get<VideoChannel>(VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannelName)
- .pipe(
- map(videoChannelHash => new VideoChannel(videoChannelHash)),
- tap(videoChannel => this.videoChannelLoaded.next(videoChannel)),
- catchError(err => this.restExtractor.handleError(err))
- )
+ .pipe(
+ map(videoChannelHash => new VideoChannel(videoChannelHash)),
+ tap(videoChannel => this.videoChannelLoaded.next(videoChannel)),
+ catchError(err => this.restExtractor.handleError(err))
+ )
}
listAccountVideoChannels (options: {
@@ -71,39 +69,39 @@ export class VideoChannelService {
const url = AccountService.BASE_ACCOUNT_URL + account.nameWithHost + '/video-channels'
return this.authHttp.get<ResultList<VideoChannelServer>>(url, { params })
- .pipe(
- map(res => VideoChannelService.extractVideoChannels(res)),
- catchError(err => this.restExtractor.handleError(err))
- )
+ .pipe(
+ map(res => VideoChannelService.extractVideoChannels(res)),
+ catchError(err => this.restExtractor.handleError(err))
+ )
}
createVideoChannel (videoChannel: VideoChannelCreate) {
return this.authHttp.post(VideoChannelService.BASE_VIDEO_CHANNEL_URL, videoChannel)
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
updateVideoChannel (videoChannelName: string, videoChannel: VideoChannelUpdate) {
return this.authHttp.put(VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannelName, videoChannel)
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
changeVideoChannelImage (videoChannelName: string, avatarForm: FormData, type: 'avatar' | 'banner') {
const url = VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannelName + '/' + type + '/pick'
return this.authHttp.post<{ avatars?: ActorImage[], banners?: ActorImage[] }>(url, avatarForm)
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
deleteVideoChannelImage (videoChannelName: string, type: 'avatar' | 'banner') {
const url = VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannelName + '/' + type
return this.authHttp.delete(url)
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
removeVideoChannel (videoChannel: VideoChannel) {
return this.authHttp.delete(VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannel.nameWithHost)
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
importVideos (videoChannelName: string, externalChannelUrl: string, syncId?: number) {
@@ -115,6 +113,6 @@ export class VideoChannelService {
}
return this.authHttp.post(path, body)
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
}
diff --git a/client/src/app/shared/shared-main/common/alert.component.ts b/client/src/app/shared/shared-main/common/alert.component.ts
index 312538de84..4d759775bd 100644
--- a/client/src/app/shared/shared-main/common/alert.component.ts
+++ b/client/src/app/shared/shared-main/common/alert.component.ts
@@ -1,6 +1,5 @@
-import { NgClass, NgIf, NgTemplateOutlet } from '@angular/common'
-import { booleanAttribute, Component, Input, OnChanges, OnInit } from '@angular/core'
-import { RouterLink } from '@angular/router'
+import { NgClass } from '@angular/common'
+import { booleanAttribute, Component, OnChanges, OnInit, input } from '@angular/core'
export type AlertType = 'success' | 'info' | 'warning' | 'danger' | 'primary'
@@ -8,11 +7,11 @@ export type AlertType = 'success' | 'info' | 'warning' | 'danger' | 'primary'
selector: 'my-alert',
styleUrls: [ './alert.component.scss' ],
templateUrl: './alert.component.html',
- imports: [ NgIf, RouterLink, NgClass, NgTemplateOutlet ]
+ imports: [ NgClass ]
})
export class AlertComponent implements OnInit, OnChanges {
- @Input({ required: true }) type: AlertType
- @Input({ transform: booleanAttribute }) rounded = true
+ readonly type = input.required<AlertType>()
+ readonly rounded = input(true, { transform: booleanAttribute })
builtClasses = ''
@@ -27,13 +26,14 @@ export class AlertComponent implements OnInit, OnChanges {
private buildClasses () {
this.builtClasses = 'alert'
- if (this.type === 'primary') {
+ const type = this.type()
+ if (type === 'primary') {
this.builtClasses += ' pt-alert-primary'
} else {
- this.builtClasses += ' alert-' + this.type
+ this.builtClasses += ' alert-' + type
}
- if (this.rounded !== true) {
+ if (this.rounded() !== true) {
this.builtClasses += ' rounded-0'
}
}
diff --git a/client/src/app/shared/shared-main/common/auto-colspan.directive.ts b/client/src/app/shared/shared-main/common/auto-colspan.directive.ts
index 613f2a9296..4dfc8d3be8 100644
--- a/client/src/app/shared/shared-main/common/auto-colspan.directive.ts
+++ b/client/src/app/shared/shared-main/common/auto-colspan.directive.ts
@@ -1,15 +1,12 @@
-import { AfterViewInit, Directive, ElementRef, Renderer2 } from '@angular/core'
+import { AfterViewInit, Directive, ElementRef, Renderer2, inject } from '@angular/core'
@Directive({
selector: '[myAutoColspan]',
standalone: true
})
export class AutoColspanDirective implements AfterViewInit {
-
- constructor (
- private host: ElementRef,
- private renderer: Renderer2
- ) { }
+ private host = inject(ElementRef)
+ private renderer = inject(Renderer2)
ngAfterViewInit () {
const el = this.host.nativeElement as HTMLElement
diff --git a/client/src/app/shared/shared-main/common/autofocus.directive.ts b/client/src/app/shared/shared-main/common/autofocus.directive.ts
index 9251502499..104d6cf986 100644
--- a/client/src/app/shared/shared-main/common/autofocus.directive.ts
+++ b/client/src/app/shared/shared-main/common/autofocus.directive.ts
@@ -1,11 +1,11 @@
-import { AfterViewInit, Directive, ElementRef } from '@angular/core'
+import { AfterViewInit, Directive, ElementRef, inject } from '@angular/core'
@Directive({
selector: '[myAutofocus]',
standalone: true
})
export class AutofocusDirective implements AfterViewInit {
- constructor (private host: ElementRef) { }
+ private host = inject(ElementRef)
ngAfterViewInit () {
const el = this.host.nativeElement as HTMLElement
diff --git a/client/src/app/shared/shared-main/common/date.pipe.ts b/client/src/app/shared/shared-main/common/date.pipe.ts
index 8e9816d8d7..eefa977f08 100644
--- a/client/src/app/shared/shared-main/common/date.pipe.ts
+++ b/client/src/app/shared/shared-main/common/date.pipe.ts
@@ -1,5 +1,5 @@
import { DatePipe } from '@angular/common'
-import { Inject, LOCALE_ID, Pipe, PipeTransform } from '@angular/core'
+import { LOCALE_ID, Pipe, PipeTransform, inject } from '@angular/core'
// Re-implementation of the angular date pipe that uses the web browser locale to display dates
@@ -12,7 +12,9 @@ export class PTDatePipe implements PipeTransform {
private angularPipe: DatePipe
private customLocaleId: string
- constructor (@Inject(LOCALE_ID) localeId: string) {
+ constructor () {
+ const localeId = inject(LOCALE_ID)
+
if (navigator.language.includes('-') && navigator.language.split('-')[0] === localeId.split('-')[0]) {
this.customLocaleId = navigator.language
} else {
diff --git a/client/src/app/shared/shared-main/common/defer-loading.directive.ts b/client/src/app/shared/shared-main/common/defer-loading.directive.ts
index 557402390e..b94cea0bf0 100644
--- a/client/src/app/shared/shared-main/common/defer-loading.directive.ts
+++ b/client/src/app/shared/shared-main/common/defer-loading.directive.ts
@@ -2,15 +2,15 @@ import debug from 'debug'
import {
AfterViewInit,
ChangeDetectorRef,
- ContentChild,
Directive,
ElementRef,
EmbeddedViewRef,
- EventEmitter,
OnDestroy,
- Output,
TemplateRef,
- ViewContainerRef
+ ViewContainerRef,
+ inject,
+ output,
+ contentChild
} from '@angular/core'
const debugLogger = debug('peertube:main:DeferLoadingDirective')
@@ -20,20 +20,18 @@ const debugLogger = debug('peertube:main:DeferLoadingDirective')
standalone: true
})
export class DeferLoadingDirective implements AfterViewInit, OnDestroy {
- @ContentChild(TemplateRef) template: TemplateRef<any>
+ private el = inject(ElementRef)
+ private viewContainer = inject(ViewContainerRef)
+ private cd = inject(ChangeDetectorRef)
- @Output() loaded = new EventEmitter()
+ readonly template = contentChild(TemplateRef)
+
+ readonly loaded = output()
view: EmbeddedViewRef<any>
private observer: IntersectionObserver
- constructor (
- private el: ElementRef,
- private viewContainer: ViewContainerRef,
- private cd: ChangeDetectorRef
- ) { }
-
ngAfterViewInit () {
if (this.hasIncompatibleBrowser()) {
return this.load()
@@ -56,7 +54,7 @@ export class DeferLoadingDirective implements AfterViewInit, OnDestroy {
debugLogger('Loading component')
this.viewContainer.clear()
- this.view = this.viewContainer.createEmbeddedView(this.template, {}, 0)
+ this.view = this.viewContainer.createEmbeddedView(this.template(), {}, 0)
this.loaded.emit()
this.cd.detectChanges()
}
diff --git a/client/src/app/shared/shared-main/common/infinite-scroller.directive.ts b/client/src/app/shared/shared-main/common/infinite-scroller.directive.ts
index e3189c4e9b..164a8de874 100644
--- a/client/src/app/shared/shared-main/common/infinite-scroller.directive.ts
+++ b/client/src/app/shared/shared-main/common/infinite-scroller.directive.ts
@@ -1,4 +1,4 @@
-import { AfterViewChecked, booleanAttribute, Directive, ElementRef, EventEmitter, Input, OnDestroy, OnInit, Output } from '@angular/core'
+import { AfterViewChecked, booleanAttribute, Directive, ElementRef, OnDestroy, OnInit, inject, input, output } from '@angular/core'
import { PeerTubeRouterService, RouterSetting } from '@app/core'
import { fromEvent, Observable, Subscription } from 'rxjs'
import { distinctUntilChanged, filter, map, share, startWith, throttleTime } from 'rxjs/operators'
@@ -8,15 +8,19 @@ import { distinctUntilChanged, filter, map, share, startWith, throttleTime } fro
standalone: true
})
export class InfiniteScrollerDirective implements OnInit, OnDestroy, AfterViewChecked {
- @Input() percentLimit = 70
- @Input({ transform: booleanAttribute }) onItself = false
- @Input() dataObservable: Observable<any[]>
+ private peertubeRouter = inject(PeerTubeRouterService)
+ private el = inject(ElementRef)
+ readonly percentLimit = input(70)
+ readonly onItself = input(false, { transform: booleanAttribute })
// Add angular state in query params to reuse the routed component
- @Input({ transform: booleanAttribute }) setAngularState: boolean
- @Input() parentDisabled = false
+ readonly dataObservable = input<Observable<any[]>>(undefined)
- @Output() nearOfBottom = new EventEmitter<void>()
+ // Add angular state in query params to reuse the routed component
+ readonly setAngularState = input<boolean, unknown>(undefined, { transform: booleanAttribute })
+ readonly parentDisabled = input(false)
+
+ readonly nearOfBottom = output()
private decimalLimit = 0
private lastCurrentBottom = -1
@@ -25,11 +29,8 @@ export class InfiniteScrollerDirective implements OnInit, OnDestroy, AfterViewCh
private checkScroll = false
- constructor (
- private peertubeRouter: PeerTubeRouterService,
- private el: ElementRef
- ) {
- this.decimalLimit = this.percentLimit / 100
+ constructor () {
+ this.decimalLimit = this.percentLimit() / 100
}
ngAfterViewChecked () {
@@ -52,14 +53,14 @@ export class InfiniteScrollerDirective implements OnInit, OnDestroy, AfterViewCh
}
initialize () {
- this.container = this.onItself
+ this.container = this.onItself()
? this.el.nativeElement
: document.documentElement
// Emit the last value
const throttleOptions = { leading: true, trailing: true }
- const scrollableElement = this.onItself ? this.container : window
+ const scrollableElement = this.onItself() ? this.container : window
const scrollObservable = fromEvent(scrollableElement, 'scroll')
.pipe(
startWith(true),
@@ -76,15 +77,16 @@ export class InfiniteScrollerDirective implements OnInit, OnDestroy, AfterViewCh
filter(({ current, maximumScroll }) => (current / maximumScroll) > this.decimalLimit)
)
.subscribe(() => {
- if (this.setAngularState && !this.parentDisabled) this.setScrollRouteParams()
+ if (this.setAngularState() && !this.parentDisabled()) this.setScrollRouteParams()
this.nearOfBottom.emit()
})
- if (this.dataObservable) {
- this.dataObservable
- .pipe(filter(d => d.length !== 0))
- .subscribe(() => this.checkScroll = true)
+ const dataObservable = this.dataObservable()
+ if (dataObservable) {
+ dataObservable
+ .pipe(filter(d => d.length !== 0))
+ .subscribe(() => this.checkScroll = true)
}
}
@@ -93,7 +95,7 @@ export class InfiniteScrollerDirective implements OnInit, OnDestroy, AfterViewCh
}
private getMaximumScroll () {
- const elementHeight = this.onItself ? this.container.clientHeight : window.innerHeight
+ const elementHeight = this.onItself() ? this.container.clientHeight : window.innerHeight
return this.container.scrollHeight - elementHeight
}
diff --git a/client/src/app/shared/shared-main/common/link.component.html b/client/src/app/shared/shared-main/common/link.component.html
index 451bdbf5a0..7fe2ad7bb8 100644
--- a/client/src/app/shared/shared-main/common/link.component.html
+++ b/client/src/app/shared/shared-main/common/link.component.html
@@ -1,15 +1,15 @@
<ng-template #content>
- <my-global-icon *ngIf="icon" [iconName]="icon"></my-global-icon>
+ <my-global-icon *ngIf="icon()" [iconName]="icon()"></my-global-icon>
<ng-content></ng-content>
</ng-template>
-@if (href) {
- <a [href]="href" [target]="target" [attr.title]="title" [ariaLabel]="ariaLabel" [tabindex]="tabindex" [ngClass]="builtClasses">
+@if (href()) {
+ <a [href]="href()" [target]="target()" [attr.title]="title()" [ariaLabel]="ariaLabel()" [tabindex]="tabindex()" [ngClass]="builtClasses">
<ng-template *ngTemplateOutlet="content"></ng-template>
</a>
} @else {
- <a [routerLink]="internalLink" [attr.title]="title" [ariaLabel]="ariaLabel" [tabindex]="tabindex" [ngClass]="builtClasses">
+ <a [routerLink]="internalLink()" [attr.title]="title()" [ariaLabel]="ariaLabel()" [tabindex]="tabindex()" [ngClass]="builtClasses">
<ng-template *ngTemplateOutlet="content"></ng-template>
</a>
}
diff --git a/client/src/app/shared/shared-main/common/link.component.ts b/client/src/app/shared/shared-main/common/link.component.ts
index 60bc61199c..2ba779411f 100644
--- a/client/src/app/shared/shared-main/common/link.component.ts
+++ b/client/src/app/shared/shared-main/common/link.component.ts
@@ -1,5 +1,5 @@
import { NgClass, NgIf, NgTemplateOutlet } from '@angular/common'
-import { booleanAttribute, Component, Input, OnInit } from '@angular/core'
+import { booleanAttribute, Component, OnInit, input } from '@angular/core'
import { RouterLink } from '@angular/router'
import { GlobalIconComponent, GlobalIconName } from '@app/shared/shared-icons/global-icon.component'
@@ -10,33 +10,33 @@ import { GlobalIconComponent, GlobalIconName } from '@app/shared/shared-icons/gl
imports: [ NgIf, RouterLink, NgClass, NgTemplateOutlet, GlobalIconComponent ]
})
export class LinkComponent implements OnInit {
- @Input() internalLink?: string | any[]
+ readonly internalLink = input<string | any[]>(undefined)
- @Input() href?: string
- @Input() target = '_self'
+ readonly href = input<string>(undefined)
+ readonly target = input('_self')
- @Input() title?: string
+ readonly title = input<string>(undefined)
- @Input() className?: string
- @Input({ transform: booleanAttribute }) inheritParentStyle = false
- @Input({ transform: booleanAttribute }) inheritParentDimension = false
+ readonly className = input<string>(undefined)
+ readonly inheritParentStyle = input(false, { transform: booleanAttribute })
+ readonly inheritParentDimension = input(false, { transform: booleanAttribute })
- @Input() tabindex: string | number
+ readonly tabindex = input<string | number>(undefined)
- @Input() ariaLabel: string
+ readonly ariaLabel = input<string>(undefined)
- @Input() icon: GlobalIconName
+ readonly icon = input<GlobalIconName>(undefined)
builtClasses: string
ngOnInit () {
- this.builtClasses = this.className || ''
+ this.builtClasses = this.className() || ''
- if (this.inheritParentStyle) {
+ if (this.inheritParentStyle()) {
this.builtClasses += ' inherit-parent-style'
}
- if (this.inheritParentDimension) {
+ if (this.inheritParentDimension()) {
this.builtClasses += ' inherit-parent-dimension'
}
}
diff --git a/client/src/app/shared/shared-main/common/loader.component.ts b/client/src/app/shared/shared-main/common/loader.component.ts
index 6e62cc1a8e..7dd8c38b73 100644
--- a/client/src/app/shared/shared-main/common/loader.component.ts
+++ b/client/src/app/shared/shared-main/common/loader.component.ts
@@ -1,14 +1,14 @@
-import { booleanAttribute, Component, Input } from '@angular/core'
+import { booleanAttribute, Component, input } from '@angular/core'
import { NgIf, NgStyle } from '@angular/common'
@Component({
selector: 'my-loader',
- template: `<div *ngIf="loading" class="spinner-border" [ngStyle]="getStyle()" role="status"></div>`,
+ template: `<div *ngIf="loading()" class="spinner-border" [ngStyle]="getStyle()" role="status"></div>`,
imports: [ NgIf, NgStyle ]
})
export class LoaderComponent {
- @Input({ transform: booleanAttribute }) loading: boolean
- @Input() size: 'sm' | 'xl'
+ readonly loading = input<boolean, unknown>(undefined, { transform: booleanAttribute })
+ readonly size = input<'sm' | 'xl'>(undefined)
private readonly sizes = {
sm: {
@@ -23,8 +23,9 @@ export class LoaderComponent {
}
getStyle () {
- if (!this.size) return undefined
+ const size = this.size()
+ if (!size) return undefined
- return this.sizes[this.size]
+ return this.sizes[size]
}
}
diff --git a/client/src/app/shared/shared-main/common/nl2br.pipe.ts b/client/src/app/shared/shared-main/common/nl2br.pipe.ts
index 4eda930582..7b860b8940 100644
--- a/client/src/app/shared/shared-main/common/nl2br.pipe.ts
+++ b/client/src/app/shared/shared-main/common/nl2br.pipe.ts
@@ -1,4 +1,4 @@
-import { Pipe, PipeTransform } from '@angular/core'
+import { Pipe, PipeTransform, inject } from '@angular/core'
import { HtmlRendererService } from '@app/core'
@Pipe({
@@ -6,10 +6,7 @@ import { HtmlRendererService } from '@app/core'
standalone: true
})
export class Nl2BrPipe implements PipeTransform {
-
- constructor (private htmlRenderer: HtmlRendererService) {
-
- }
+ private htmlRenderer = inject(HtmlRendererService)
transform (value: string): string {
return this.htmlRenderer.convertToBr(value)
diff --git a/client/src/app/shared/shared-main/common/peertube-template.directive.ts b/client/src/app/shared/shared-main/common/peertube-template.directive.ts
index 5d806a7e2a..10d9a7c63a 100644
--- a/client/src/app/shared/shared-main/common/peertube-template.directive.ts
+++ b/client/src/app/shared/shared-main/common/peertube-template.directive.ts
@@ -1,14 +1,12 @@
-import { Directive, Input, TemplateRef } from '@angular/core'
+import { Directive, TemplateRef, inject, input } from '@angular/core'
@Directive({
// eslint-disable-next-line @angular-eslint/directive-selector
selector: '[ptTemplate]',
standalone: true
})
-export class PeerTubeTemplateDirective <T extends string> {
- @Input('ptTemplate') name: T
+export class PeerTubeTemplateDirective<T extends string> {
+ template = inject<TemplateRef<any>>(TemplateRef)
- constructor (public template: TemplateRef<any>) {
- // empty
- }
+ readonly name = input<T>(undefined, { alias: 'ptTemplate' })
}
diff --git a/client/src/app/shared/shared-main/common/progress-bar.component.html b/client/src/app/shared/shared-main/common/progress-bar.component.html
index 5f72093802..4f4d5afe4b 100644
--- a/client/src/app/shared/shared-main/common/progress-bar.component.html
+++ b/client/src/app/shared/shared-main/common/progress-bar.component.html
@@ -1,11 +1,11 @@
<div
- role="progressbar" class="progress-container" tabindex="0" [ngbTooltip]="label"
- [attr.aria-valuenow]="value" aria-valuemin="0" [attr.aria-valuemax]="max"
- [attr.aria-label]="label"
- [ngClass]="{ red: theme === 'red', green: theme === 'green', small: size === 'small' }"
+ role="progressbar" class="progress-container" tabindex="0" [ngbTooltip]="label()"
+ [attr.aria-valuenow]="value()" aria-valuemin="0" [attr.aria-valuemax]="max()"
+ [attr.aria-label]="label()"
+ [ngClass]="{ red: theme() === 'red', green: theme() === 'green', small: size() === 'small' }"
>
<div class="progress-bar" [style]="{ width: percentage() + '%' }"></div>
- <span class="value">{{ valueFormatted }}</span>
- <span class="max" *ngIf="maxFormatted">{{ maxFormatted }}</span>
+ <span class="value">{{ valueFormatted() }}</span>
+ <span class="max" *ngIf="maxFormatted()">{{ maxFormatted() }}</span>
</div>
diff --git a/client/src/app/shared/shared-main/common/progress-bar.component.ts b/client/src/app/shared/shared-main/common/progress-bar.component.ts
index 032a83f453..a907e2ba41 100644
--- a/client/src/app/shared/shared-main/common/progress-bar.component.ts
+++ b/client/src/app/shared/shared-main/common/progress-bar.component.ts
@@ -1,5 +1,5 @@
import { CommonModule } from '@angular/common'
-import { Component, Input, numberAttribute } from '@angular/core'
+import { Component, numberAttribute, input } from '@angular/core'
import { NgbTooltip } from '@ng-bootstrap/ng-bootstrap'
@Component({
@@ -11,23 +11,22 @@ import { NgbTooltip } from '@ng-bootstrap/ng-bootstrap'
NgbTooltip
]
})
-
export class ProgressBarComponent {
- @Input({ required: true, transform: numberAttribute }) value: number
- @Input({ required: true }) label: string
+ readonly value = input.required<number, unknown>({ transform: numberAttribute })
+ readonly label = input.required<string>()
- @Input({ required: true }) valueFormatted: string | number
+ readonly valueFormatted = input.required<string | number>()
- @Input() maxFormatted: string
+ readonly maxFormatted = input<string>(undefined)
- @Input() size: 'normal' | 'small' = 'normal'
+ readonly size = input<'normal' | 'small'>('normal')
- @Input({ transform: numberAttribute }) max = 100
- @Input({ transform: numberAttribute }) min = 0
+ readonly max = input(100, { transform: numberAttribute })
+ readonly min = input(0, { transform: numberAttribute })
- @Input() theme: 'green' | 'red' | 'main' = 'main'
+ readonly theme = input<'green' | 'red' | 'main'>('main')
percentage () {
- return this.value * 100 / this.max
+ return this.value() * 100 / this.max()
}
}
diff --git a/client/src/app/shared/shared-main/custom-page/custom-page.service.ts b/client/src/app/shared/shared-main/custom-page/custom-page.service.ts
index b0af379d2b..6340550fb8 100644
--- a/client/src/app/shared/shared-main/custom-page/custom-page.service.ts
+++ b/client/src/app/shared/shared-main/custom-page/custom-page.service.ts
@@ -1,31 +1,29 @@
import { of } from 'rxjs'
import { catchError } from 'rxjs/operators'
import { HttpClient } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { RestExtractor } from '@app/core'
import { CustomPage } from '@peertube/peertube-models'
import { environment } from '../../../../environments/environment'
@Injectable()
export class CustomPageService {
- static BASE_INSTANCE_HOMEPAGE_URL = environment.apiUrl + '/api/v1/custom-pages/homepage/instance'
+ private authHttp = inject(HttpClient)
+ private restExtractor = inject(RestExtractor)
- constructor (
- private authHttp: HttpClient,
- private restExtractor: RestExtractor
- ) { }
+ static BASE_INSTANCE_HOMEPAGE_URL = environment.apiUrl + '/api/v1/custom-pages/homepage/instance'
getInstanceHomepage () {
return this.authHttp.get<CustomPage>(CustomPageService.BASE_INSTANCE_HOMEPAGE_URL)
- .pipe(
- catchError(err => {
- if (err.status === 404) {
- return of({ content: '' })
- }
+ .pipe(
+ catchError(err => {
+ if (err.status === 404) {
+ return of({ content: '' })
+ }
- return this.restExtractor.handleError(err)
- })
- )
+ return this.restExtractor.handleError(err)
+ })
+ )
}
updateInstanceHomepage (content: string) {
diff --git a/client/src/app/shared/shared-main/date/date-toggle.component.ts b/client/src/app/shared/shared-main/date/date-toggle.component.ts
index f310f88ecf..1f02c5abe0 100644
--- a/client/src/app/shared/shared-main/date/date-toggle.component.ts
+++ b/client/src/app/shared/shared-main/date/date-toggle.component.ts
@@ -1,4 +1,4 @@
-import { Component, Input, OnChanges } from '@angular/core'
+import { Component, OnChanges, inject, input, model } from '@angular/core'
import { FromNowPipe } from './from-now.pipe'
@Component({
@@ -8,24 +8,24 @@ import { FromNowPipe } from './from-now.pipe'
standalone: true
})
export class DateToggleComponent implements OnChanges {
- @Input() date: Date
- @Input() toggled = false
+ private fromNowPipe = inject(FromNowPipe)
+
+ readonly date = input<Date>(undefined)
+ readonly toggled = model(false)
dateRelative: string
dateAbsolute: string
- constructor (private fromNowPipe: FromNowPipe) { }
-
ngOnChanges () {
this.updateDates()
}
toggle () {
- this.toggled = !this.toggled
+ this.toggled.update(toggled => !toggled)
}
getTitle () {
- const target = this.toggled
+ const target = this.toggled()
? this.dateRelative
: this.dateAbsolute
@@ -33,13 +33,13 @@ export class DateToggleComponent implements OnChanges {
}
getContent () {
- return this.toggled
+ return this.toggled()
? this.dateAbsolute
: this.dateRelative
}
private updateDates () {
- this.dateRelative = this.fromNowPipe.transform(this.date)
- this.dateAbsolute = this.date.toLocaleDateString()
+ this.dateRelative = this.fromNowPipe.transform(this.date())
+ this.dateAbsolute = this.date().toLocaleDateString()
}
}
diff --git a/client/src/app/shared/shared-main/feeds/feed.component.html b/client/src/app/shared/shared-main/feeds/feed.component.html
index 7655604cc4..702c265533 100644
--- a/client/src/app/shared/shared-main/feeds/feed.component.html
+++ b/client/src/app/shared/shared-main/feeds/feed.component.html
@@ -1,5 +1,5 @@
<button
- *ngIf="syndicationItems && syndicationItems.length !== 0"
+ *ngIf="syndicationItems() && syndicationItems().length !== 0"
#popover="ngbPopover"
[ngbPopover]="feedsList" [autoClose]="true" placement="bottom left auto"
class="feed border-0 p-0" [title]="getTitle()"
@@ -7,6 +7,6 @@
<my-global-icon iconName="syndication"></my-global-icon>
<ng-template #feedsList>
- <a *ngFor="let item of syndicationItems" class="feed-link" [href]="item.url" target="_blank" rel="noopener noreferrer">{{ item.label }}</a>
+ <a *ngFor="let item of syndicationItems()" class="feed-link" [href]="item.url" target="_blank" rel="noopener noreferrer">{{ item.label }}</a>
</ng-template>
</button>
diff --git a/client/src/app/shared/shared-main/feeds/feed.component.ts b/client/src/app/shared/shared-main/feeds/feed.component.ts
index 018570e466..7740ddc710 100644
--- a/client/src/app/shared/shared-main/feeds/feed.component.ts
+++ b/client/src/app/shared/shared-main/feeds/feed.component.ts
@@ -1,5 +1,5 @@
import { NgFor, NgIf } from '@angular/common'
-import { Component, Input, ViewChild } from '@angular/core'
+import { Component, input, viewChild } from '@angular/core'
import { NgbPopover } from '@ng-bootstrap/ng-bootstrap'
import { GlobalIconComponent } from '../../shared-icons/global-icon.component'
import { Syndication } from './syndication.model'
@@ -11,12 +11,12 @@ import { Syndication } from './syndication.model'
imports: [ NgIf, NgbPopover, GlobalIconComponent, NgFor ]
})
export class FeedComponent {
- @ViewChild('popover') popover: NgbPopover
+ readonly popover = viewChild<NgbPopover>('popover')
- @Input() syndicationItems: Syndication[]
+ readonly syndicationItems = input<Syndication[]>(undefined)
getTitle () {
- if (this.popover?.isOpen()) {
+ if (this.popover()?.isOpen()) {
return $localize`Close syndication dropdown`
}
diff --git a/client/src/app/shared/shared-main/instance/instance.service.ts b/client/src/app/shared/shared-main/instance/instance.service.ts
index 054f04485f..a9bc48535d 100644
--- a/client/src/app/shared/shared-main/instance/instance.service.ts
+++ b/client/src/app/shared/shared-main/instance/instance.service.ts
@@ -1,31 +1,35 @@
import { forkJoin } from 'rxjs'
import { catchError, map } from 'rxjs/operators'
import { HttpClient } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { MarkdownService, RestExtractor, ServerService } from '@app/core'
import { objectKeysTyped, peertubeTranslate } from '@peertube/peertube-core-utils'
import { About } from '@peertube/peertube-models'
import { environment } from '../../../../environments/environment'
import { logger } from '@root-helpers/logger'
-export type AboutHTML = Pick<About['instance'],
-'terms' | 'codeOfConduct' | 'moderationInformation' | 'administrator' | 'creationReason' |
-'maintenanceLifetime' | 'businessModel' | 'hardwareInformation'
+export type AboutHTML = Pick<
+ About['instance'],
+ | 'terms'
+ | 'codeOfConduct'
+ | 'moderationInformation'
+ | 'administrator'
+ | 'creationReason'
+ | 'maintenanceLifetime'
+ | 'businessModel'
+ | 'hardwareInformation'
>
@Injectable()
export class InstanceService {
+ private authHttp = inject(HttpClient)
+ private restExtractor = inject(RestExtractor)
+ private markdownService = inject(MarkdownService)
+ private serverService = inject(ServerService)
+
private static BASE_CONFIG_URL = environment.apiUrl + '/api/v1/config'
private static BASE_SERVER_URL = environment.apiUrl + '/api/v1/server'
- constructor (
- private authHttp: HttpClient,
- private restExtractor: RestExtractor,
- private markdownService: MarkdownService,
- private serverService: ServerService
- ) {
- }
-
getAbout () {
return this.authHttp.get<About>(InstanceService.BASE_CONFIG_URL + '/about')
.pipe(catchError(res => this.restExtractor.handleError(res)))
@@ -74,8 +78,7 @@ export class InstanceService {
}
return this.authHttp.post(InstanceService.BASE_SERVER_URL + '/contact', body)
- .pipe(catchError(res => this.restExtractor.handleError(res)))
-
+ .pipe(catchError(res => this.restExtractor.handleError(res)))
}
async buildHtml (about: About) {
diff --git a/client/src/app/shared/shared-main/menu/horizontal-menu.component.html b/client/src/app/shared/shared-main/menu/horizontal-menu.component.html
index 080c7061de..ed882a0b63 100644
--- a/client/src/app/shared/shared-main/menu/horizontal-menu.component.html
+++ b/client/src/app/shared/shared-main/menu/horizontal-menu.component.html
@@ -1,8 +1,8 @@
-<div class="root" [ngClass]="{ 'with-mb': withMarginBottom }">
- <h1 *ngIf="h1">
- <my-global-icon *ngIf="h1Icon" [iconName]="h1Icon"></my-global-icon>
+<div class="root" [ngClass]="{ 'with-mb': withMarginBottom() }">
+ <h1 *ngIf="h1()">
+ <my-global-icon *ngIf="h1Icon()" [iconName]="h1Icon()"></my-global-icon>
- {{ h1 }}
+ {{ h1() }}
</h1>
<ng-template #entryTemplate let-item="item" let-dropdown="dropdown" let-modal="modal">
@@ -16,8 +16,8 @@
</a>
</ng-template>
- <div [ngClass]="{ 'children-container': areChildren, 'parent-container': !areChildren }">
- <my-list-overflow [items]="menuEntries" [itemTemplate]="entryTemplate" [hasBorder]="!areChildren"></my-list-overflow>
+ <div [ngClass]="{ 'children-container': areChildren(), 'parent-container': !areChildren() }">
+ <my-list-overflow [items]="menuEntries()" [itemTemplate]="entryTemplate" [hasBorder]="!areChildren()"></my-list-overflow>
</div>
@if (children && children.length !== 0) {
diff --git a/client/src/app/shared/shared-main/menu/horizontal-menu.component.ts b/client/src/app/shared/shared-main/menu/horizontal-menu.component.ts
index bdcfbb3ce0..0c7711fce6 100644
--- a/client/src/app/shared/shared-main/menu/horizontal-menu.component.ts
+++ b/client/src/app/shared/shared-main/menu/horizontal-menu.component.ts
@@ -1,5 +1,5 @@
import { CommonModule } from '@angular/common'
-import { booleanAttribute, Component, Input, OnChanges, OnDestroy, OnInit } from '@angular/core'
+import { booleanAttribute, Component, OnChanges, OnDestroy, OnInit, inject, input } from '@angular/core'
import { ActivatedRoute, NavigationEnd, Router, RouterModule } from '@angular/router'
import { GlobalIconComponent, GlobalIconName } from '@app/shared/shared-icons/global-icon.component'
import { logger } from '@root-helpers/logger'
@@ -41,27 +41,23 @@ export type HorizontalMenuEntry = {
]
})
export class HorizontalMenuComponent implements OnInit, OnChanges, OnDestroy {
- @Input() menuEntries: HorizontalMenuEntry[] = []
+ private router = inject(Router)
+ private route = inject(ActivatedRoute)
+ private modal = inject(NgbModal)
- @Input() h1: string
- @Input() h1Icon: GlobalIconName
+ readonly menuEntries = input<HorizontalMenuEntry[]>([])
- @Input({ transform: booleanAttribute }) areChildren = false
- @Input({ transform: booleanAttribute }) withMarginBottom = true
+ readonly h1 = input<string>(undefined)
+ readonly h1Icon = input<GlobalIconName>(undefined)
+
+ readonly areChildren = input(false, { transform: booleanAttribute })
+ readonly withMarginBottom = input(true, { transform: booleanAttribute })
activeParent: HorizontalMenuEntry
children: HorizontalMenuEntry[] = []
private routerSub: Subscription
- constructor (
- private router: Router,
- private route: ActivatedRoute,
- private modal: NgbModal
- ) {
-
- }
-
ngOnInit () {
this.routerSub = this.router.events.pipe(
filter((event: any) => event instanceof NavigationEnd)
@@ -93,7 +89,7 @@ export class HorizontalMenuComponent implements OnInit, OnChanges, OnDestroy {
return a + '/' + c.url[0].path
}, '')
- const entry = this.menuEntries.find(parent => {
+ const entry = this.menuEntries().find(parent => {
if (currentUrl.startsWith(parent.routerLink)) return true
if (!parent.routerLink.startsWith('/') && `${currentComponentPath}/${parent.routerLink}` === currentUrl) return true
@@ -103,8 +99,9 @@ export class HorizontalMenuComponent implements OnInit, OnChanges, OnDestroy {
})
if (!entry) {
- if (this.menuEntries.length !== 0 && currentUrl !== '/') {
- logger.info(`Unable to find entry for ${currentUrl} or ${currentComponentPath}`, { menuEntries: this.menuEntries })
+ const menuEntries = this.menuEntries()
+ if (menuEntries.length !== 0 && currentUrl !== '/') {
+ logger.info(`Unable to find entry for ${currentUrl} or ${currentComponentPath}`, { menuEntries })
}
return
diff --git a/client/src/app/shared/shared-main/menu/list-overflow.component.html b/client/src/app/shared/shared-main/menu/list-overflow.component.html
index ed86bf621b..80cd7d2248 100644
--- a/client/src/app/shared/shared-main/menu/list-overflow.component.html
+++ b/client/src/app/shared/shared-main/menu/list-overflow.component.html
@@ -1,11 +1,11 @@
<div class="root">
- <div #itemsParent class="list-overflow-parent" [ngClass]="{ 'opacity-0': !initialized, 'has-border': hasBorder }">
+ <div #itemsParent class="list-overflow-parent" [ngClass]="{ 'opacity-0': !initialized, 'has-border': hasBorder() }">
<ul class="ul-unstyle d-flex">
- @for (item of items; track item.label; let id = $index) {
+ @for (item of items(); track item.label; let id = $index) {
@if (!item.isDisplayed || item.isDisplayed()) {
<li class="d-inline-block" [id]="getId(id)" #itemsRendered [style]="{ visibility: showItemsUntilIndexExcluded && id >= showItemsUntilIndexExcluded ? 'hidden' : 'inherit' }">
- <ng-container *ngTemplateOutlet="itemTemplate; context: {item: item}"></ng-container>
+ <ng-container *ngTemplateOutlet="itemTemplate(); context: {item: item}"></ng-container>
</li>
}
}
@@ -24,10 +24,10 @@
</button>
<ul class="ul-unstyle" ngbDropdownMenu>
- @for (item of items | slice:showItemsUntilIndexExcluded:items.length; track item.label) {
+ @for (item of items() | slice:showItemsUntilIndexExcluded:items().length; track item.label) {
@if (!item.isDisplayed || item.isDisplayed()) {
<li>
- <ng-container *ngTemplateOutlet="itemTemplate; context: {item: item, dropdown: true}"></ng-container>
+ <ng-container *ngTemplateOutlet="itemTemplate(); context: {item: item, dropdown: true}"></ng-container>
</li>
}
}
@@ -39,10 +39,10 @@
<ng-template #modal let-close="close" let-dismiss="dismiss">
<div class="modal-body">
<ul class="ul-unstyle">
- @for (item of items | slice:showItemsUntilIndexExcluded:items.length; track item.label) {
+ @for (item of items() | slice:showItemsUntilIndexExcluded:items().length; track item.label) {
@if (!item.isDisplayed || item.isDisplayed()) {
<li>
- <ng-container *ngTemplateOutlet="itemTemplate; context: {item: item, modal: true}"></ng-container>
+ <ng-container *ngTemplateOutlet="itemTemplate(); context: {item: item, modal: true}"></ng-container>
</li>
}
}
diff --git a/client/src/app/shared/shared-main/menu/list-overflow.component.ts b/client/src/app/shared/shared-main/menu/list-overflow.component.ts
index 837a82c8f0..8d29e751fa 100644
--- a/client/src/app/shared/shared-main/menu/list-overflow.component.ts
+++ b/client/src/app/shared/shared-main/menu/list-overflow.component.ts
@@ -7,12 +7,12 @@ import {
Component,
ElementRef,
HostListener,
- Input,
OnInit,
- QueryList,
TemplateRef,
- ViewChild,
- ViewChildren
+ inject,
+ input,
+ viewChild,
+ viewChildren
} from '@angular/core'
import { ScreenService } from '@app/core'
import { NgbDropdown, NgbDropdownMenu, NgbDropdownToggle, NgbModal } from '@ng-bootstrap/ng-bootstrap'
@@ -43,13 +43,23 @@ export interface ListOverflowItem {
]
})
export class ListOverflowComponent<T extends ListOverflowItem> implements OnInit, AfterViewInit {
- @Input() items: T[]
- @Input() itemTemplate: TemplateRef<{ item: T, dropdown?: boolean, modal?: boolean }>
- @Input({ transform: booleanAttribute }) hasBorder = false
-
- @ViewChild('modal', { static: true }) modal: ElementRef
- @ViewChild('itemsParent', { static: true }) parent: ElementRef<HTMLDivElement>
- @ViewChildren('itemsRendered') itemsRendered: QueryList<ElementRef>
+ private cdr = inject(ChangeDetectorRef)
+ private modalService = inject(NgbModal)
+ private screenService = inject(ScreenService)
+
+ readonly items = input<T[]>(undefined)
+ readonly itemTemplate = input<
+ TemplateRef<{
+ item: T
+ dropdown?: boolean
+ modal?: boolean
+ }>
+ >(undefined)
+ readonly hasBorder = input(false, { transform: booleanAttribute })
+
+ readonly modal = viewChild<ElementRef>('modal')
+ readonly parent = viewChild<ElementRef<HTMLDivElement>>('itemsParent')
+ readonly itemsRendered = viewChildren<ElementRef>('itemsRendered')
showItemsUntilIndexExcluded: number
isInMobileView = false
@@ -57,12 +67,6 @@ export class ListOverflowComponent<T extends ListOverflowItem> implements OnInit
private randomInt: number
- constructor (
- private cdr: ChangeDetectorRef,
- private modalService: NgbModal,
- private screenService: ScreenService
- ) {}
-
ngOnInit () {
this.randomInt = randomInt(1, 2000)
}
@@ -82,13 +86,13 @@ export class ListOverflowComponent<T extends ListOverflowItem> implements OnInit
onWindowResize () {
this.isInMobileView = !!this.screenService.isInMobileView()
- const parentWidth = this.parent.nativeElement.getBoundingClientRect().width
+ const parentWidth = this.parent().nativeElement.getBoundingClientRect().width
let showItemsUntilIndexExcluded: number
let accWidth = 0
debugLogger('Parent width is %d', parentWidth)
- for (const [ index, el ] of this.itemsRendered.toArray().entries()) {
+ for (const [ index, el ] of this.itemsRendered().entries()) {
accWidth += el.nativeElement.getBoundingClientRect().width
if (showItemsUntilIndexExcluded === undefined) {
@@ -103,7 +107,7 @@ export class ListOverflowComponent<T extends ListOverflowItem> implements OnInit
}
toggleModal () {
- this.modalService.open(this.modal, { centered: true })
+ this.modalService.open(this.modal(), { centered: true })
}
getId (id: number | string = uniqueId()): string {
diff --git a/client/src/app/shared/shared-main/plugins/plugin-placeholder.component.ts b/client/src/app/shared/shared-main/plugins/plugin-placeholder.component.ts
index 2005bf886d..92f4b35d26 100644
--- a/client/src/app/shared/shared-main/plugins/plugin-placeholder.component.ts
+++ b/client/src/app/shared/shared-main/plugins/plugin-placeholder.component.ts
@@ -1,4 +1,4 @@
-import { Component, Input } from '@angular/core'
+import { Component, input } from '@angular/core'
import { PluginElementPlaceholder } from '@peertube/peertube-models'
@Component({
@@ -7,11 +7,10 @@ import { PluginElementPlaceholder } from '@peertube/peertube-models'
styleUrls: [ './plugin-placeholder.component.scss' ],
standalone: true
})
-
export class PluginPlaceholderComponent {
- @Input() pluginId: PluginElementPlaceholder
+ readonly pluginId = input<PluginElementPlaceholder>(undefined)
getId () {
- return 'plugin-placeholder-' + this.pluginId
+ return 'plugin-placeholder-' + this.pluginId()
}
}
diff --git a/client/src/app/shared/shared-main/plugins/plugin-selector.directive.ts b/client/src/app/shared/shared-main/plugins/plugin-selector.directive.ts
index cb6e1552a8..be474e4776 100644
--- a/client/src/app/shared/shared-main/plugins/plugin-selector.directive.ts
+++ b/client/src/app/shared/shared-main/plugins/plugin-selector.directive.ts
@@ -1,4 +1,4 @@
-import { Directive, ElementRef, Input, OnInit, Renderer2 } from '@angular/core'
+import { Directive, ElementRef, OnInit, Renderer2, inject, input } from '@angular/core'
import { PluginSelectorId } from '@peertube/peertube-models'
@Directive({
@@ -6,21 +6,18 @@ import { PluginSelectorId } from '@peertube/peertube-models'
standalone: true
})
export class PluginSelectorDirective implements OnInit {
- @Input() pluginSelectorId: PluginSelectorId
+ private renderer = inject(Renderer2)
+ private hostElement = inject<ElementRef<HTMLElement>>(ElementRef)
- constructor (
- private renderer: Renderer2,
- private hostElement: ElementRef<HTMLElement>
- ) {
-
- }
+ readonly pluginSelectorId = input<PluginSelectorId>(undefined)
ngOnInit () {
- if (!this.pluginSelectorId) return
+ const pluginSelectorId = this.pluginSelectorId()
+ if (!pluginSelectorId) return
const id = this.hostElement.nativeElement.getAttribute('id')
if (id) throw new Error('Cannot set id on element that already has an id')
- this.renderer.setAttribute(this.hostElement.nativeElement, 'id', `plugin-selector-${this.pluginSelectorId}`)
+ this.renderer.setAttribute(this.hostElement.nativeElement, 'id', `plugin-selector-${pluginSelectorId}`)
}
}
diff --git a/client/src/app/shared/shared-main/router/actor-redirect-guard.service.ts b/client/src/app/shared/shared-main/router/actor-redirect-guard.service.ts
index 4ec9e2f62a..4a6efad135 100644
--- a/client/src/app/shared/shared-main/router/actor-redirect-guard.service.ts
+++ b/client/src/app/shared/shared-main/router/actor-redirect-guard.service.ts
@@ -1,18 +1,15 @@
import { forkJoin, of } from 'rxjs'
import { catchError, map } from 'rxjs/operators'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { ActivatedRouteSnapshot, Router } from '@angular/router'
import { AccountService } from '../account/account.service'
import { VideoChannelService } from '../channel/video-channel.service'
@Injectable()
export class ActorRedirectGuard {
-
- constructor (
- private router: Router,
- private accountService: AccountService,
- private channelService: VideoChannelService
- ) {}
+ private router = inject(Router)
+ private accountService = inject(AccountService)
+ private channelService = inject(VideoChannelService)
canActivate (route: ActivatedRouteSnapshot) {
const actorName = route.params.actorName
diff --git a/client/src/app/shared/shared-main/search/simple-search-input.component.html b/client/src/app/shared/shared-main/search/simple-search-input.component.html
index 27830419d1..c3ee024551 100644
--- a/client/src/app/shared/shared-main/search/simple-search-input.component.html
+++ b/client/src/app/shared/shared-main/search/simple-search-input.component.html
@@ -2,7 +2,7 @@
<div class="input-group has-clear" [hidden]="!inputShown">
<input
#ref type="text" class="last-in-group"
- [(ngModel)]="value" (keyup.enter)="sendSearch()" [name]="name" [placeholder]="placeholder"
+ [(ngModel)]="value" (keyup.enter)="sendSearch()" [name]="name()" [placeholder]="placeholder()"
>
<button class="border-0 p-0 form-control-clear" title="Clear filter" i18n-title (click)="onResetFilter()">
@@ -10,11 +10,11 @@
</button>
</div>
- <button class="border-0 p-0 search-button" [title]="iconTitle" (click)="onIconClick()">
+ <button class="border-0 p-0 search-button" [title]="iconTitle()" (click)="onIconClick()">
<my-global-icon iconName="search"></my-global-icon>
</button>
- <button *ngIf="!alwaysShow && inputShown" class="border-0 p-0 close-search-button" i18n-title title="Close search" (click)="hideInput()">
+ <button *ngIf="!alwaysShow() && inputShown" class="border-0 p-0 close-search-button" i18n-title title="Close search" (click)="hideInput()">
<my-global-icon iconName="cross"></my-global-icon>
</button>
</div>
diff --git a/client/src/app/shared/shared-main/search/simple-search-input.component.ts b/client/src/app/shared/shared-main/search/simple-search-input.component.ts
index 2d6e26e8d2..5fc7487598 100644
--- a/client/src/app/shared/shared-main/search/simple-search-input.component.ts
+++ b/client/src/app/shared/shared-main/search/simple-search-input.component.ts
@@ -1,4 +1,4 @@
-import { Component, ElementRef, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core'
+import { Component, ElementRef, OnInit, input, output, viewChild } from '@angular/core'
import { NgIf } from '@angular/common'
import { GlobalIconComponent } from '../../shared-icons/global-icon.component'
import { FormsModule } from '@angular/forms'
@@ -10,15 +10,15 @@ import { FormsModule } from '@angular/forms'
imports: [ FormsModule, GlobalIconComponent, NgIf ]
})
export class SimpleSearchInputComponent implements OnInit {
- @ViewChild('ref') input: ElementRef
+ readonly input = viewChild<ElementRef>('ref')
- @Input() name = 'search'
- @Input() placeholder = $localize`Search`
- @Input() iconTitle = $localize`Search`
- @Input() alwaysShow = true
+ readonly name = input('search')
+ readonly placeholder = input($localize`Search`)
+ readonly iconTitle = input($localize`Search`)
+ readonly alwaysShow = input(true)
- @Output() searchChanged = new EventEmitter<string>()
- @Output() inputDisplayChanged = new EventEmitter<boolean>()
+ readonly searchChanged = output<string>()
+ readonly inputDisplayChanged = output<boolean>()
value = ''
lastSearch = ''
@@ -29,7 +29,7 @@ export class SimpleSearchInputComponent implements OnInit {
}
isInputShown () {
- if (this.alwaysShow) return true
+ if (this.alwaysShow()) return true
return this.inputShown
}
@@ -48,7 +48,7 @@ export class SimpleSearchInputComponent implements OnInit {
this.inputDisplayChanged.emit(this.inputShown)
if (focus) {
- setTimeout(() => this.input.nativeElement.focus())
+ setTimeout(() => this.input().nativeElement.focus())
}
}
@@ -75,7 +75,7 @@ export class SimpleSearchInputComponent implements OnInit {
onResetFilter () {
this.value = ''
- this.input.nativeElement.focus()
+ this.input().nativeElement.focus()
this.sendSearch()
}
diff --git a/client/src/app/shared/shared-main/users/login-link.component.html b/client/src/app/shared/shared-main/users/login-link.component.html
index a8dc2f6614..2755b0bc68 100644
--- a/client/src/app/shared/shared-main/users/login-link.component.html
+++ b/client/src/app/shared/shared-main/users/login-link.component.html
@@ -2,8 +2,8 @@
i18n-title title="Go to the login page"
class="d-flex"
internalLink="/login" [href]="getExternalLoginHref()"
- [className]="className"
- [icon]="icon ? 'sign-in' : undefined"
+ [className]="className()"
+ [icon]="icon() ? 'sign-in' : undefined"
>
- {{ label }}
+ {{ label() }}
</my-link>
diff --git a/client/src/app/shared/shared-main/users/login-link.component.ts b/client/src/app/shared/shared-main/users/login-link.component.ts
index 164afa7c11..70b0612d13 100644
--- a/client/src/app/shared/shared-main/users/login-link.component.ts
+++ b/client/src/app/shared/shared-main/users/login-link.component.ts
@@ -1,4 +1,4 @@
-import { booleanAttribute, Component, Input } from '@angular/core'
+import { booleanAttribute, Component, inject, input } from '@angular/core'
import { ServerService } from '@app/core'
import { PluginsManager } from '@root-helpers/plugins-manager'
import { environment } from 'src/environments/environment'
@@ -11,14 +11,12 @@ import { LinkComponent } from '../common/link.component'
imports: [ LinkComponent ]
})
export class LoginLinkComponent {
- @Input() label = $localize`Login`
- @Input({ transform: booleanAttribute }) icon = false
+ private server = inject(ServerService)
- @Input() className?: string
+ readonly label = input($localize`Login`)
+ readonly icon = input(false, { transform: booleanAttribute })
- constructor (private server: ServerService) {
-
- }
+ readonly className = input<string>(undefined)
getExternalLoginHref () {
return PluginsManager.getDefaultLoginHref(environment.apiUrl, this.server.getHTMLConfig())
diff --git a/client/src/app/shared/shared-main/users/signup-label.component.html b/client/src/app/shared/shared-main/users/signup-label.component.html
index 3311dd6023..5ceae5766f 100644
--- a/client/src/app/shared/shared-main/users/signup-label.component.html
+++ b/client/src/app/shared/shared-main/users/signup-label.component.html
@@ -1,11 +1,11 @@
-@if (withInstanceName) {
- @if (requiresApproval) {
+@if (withInstanceName()) {
+ @if (requiresApproval()) {
<ng-container i18n>Request an account on {{ instanceName }}</ng-container>
} @else {
<ng-container i18n>Create an account on {{ instanceName }}</ng-container>
}
} @else {
- @if (requiresApproval) {
+ @if (requiresApproval()) {
<ng-container i18n>Request an account</ng-container>
} @else {
<ng-container i18n>Create an account</ng-container>
diff --git a/client/src/app/shared/shared-main/users/signup-label.component.ts b/client/src/app/shared/shared-main/users/signup-label.component.ts
index b6f501421a..148124f982 100644
--- a/client/src/app/shared/shared-main/users/signup-label.component.ts
+++ b/client/src/app/shared/shared-main/users/signup-label.component.ts
@@ -1,4 +1,4 @@
-import { booleanAttribute, Component, Input } from '@angular/core'
+import { booleanAttribute, Component, inject, input } from '@angular/core'
import { ServerService } from '@app/core'
@Component({
@@ -7,11 +7,10 @@ import { ServerService } from '@app/core'
imports: []
})
export class SignupLabelComponent {
- @Input({ transform: booleanAttribute }) requiresApproval: boolean
- @Input({ transform: booleanAttribute }) withInstanceName = false
+ private server = inject(ServerService)
- constructor (private server: ServerService) {
- }
+ readonly requiresApproval = input<boolean, unknown>(undefined, { transform: booleanAttribute })
+ readonly withInstanceName = input(false, { transform: booleanAttribute })
get instanceName () {
return this.server.getHTMLConfig().instance.name
diff --git a/client/src/app/shared/shared-main/users/user-history.service.ts b/client/src/app/shared/shared-main/users/user-history.service.ts
index 90a9a0eb97..055bb5103f 100644
--- a/client/src/app/shared/shared-main/users/user-history.service.ts
+++ b/client/src/app/shared/shared-main/users/user-history.service.ts
@@ -1,6 +1,6 @@
import { catchError, switchMap } from 'rxjs/operators'
import { HttpClient, HttpParams } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { ComponentPaginationLight, RestExtractor, RestService } from '@app/core'
import { ResultList } from '@peertube/peertube-models'
import { environment } from '../../../../environments/environment'
@@ -9,14 +9,12 @@ import { VideoService } from '../video/video.service'
@Injectable()
export class UserHistoryService {
- static BASE_USER_VIDEOS_HISTORY_URL = environment.apiUrl + '/api/v1/users/me/history/videos'
+ private authHttp = inject(HttpClient)
+ private restExtractor = inject(RestExtractor)
+ private restService = inject(RestService)
+ private videoService = inject(VideoService)
- constructor (
- private authHttp: HttpClient,
- private restExtractor: RestExtractor,
- private restService: RestService,
- private videoService: VideoService
- ) {}
+ static BASE_USER_VIDEOS_HISTORY_URL = environment.apiUrl + '/api/v1/users/me/history/videos'
list (historyPagination: ComponentPaginationLight, search?: string) {
const pagination = this.restService.componentToRestPagination(historyPagination)
@@ -27,22 +25,22 @@ export class UserHistoryService {
if (search) params = params.append('search', search)
return this.authHttp
- .get<ResultList<Video>>(UserHistoryService.BASE_USER_VIDEOS_HISTORY_URL, { params })
- .pipe(
- switchMap(res => this.videoService.extractVideos(res)),
- catchError(err => this.restExtractor.handleError(err))
- )
+ .get<ResultList<Video>>(UserHistoryService.BASE_USER_VIDEOS_HISTORY_URL, { params })
+ .pipe(
+ switchMap(res => this.videoService.extractVideos(res)),
+ catchError(err => this.restExtractor.handleError(err))
+ )
}
deleteElement (video: Video) {
return this.authHttp
- .delete(UserHistoryService.BASE_USER_VIDEOS_HISTORY_URL + '/' + video.id)
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .delete(UserHistoryService.BASE_USER_VIDEOS_HISTORY_URL + '/' + video.id)
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
clearAll () {
return this.authHttp
- .post(UserHistoryService.BASE_USER_VIDEOS_HISTORY_URL + '/remove', {})
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .post(UserHistoryService.BASE_USER_VIDEOS_HISTORY_URL + '/remove', {})
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
}
diff --git a/client/src/app/shared/shared-main/users/user-notification.service.ts b/client/src/app/shared/shared-main/users/user-notification.service.ts
index 1f7adb9949..c3e433464d 100644
--- a/client/src/app/shared/shared-main/users/user-notification.service.ts
+++ b/client/src/app/shared/shared-main/users/user-notification.service.ts
@@ -1,7 +1,7 @@
import { SortMeta } from 'primeng/api'
import { catchError, map, tap } from 'rxjs/operators'
import { HttpClient, HttpContext, HttpParams } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { AuthService, ComponentPaginationLight, PeerTubeSocket, RestExtractor, RestService } from '@app/core'
import { NGX_LOADING_BAR_IGNORED } from '@ngx-loading-bar/http-client'
import { ResultList, UserNotification as UserNotificationServer, UserNotificationSetting } from '@peertube/peertube-models'
@@ -10,17 +10,15 @@ import { UserNotification } from './user-notification.model'
@Injectable()
export class UserNotificationService {
+ private authHttp = inject(HttpClient)
+ private auth = inject(AuthService)
+ private restExtractor = inject(RestExtractor)
+ private restService = inject(RestService)
+ private peertubeSocket = inject(PeerTubeSocket)
+
static BASE_NOTIFICATIONS_URL = environment.apiUrl + '/api/v1/users/me/notifications'
static BASE_NOTIFICATION_SETTINGS = environment.apiUrl + '/api/v1/users/me/notification-settings'
- constructor (
- private authHttp: HttpClient,
- private auth: AuthService,
- private restExtractor: RestExtractor,
- private restService: RestService,
- private peertubeSocket: PeerTubeSocket
- ) {}
-
listMyNotifications (parameters: {
pagination: ComponentPaginationLight
ignoreLoadingBar?: boolean
@@ -39,10 +37,10 @@ export class UserNotificationService {
: undefined
return this.authHttp.get<ResultList<UserNotification>>(UserNotificationService.BASE_NOTIFICATIONS_URL, { params, context })
- .pipe(
- map(res => this.restExtractor.applyToResultListData(res, this.formatNotification.bind(this))),
- catchError(err => this.restExtractor.handleError(err))
- )
+ .pipe(
+ map(res => this.restExtractor.applyToResultListData(res, this.formatNotification.bind(this))),
+ catchError(err => this.restExtractor.handleError(err))
+ )
}
countUnreadNotifications () {
@@ -57,10 +55,10 @@ export class UserNotificationService {
const context = new HttpContext().set(NGX_LOADING_BAR_IGNORED, true)
return this.authHttp.post(url, body, { context })
- .pipe(
- tap(() => this.peertubeSocket.dispatchNotificationEvent('read')),
- catchError(res => this.restExtractor.handleError(res))
- )
+ .pipe(
+ tap(() => this.peertubeSocket.dispatchNotificationEvent('read')),
+ catchError(res => this.restExtractor.handleError(res))
+ )
}
markAllAsRead () {
@@ -68,17 +66,17 @@ export class UserNotificationService {
const context = new HttpContext().set(NGX_LOADING_BAR_IGNORED, true)
return this.authHttp.post(url, {}, { context })
- .pipe(
- tap(() => this.peertubeSocket.dispatchNotificationEvent('read-all')),
- catchError(res => this.restExtractor.handleError(res))
- )
+ .pipe(
+ tap(() => this.peertubeSocket.dispatchNotificationEvent('read-all')),
+ catchError(res => this.restExtractor.handleError(res))
+ )
}
updateNotificationSettings (settings: UserNotificationSetting) {
const url = UserNotificationService.BASE_NOTIFICATION_SETTINGS
return this.authHttp.put(url, settings)
- .pipe(catchError(res => this.restExtractor.handleError(res)))
+ .pipe(catchError(res => this.restExtractor.handleError(res)))
}
private formatNotification (notification: UserNotificationServer) {
diff --git a/client/src/app/shared/shared-main/users/user-quota.component.ts b/client/src/app/shared/shared-main/users/user-quota.component.ts
index fb32d89ff0..3b74647494 100644
--- a/client/src/app/shared/shared-main/users/user-quota.component.ts
+++ b/client/src/app/shared/shared-main/users/user-quota.component.ts
@@ -1,5 +1,5 @@
import { NgIf } from '@angular/common'
-import { Component, OnInit } from '@angular/core'
+import { Component, OnInit, inject } from '@angular/core'
import { AuthService, UserService } from '@app/core'
import { first } from 'rxjs'
import { BytesPipe } from '../common/bytes.pipe'
@@ -10,8 +10,10 @@ import { ProgressBarComponent } from '../common/progress-bar.component'
templateUrl: './user-quota.component.html',
imports: [ NgIf, BytesPipe, ProgressBarComponent ]
})
-
export class UserQuotaComponent implements OnInit {
+ private userService = inject(UserService)
+ private auth = inject(AuthService)
+
userVideoQuota = '0'
userVideoQuotaUsed = 0
userVideoQuotaPercentage = 15
@@ -20,11 +22,6 @@ export class UserQuotaComponent implements OnInit {
userVideoQuotaUsedDaily = 0
userVideoQuotaDailyPercentage = 15
- constructor (
- private userService: UserService,
- private auth: AuthService
- ) { }
-
get user () {
return this.auth.getUser()
}
diff --git a/client/src/app/shared/shared-main/video-caption/video-caption.service.ts b/client/src/app/shared/shared-main/video-caption/video-caption.service.ts
index a7a288fc3b..dbe49329b9 100644
--- a/client/src/app/shared/shared-main/video-caption/video-caption.service.ts
+++ b/client/src/app/shared/shared-main/video-caption/video-caption.service.ts
@@ -1,5 +1,5 @@
import { HttpClient } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { ConfirmService, RestExtractor, ServerService } from '@app/core'
import { objectToFormData } from '@app/helpers'
import { peertubeTranslate, sortBy } from '@peertube/peertube-core-utils'
@@ -12,41 +12,39 @@ import { VideoCaptionEdit } from './video-caption-edit.model'
@Injectable()
export class VideoCaptionService {
- constructor (
- private authHttp: HttpClient,
- private serverService: ServerService,
- private restExtractor: RestExtractor,
- private confirmService: ConfirmService
- ) {}
+ private authHttp = inject(HttpClient)
+ private serverService = inject(ServerService)
+ private restExtractor = inject(RestExtractor)
+ private confirmService = inject(ConfirmService)
listCaptions (videoId: string, videoPassword?: string): Observable<ResultList<VideoCaption>> {
const headers = VideoPasswordService.buildVideoPasswordHeader(videoPassword)
return this.authHttp.get<ResultList<VideoCaption>>(`${VideoService.BASE_VIDEO_URL}/${videoId}/captions`, { headers })
- .pipe(
- switchMap(captionsResult => {
- return this.serverService.getServerLocale()
- .pipe(map(translations => ({ captionsResult, translations })))
- }),
- map(({ captionsResult, translations }) => {
- for (const c of captionsResult.data) {
- c.language.label = peertubeTranslate(c.language.label, translations)
- }
-
- return captionsResult
- }),
- map(captionsResult => {
- sortBy(captionsResult.data, 'language', 'label')
-
- return captionsResult
- })
- )
- .pipe(catchError(res => this.restExtractor.handleError(res)))
+ .pipe(
+ switchMap(captionsResult => {
+ return this.serverService.getServerLocale()
+ .pipe(map(translations => ({ captionsResult, translations })))
+ }),
+ map(({ captionsResult, translations }) => {
+ for (const c of captionsResult.data) {
+ c.language.label = peertubeTranslate(c.language.label, translations)
+ }
+
+ return captionsResult
+ }),
+ map(captionsResult => {
+ sortBy(captionsResult.data, 'language', 'label')
+
+ return captionsResult
+ })
+ )
+ .pipe(catchError(res => this.restExtractor.handleError(res)))
}
removeCaption (videoId: number | string, language: string) {
return this.authHttp.delete(`${VideoService.BASE_VIDEO_URL}/${videoId}/captions/${language}`)
- .pipe(catchError(res => this.restExtractor.handleError(res)))
+ .pipe(catchError(res => this.restExtractor.handleError(res)))
}
addCaption (videoId: number | string, language: string, captionfile: File) {
@@ -54,7 +52,7 @@ export class VideoCaptionService {
const data = objectToFormData(body)
return this.authHttp.put(`${VideoService.BASE_VIDEO_URL}/${videoId}/captions/${language}`, data)
- .pipe(catchError(res => this.restExtractor.handleError(res)))
+ .pipe(catchError(res => this.restExtractor.handleError(res)))
}
updateCaptions (videoId: number | string, videoCaptions: VideoCaptionEdit[]) {
diff --git a/client/src/app/shared/shared-main/video/embed.component.ts b/client/src/app/shared/shared-main/video/embed.component.ts
index 248416a745..d52cf3e44b 100644
--- a/client/src/app/shared/shared-main/video/embed.component.ts
+++ b/client/src/app/shared/shared-main/video/embed.component.ts
@@ -1,5 +1,5 @@
import { environment } from 'src/environments/environment'
-import { Component, ElementRef, Input, OnInit, booleanAttribute } from '@angular/core'
+import { Component, ElementRef, OnInit, booleanAttribute, inject, input } from '@angular/core'
import { DomSanitizer, SafeHtml } from '@angular/platform-browser'
import { buildVideoOrPlaylistEmbed } from '@root-helpers/video'
import { buildVideoEmbedLink, decorateVideoLink } from '@peertube/peertube-core-utils'
@@ -14,33 +14,29 @@ export type EmbedVideoInput = Pick<Video, 'name' | 'uuid'> & Partial<Pick<Video,
standalone: true
})
export class EmbedComponent implements OnInit {
- @Input({ required: true }) video: EmbedVideoInput
- @Input({ transform: booleanAttribute }) enableAPI: boolean
- @Input({ transform: booleanAttribute }) mute: boolean
- @Input({ transform: booleanAttribute }) autoplay: boolean
+ private sanitizer = inject(DomSanitizer)
+ private el = inject(ElementRef)
- embedHTML: SafeHtml
-
- constructor (
- private sanitizer: DomSanitizer,
- private el: ElementRef
- ) {
+ readonly video = input.required<EmbedVideoInput>()
+ readonly enableAPI = input<boolean, unknown>(undefined, { transform: booleanAttribute })
+ readonly mute = input<boolean, unknown>(undefined, { transform: booleanAttribute })
+ readonly autoplay = input<boolean, unknown>(undefined, { transform: booleanAttribute })
- }
+ embedHTML: SafeHtml
ngOnInit () {
const html = buildVideoOrPlaylistEmbed({
embedUrl: decorateVideoLink({
- url: buildVideoEmbedLink(this.video, environment.originServerUrl),
+ url: buildVideoEmbedLink(this.video(), environment.originServerUrl),
title: false,
warningTitle: false,
- api: this.enableAPI,
- muted: this.mute,
- autoplay: this.autoplay
+ api: this.enableAPI(),
+ muted: this.mute(),
+ autoplay: this.autoplay()
}),
- embedTitle: this.video.name,
- aspectRatio: this.video.aspectRatio
+ embedTitle: this.video().name,
+ aspectRatio: this.video().aspectRatio
})
this.embedHTML = this.sanitizer.bypassSecurityTrustHtml(html)
diff --git a/client/src/app/shared/shared-main/video/redundancy.service.ts b/client/src/app/shared/shared-main/video/redundancy.service.ts
index e017003ff0..65d15e9e49 100644
--- a/client/src/app/shared/shared-main/video/redundancy.service.ts
+++ b/client/src/app/shared/shared-main/video/redundancy.service.ts
@@ -2,20 +2,18 @@ import { SortMeta } from 'primeng/api'
import { concat, Observable } from 'rxjs'
import { catchError, toArray } from 'rxjs/operators'
import { HttpClient, HttpParams } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { RestExtractor, RestPagination, RestService } from '@app/core'
import { ResultList, Video, VideoRedundanciesTarget, VideoRedundancy } from '@peertube/peertube-models'
import { environment } from '../../../../environments/environment'
@Injectable()
export class RedundancyService {
- static BASE_REDUNDANCY_URL = environment.apiUrl + '/api/v1/server/redundancy'
+ private authHttp = inject(HttpClient)
+ private restService = inject(RestService)
+ private restExtractor = inject(RestExtractor)
- constructor (
- private authHttp: HttpClient,
- private restService: RestService,
- private restExtractor: RestExtractor
- ) { }
+ static BASE_REDUNDANCY_URL = environment.apiUrl + '/api/v1/server/redundancy'
updateRedundancy (host: string, redundancyAllowed: boolean) {
const url = RedundancyService.BASE_REDUNDANCY_URL + '/' + host
@@ -23,7 +21,7 @@ export class RedundancyService {
const body = { redundancyAllowed }
return this.authHttp.put(url, body)
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
listVideoRedundancies (options: {
@@ -39,9 +37,9 @@ export class RedundancyService {
if (target) params = params.append('target', target)
return this.authHttp.get<ResultList<VideoRedundancy>>(RedundancyService.BASE_REDUNDANCY_URL + '/videos', { params })
- .pipe(
- catchError(res => this.restExtractor.handleError(res))
- )
+ .pipe(
+ catchError(res => this.restExtractor.handleError(res))
+ )
}
addVideoRedundancy (video: Video) {
@@ -61,6 +59,6 @@ export class RedundancyService {
private removeRedundancy (redundancyId: number) {
return this.authHttp.delete(RedundancyService.BASE_REDUNDANCY_URL + '/videos/' + redundancyId)
- .pipe(catchError(res => this.restExtractor.handleError(res)))
+ .pipe(catchError(res => this.restExtractor.handleError(res)))
}
}
diff --git a/client/src/app/shared/shared-main/video/video-chapter.service.ts b/client/src/app/shared/shared-main/video/video-chapter.service.ts
index 6d221c9e96..2f5b220011 100644
--- a/client/src/app/shared/shared-main/video/video-chapter.service.ts
+++ b/client/src/app/shared/shared-main/video/video-chapter.service.ts
@@ -1,6 +1,6 @@
import { catchError } from 'rxjs/operators'
import { HttpClient } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { RestExtractor } from '@app/core'
import { VideoChapter, VideoChapterUpdate } from '@peertube/peertube-models'
import { VideoPasswordService } from './video-password.service'
@@ -10,11 +10,8 @@ import { of } from 'rxjs'
@Injectable()
export class VideoChapterService {
-
- constructor (
- private authHttp: HttpClient,
- private restExtractor: RestExtractor
- ) {}
+ private authHttp = inject(HttpClient)
+ private restExtractor = inject(RestExtractor)
getChapters (options: { videoId: string, videoPassword?: string }) {
const headers = VideoPasswordService.buildVideoPasswordHeader(options.videoPassword)
diff --git a/client/src/app/shared/shared-main/video/video-file-token.service.ts b/client/src/app/shared/shared-main/video/video-file-token.service.ts
index 87a9528958..04a26d9870 100644
--- a/client/src/app/shared/shared-main/video/video-file-token.service.ts
+++ b/client/src/app/shared/shared-main/video/video-file-token.service.ts
@@ -1,6 +1,6 @@
import { catchError, map, of, tap } from 'rxjs'
import { HttpClient } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { RestExtractor } from '@app/core'
import { VideoToken } from '@peertube/peertube-models'
import { VideoService } from './video.service'
@@ -8,14 +8,11 @@ import { VideoPasswordService } from './video-password.service'
@Injectable()
export class VideoFileTokenService {
+ private authHttp = inject(HttpClient)
+ private restExtractor = inject(RestExtractor)
private readonly store = new Map<string, { token: string, expires: Date }>()
- constructor (
- private authHttp: HttpClient,
- private restExtractor: RestExtractor
- ) {}
-
getVideoFileToken ({ videoUUID, videoPassword }: { videoUUID: string, videoPassword?: string }) {
const existing = this.store.get(videoUUID)
if (existing) return of(existing)
diff --git a/client/src/app/shared/shared-main/video/video-import.service.ts b/client/src/app/shared/shared-main/video/video-import.service.ts
index 05101d72d7..a876fb96d7 100644
--- a/client/src/app/shared/shared-main/video/video-import.service.ts
+++ b/client/src/app/shared/shared-main/video/video-import.service.ts
@@ -2,7 +2,7 @@ import { SortMeta } from 'primeng/api'
import { Observable } from 'rxjs'
import { catchError, map, switchMap } from 'rxjs/operators'
import { HttpClient, HttpParams } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { RestExtractor, RestPagination, RestService, ServerService, UserService } from '@app/core'
import { objectToFormData } from '@app/helpers'
import { peertubeTranslate } from '@peertube/peertube-core-utils'
@@ -11,14 +11,12 @@ import { environment } from '../../../../environments/environment'
@Injectable()
export class VideoImportService {
- private static BASE_VIDEO_IMPORT_URL = environment.apiUrl + '/api/v1/videos/imports/'
+ private authHttp = inject(HttpClient)
+ private restService = inject(RestService)
+ private restExtractor = inject(RestExtractor)
+ private serverService = inject(ServerService)
- constructor (
- private authHttp: HttpClient,
- private restService: RestService,
- private restExtractor: RestExtractor,
- private serverService: ServerService
- ) {}
+ private static BASE_VIDEO_IMPORT_URL = environment.apiUrl + '/api/v1/videos/imports/'
importVideoUrl (targetUrl: string, video: VideoUpdate): Observable<VideoImport> {
const url = VideoImportService.BASE_VIDEO_IMPORT_URL
@@ -28,7 +26,7 @@ export class VideoImportService {
const data = objectToFormData(body)
return this.authHttp.post<VideoImport>(url, data)
- .pipe(catchError(res => this.restExtractor.handleError(res)))
+ .pipe(catchError(res => this.restExtractor.handleError(res)))
}
importVideoTorrent (target: string | Blob, video: VideoUpdate): Observable<VideoImport> {
@@ -40,7 +38,7 @@ export class VideoImportService {
const data = objectToFormData(body)
return this.authHttp.post<VideoImport>(url, data)
- .pipe(catchError(res => this.restExtractor.handleError(res)))
+ .pipe(catchError(res => this.restExtractor.handleError(res)))
}
getMyVideoImports (pagination: RestPagination, sort: SortMeta, search?: string): Observable<ResultList<VideoImport>> {
@@ -61,21 +59,21 @@ export class VideoImportService {
}
return this.authHttp
- .get<ResultList<VideoImport>>(UserService.BASE_USERS_URL + 'me/videos/imports', { params })
- .pipe(
- switchMap(res => this.extractVideoImports(res)),
- catchError(err => this.restExtractor.handleError(err))
- )
+ .get<ResultList<VideoImport>>(UserService.BASE_USERS_URL + 'me/videos/imports', { params })
+ .pipe(
+ switchMap(res => this.extractVideoImports(res)),
+ catchError(err => this.restExtractor.handleError(err))
+ )
}
deleteVideoImport (videoImport: VideoImport) {
return this.authHttp.delete(VideoImportService.BASE_VIDEO_IMPORT_URL + videoImport.id)
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
cancelVideoImport (videoImport: VideoImport) {
return this.authHttp.post(VideoImportService.BASE_VIDEO_IMPORT_URL + videoImport.id + '/cancel', {})
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
private buildImportVideoObject (video: VideoUpdate): VideoImportCreate {
@@ -110,14 +108,12 @@ export class VideoImportService {
private extractVideoImports (result: ResultList<VideoImport>): Observable<ResultList<VideoImport>> {
return this.serverService.getServerLocale()
- .pipe(
- map(translations => {
- result.data.forEach(d =>
- d.state.label = peertubeTranslate(d.state.label, translations)
- )
-
- return result
- })
- )
+ .pipe(
+ map(translations => {
+ result.data.forEach(d => d.state.label = peertubeTranslate(d.state.label, translations))
+
+ return result
+ })
+ )
}
}
diff --git a/client/src/app/shared/shared-main/video/video-ownership.service.ts b/client/src/app/shared/shared-main/video/video-ownership.service.ts
index 03bdea14cc..b912a0b1c1 100644
--- a/client/src/app/shared/shared-main/video/video-ownership.service.ts
+++ b/client/src/app/shared/shared-main/video/video-ownership.service.ts
@@ -2,21 +2,18 @@ import { SortMeta } from 'primeng/api'
import { Observable } from 'rxjs'
import { catchError } from 'rxjs/operators'
import { HttpClient, HttpParams } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { RestExtractor, RestPagination, RestService } from '@app/core'
import { ResultList, VideoChangeOwnership, VideoChangeOwnershipAccept, VideoChangeOwnershipCreate } from '@peertube/peertube-models'
import { environment } from '../../../../environments/environment'
@Injectable()
export class VideoOwnershipService {
- private static BASE_VIDEO_CHANGE_OWNERSHIP_URL = environment.apiUrl + '/api/v1/videos/'
+ private authHttp = inject(HttpClient)
+ private restService = inject(RestService)
+ private restExtractor = inject(RestExtractor)
- constructor (
- private authHttp: HttpClient,
- private restService: RestService,
- private restExtractor: RestExtractor
- ) {
- }
+ private static BASE_VIDEO_CHANGE_OWNERSHIP_URL = environment.apiUrl + '/api/v1/videos/'
changeOwnership (id: number, username: string) {
const url = VideoOwnershipService.BASE_VIDEO_CHANGE_OWNERSHIP_URL + id + '/give-ownership'
diff --git a/client/src/app/shared/shared-main/video/video-password.service.ts b/client/src/app/shared/shared-main/video/video-password.service.ts
index 156efd60fa..7cbae247a4 100644
--- a/client/src/app/shared/shared-main/video/video-password.service.ts
+++ b/client/src/app/shared/shared-main/video/video-password.service.ts
@@ -1,5 +1,5 @@
import { ResultList, VideoPassword } from '@peertube/peertube-models'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { catchError, switchMap } from 'rxjs'
import { HttpClient, HttpHeaders } from '@angular/common/http'
import { RestExtractor } from '@app/core'
@@ -7,11 +7,8 @@ import { VideoService } from './video.service'
@Injectable()
export class VideoPasswordService {
-
- constructor (
- private authHttp: HttpClient,
- private restExtractor: RestExtractor
- ) {}
+ private authHttp = inject(HttpClient)
+ private restExtractor = inject(RestExtractor)
static buildVideoPasswordHeader (videoPassword: string) {
return videoPassword
diff --git a/client/src/app/shared/shared-main/video/video.resolver.ts b/client/src/app/shared/shared-main/video/video.resolver.ts
index dc07bb5daf..7250bea5f1 100644
--- a/client/src/app/shared/shared-main/video/video.resolver.ts
+++ b/client/src/app/shared/shared-main/video/video.resolver.ts
@@ -1,13 +1,10 @@
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { ActivatedRouteSnapshot } from '@angular/router'
import { VideoService } from './video.service'
@Injectable()
export class VideoResolver {
- constructor (
- private videoService: VideoService
- ) {
- }
+ private videoService = inject(VideoService)
resolve (route: ActivatedRouteSnapshot) {
const videoId: string = route.params['videoId']
diff --git a/client/src/app/shared/shared-main/video/video.service.ts b/client/src/app/shared/shared-main/video/video.service.ts
index 89a4361457..a586d9fcaf 100644
--- a/client/src/app/shared/shared-main/video/video.service.ts
+++ b/client/src/app/shared/shared-main/video/video.service.ts
@@ -1,5 +1,5 @@
import { HttpClient, HttpParams, HttpRequest } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { AuthService, ComponentPaginationLight, ConfirmService, RestExtractor, RestService, ServerService, UserService } from '@app/core'
import { objectToFormData } from '@app/helpers'
import { arrayify, buildDownloadFilesUrl } from '@peertube/peertube-core-utils'
@@ -57,20 +57,18 @@ export type CommonVideoParams = {
@Injectable()
export class VideoService {
+ private auth = inject(AuthService)
+ private authHttp = inject(HttpClient)
+ private restExtractor = inject(RestExtractor)
+ private restService = inject(RestService)
+ private serverService = inject(ServerService)
+ private confirmService = inject(ConfirmService)
+
static BASE_VIDEO_URL = environment.apiUrl + '/api/v1/videos'
static BASE_FEEDS_URL = environment.apiUrl + '/feeds/videos.'
static PODCAST_FEEDS_URL = environment.apiUrl + '/feeds/podcast/videos.xml'
static BASE_SUBSCRIPTION_FEEDS_URL = environment.apiUrl + '/feeds/subscriptions.'
- constructor (
- private auth: AuthService,
- private authHttp: HttpClient,
- private restExtractor: RestExtractor,
- private restService: RestService,
- private serverService: ServerService,
- private confirmService: ConfirmService
- ) {}
-
getVideoViewUrl (uuid: string) {
return `${VideoService.BASE_VIDEO_URL}/${uuid}/views`
}
@@ -124,15 +122,15 @@ export class VideoService {
const data = objectToFormData(body)
return this.authHttp.put(`${VideoService.BASE_VIDEO_URL}/${video.id}`, data)
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
uploadVideo (video: FormData) {
const req = new HttpRequest('POST', `${VideoService.BASE_VIDEO_URL}/upload`, video, { reportProgress: true })
return this.authHttp
- .request<{ video: { id: number, uuid: string } }>(req)
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .request<{ video: { id: number, uuid: string } }>(req)
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
getMyVideos (options: {
@@ -170,43 +168,47 @@ export class VideoService {
}
return this.authHttp
- .get<ResultList<Video>>(UserService.BASE_USERS_URL + 'me/videos', { params })
- .pipe(
- switchMap(res => this.extractVideos(res)),
- catchError(err => this.restExtractor.handleError(err))
- )
+ .get<ResultList<Video>>(UserService.BASE_USERS_URL + 'me/videos', { params })
+ .pipe(
+ switchMap(res => this.extractVideos(res)),
+ catchError(err => this.restExtractor.handleError(err))
+ )
}
- getAccountVideos (parameters: CommonVideoParams & {
- account: Pick<Account, 'nameWithHost'>
- }): Observable<ResultList<Video>> {
+ getAccountVideos (
+ parameters: CommonVideoParams & {
+ account: Pick<Account, 'nameWithHost'>
+ }
+ ): Observable<ResultList<Video>> {
const { account } = parameters
let params = new HttpParams()
params = this.buildCommonVideosParams({ params, ...parameters })
return this.authHttp
- .get<ResultList<Video>>(AccountService.BASE_ACCOUNT_URL + account.nameWithHost + '/videos', { params })
- .pipe(
- switchMap(res => this.extractVideos(res)),
- catchError(err => this.restExtractor.handleError(err))
- )
+ .get<ResultList<Video>>(AccountService.BASE_ACCOUNT_URL + account.nameWithHost + '/videos', { params })
+ .pipe(
+ switchMap(res => this.extractVideos(res)),
+ catchError(err => this.restExtractor.handleError(err))
+ )
}
- getVideoChannelVideos (parameters: CommonVideoParams & {
- videoChannel: Pick<VideoChannel, 'nameWithHost'>
- }): Observable<ResultList<Video>> {
+ getVideoChannelVideos (
+ parameters: CommonVideoParams & {
+ videoChannel: Pick<VideoChannel, 'nameWithHost'>
+ }
+ ): Observable<ResultList<Video>> {
const { videoChannel } = parameters
let params = new HttpParams()
params = this.buildCommonVideosParams({ params, ...parameters })
return this.authHttp
- .get<ResultList<Video>>(VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannel.nameWithHost + '/videos', { params })
- .pipe(
- switchMap(res => this.extractVideos(res)),
- catchError(err => this.restExtractor.handleError(err))
- )
+ .get<ResultList<Video>>(VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannel.nameWithHost + '/videos', { params })
+ .pipe(
+ switchMap(res => this.extractVideos(res)),
+ catchError(err => this.restExtractor.handleError(err))
+ )
}
getVideos (parameters: CommonVideoParams): Observable<ResultList<Video>> {
@@ -214,11 +216,11 @@ export class VideoService {
params = this.buildCommonVideosParams({ params, ...parameters })
return this.authHttp
- .get<ResultList<Video>>(VideoService.BASE_VIDEO_URL, { params })
- .pipe(
- switchMap(res => this.extractVideos(res)),
- catchError(err => this.restExtractor.handleError(err))
- )
+ .get<ResultList<Video>>(VideoService.BASE_VIDEO_URL, { params })
+ .pipe(
+ switchMap(res => this.extractVideos(res)),
+ catchError(err => this.restExtractor.handleError(err))
+ )
}
buildBaseFeedUrls (params: HttpParams, base = VideoService.BASE_FEEDS_URL) {
@@ -295,10 +297,10 @@ export class VideoService {
getVideoFileMetadata (metadataUrl: string) {
return this.authHttp
- .get<VideoFileMetadata>(metadataUrl)
- .pipe(
- catchError(err => this.restExtractor.handleError(err))
- )
+ .get<VideoFileMetadata>(metadataUrl)
+ .pipe(
+ catchError(err => this.restExtractor.handleError(err))
+ )
}
removeVideo (idArg: number | number[]) {
@@ -415,16 +417,16 @@ export class VideoService {
getSource (videoId: number) {
return this.authHttp
- .get<VideoSource>(VideoService.BASE_VIDEO_URL + '/' + videoId + '/source')
- .pipe(
- catchError(err => {
- if (err.status === 404) {
- return of(undefined)
- }
+ .get<VideoSource>(VideoService.BASE_VIDEO_URL + '/' + videoId + '/source')
+ .pipe(
+ catchError(err => {
+ if (err.status === 404) {
+ return of(undefined)
+ }
- return this.restExtractor.handleError(err)
- })
- )
+ return this.restExtractor.handleError(err)
+ })
+ )
}
// ---------------------------------------------------------------------------
@@ -447,24 +449,24 @@ export class VideoService {
const url = UserService.BASE_USERS_URL + 'me/videos/' + id + '/rating'
return this.authHttp.get<UserVideoRate>(url)
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
extractVideos (result: ResultList<VideoServerModel>) {
return this.serverService.getServerLocale()
- .pipe(
- map(translations => {
- const videosJson = result.data
- const totalVideos = result.total
- const videos: Video[] = []
+ .pipe(
+ map(translations => {
+ const videosJson = result.data
+ const totalVideos = result.total
+ const videos: Video[] = []
- for (const videoJson of videosJson) {
- videos.push(new Video(videoJson, translations))
- }
+ for (const videoJson of videosJson) {
+ videos.push(new Video(videoJson, translations))
+ }
- return { total: totalVideos, data: videos }
- })
- )
+ return { total: totalVideos, data: videos }
+ })
+ )
}
explainedPrivacyLabels (serverPrivacies: VideoConstant<VideoPrivacyType>[], defaultPrivacyId: VideoPrivacyType = VideoPrivacy.PUBLIC) {
@@ -598,7 +600,7 @@ export class VideoService {
const headers = VideoPasswordService.buildVideoPasswordHeader(videoPassword)
return this.authHttp
- .put(url, body, { headers })
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .put(url, body, { headers })
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
}
diff --git a/client/src/app/shared/shared-moderation/abuse.service.ts b/client/src/app/shared/shared-moderation/abuse.service.ts
index d245441e0e..4bc3499b26 100644
--- a/client/src/app/shared/shared-moderation/abuse.service.ts
+++ b/client/src/app/shared/shared-moderation/abuse.service.ts
@@ -3,7 +3,7 @@ import { SortMeta } from 'primeng/api'
import { Observable } from 'rxjs'
import { catchError } from 'rxjs/operators'
import { HttpClient, HttpParams } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { RestExtractor, RestPagination, RestService } from '@app/core'
import {
AbuseCreate,
@@ -20,15 +20,13 @@ import { environment } from '../../../environments/environment'
@Injectable()
export class AbuseService {
+ private authHttp = inject(HttpClient)
+ private restService = inject(RestService)
+ private restExtractor = inject(RestExtractor)
+
private static BASE_ABUSE_URL = environment.apiUrl + '/api/v1/abuses'
private static BASE_MY_ABUSE_URL = environment.apiUrl + '/api/v1/users/me/abuses'
- constructor (
- private authHttp: HttpClient,
- private restService: RestService,
- private restExtractor: RestExtractor
- ) { }
-
getAdminAbuses (options: {
pagination: RestPagination
sort: SortMeta
@@ -98,23 +96,23 @@ export class AbuseService {
const url = AbuseService.BASE_ABUSE_URL + '/' + abuse.id + '/messages'
return this.authHttp.post(url, { message })
- .pipe(catchError(res => this.restExtractor.handleError(res)))
+ .pipe(catchError(res => this.restExtractor.handleError(res)))
}
listAbuseMessages (abuse: UserAbuse) {
const url = AbuseService.BASE_ABUSE_URL + '/' + abuse.id + '/messages'
return this.authHttp.get<ResultList<AbuseMessage>>(url)
- .pipe(
- catchError(res => this.restExtractor.handleError(res))
- )
+ .pipe(
+ catchError(res => this.restExtractor.handleError(res))
+ )
}
deleteAbuseMessage (abuse: UserAbuse, abuseMessage: AbuseMessage) {
const url = AbuseService.BASE_ABUSE_URL + '/' + abuse.id + '/messages/' + abuseMessage.id
return this.authHttp.delete(url)
- .pipe(catchError(res => this.restExtractor.handleError(res)))
+ .pipe(catchError(res => this.restExtractor.handleError(res)))
}
getPrefefinedReasons (type: AbuseFilter) {
@@ -132,14 +130,16 @@ export class AbuseService {
{
id: 'spamOrMisleading',
label: $localize`Spam, ad or false news`,
- // eslint-disable-next-line max-len
- help: $localize`Contains marketing, spam, purposefully deceitful news, or otherwise misleading thumbnail/text/tags. Please provide reputable sources to report hoaxes.`
+ help:
+ // eslint-disable-next-line max-len
+ $localize`Contains marketing, spam, purposefully deceitful news, or otherwise misleading thumbnail/text/tags. Please provide reputable sources to report hoaxes.`
},
{
id: 'privacy',
label: $localize`Privacy breach or doxxing`,
- // eslint-disable-next-line max-len
- help: $localize`Contains personal information that could be used to track, identify, contact or impersonate someone (e.g. name, address, phone number, email, or credit card details).`
+ help:
+ // eslint-disable-next-line max-len
+ $localize`Contains personal information that could be used to track, identify, contact or impersonate someone (e.g. name, address, phone number, email, or credit card details).`
},
{
id: 'rights',
@@ -149,8 +149,9 @@ export class AbuseService {
{
id: 'serverRules',
label: $localize`Breaks server rules`,
- // eslint-disable-next-line max-len
- help: $localize`Anything not included in the above that breaks the terms of service, code of conduct, or general rules in place on the server.`
+ help:
+ // eslint-disable-next-line max-len
+ $localize`Anything not included in the above that breaks the terms of service, code of conduct, or general rules in place on the server.`
}
]
diff --git a/client/src/app/shared/shared-moderation/account-block-badges.component.html b/client/src/app/shared/shared-moderation/account-block-badges.component.html
index fd37096762..7629429acd 100644
--- a/client/src/app/shared/shared-moderation/account-block-badges.component.html
+++ b/client/src/app/shared/shared-moderation/account-block-badges.component.html
@@ -1,4 +1,4 @@
-<span *ngIf="account.mutedByUser" class="pt-badge badge-danger" i18n>Muted</span>
-<span *ngIf="account.mutedServerByUser" class="pt-badge badge-danger" i18n>Instance muted</span>
-<span *ngIf="account.mutedByInstance" class="pt-badge badge-danger" i18n>Muted by your instance</span>
-<span *ngIf="account.mutedServerByInstance" class="pt-badge badge-danger" i18n>Instance muted by your instance</span>
+<span *ngIf="account().mutedByUser" class="pt-badge badge-danger" i18n>Muted</span>
+<span *ngIf="account().mutedServerByUser" class="pt-badge badge-danger" i18n>Instance muted</span>
+<span *ngIf="account().mutedByInstance" class="pt-badge badge-danger" i18n>Muted by your instance</span>
+<span *ngIf="account().mutedServerByInstance" class="pt-badge badge-danger" i18n>Instance muted by your instance</span>
diff --git a/client/src/app/shared/shared-moderation/account-block-badges.component.ts b/client/src/app/shared/shared-moderation/account-block-badges.component.ts
index 76e59872c1..d716fc5617 100644
--- a/client/src/app/shared/shared-moderation/account-block-badges.component.ts
+++ b/client/src/app/shared/shared-moderation/account-block-badges.component.ts
@@ -1,4 +1,4 @@
-import { Component, Input } from '@angular/core'
+import { Component, input } from '@angular/core'
import { NgIf } from '@angular/common'
import { Account } from '../shared-main/account/account.model'
@@ -9,5 +9,5 @@ import { Account } from '../shared-main/account/account.model'
imports: [ NgIf ]
})
export class AccountBlockBadgesComponent {
- @Input() account: Account
+ readonly account = input<Account>(undefined)
}
diff --git a/client/src/app/shared/shared-moderation/account-blocklist.component.ts b/client/src/app/shared/shared-moderation/account-blocklist.component.ts
index 8fb1806e75..5ae91e70a9 100644
--- a/client/src/app/shared/shared-moderation/account-blocklist.component.ts
+++ b/client/src/app/shared/shared-moderation/account-blocklist.component.ts
@@ -1,5 +1,5 @@
import { SortMeta } from 'primeng/api'
-import { Directive, OnInit } from '@angular/core'
+import { Directive, OnInit, inject } from '@angular/core'
import { Notifier, RestPagination, RestTable } from '@app/core'
import { AccountBlock } from './account-block.model'
import { BlocklistComponentType, BlocklistService } from './blocklist.service'
@@ -7,6 +7,9 @@ import { BlocklistComponentType, BlocklistService } from './blocklist.service'
@Directive()
// eslint-disable-next-line @angular-eslint/directive-class-suffix
export class GenericAccountBlocklistComponent extends RestTable implements OnInit {
+ private notifier = inject(Notifier)
+ private blocklistService = inject(BlocklistService)
+
// @ts-expect-error: "Abstract methods can only appear within an abstract class"
abstract mode: BlocklistComponentType
@@ -15,13 +18,6 @@ export class GenericAccountBlocklistComponent extends RestTable implements OnIni
sort: SortMeta = { field: 'createdAt', order: -1 }
pagination: RestPagination = { count: this.rowsPerPage, start: 0 }
- constructor (
- private notifier: Notifier,
- private blocklistService: BlocklistService
- ) {
- super()
- }
-
// @ts-expect-error: "Abstract methods can only appear within an abstract class"
abstract getIdentifier (): string
diff --git a/client/src/app/shared/shared-moderation/batch-domains-modal.component.html b/client/src/app/shared/shared-moderation/batch-domains-modal.component.html
index ddb27d7fa4..014692520e 100644
--- a/client/src/app/shared/shared-moderation/batch-domains-modal.component.html
+++ b/client/src/app/shared/shared-moderation/batch-domains-modal.component.html
@@ -1,6 +1,6 @@
<ng-template #modal>
<div class="modal-header">
- <h4 class="modal-title">{{ action }}</h4>
+ <h4 class="modal-title">{{ action() }}</h4>
<button class="border-0 p-0" title="Close this modal" i18n-title (click)="hide()">
<my-global-icon iconName="cross"></my-global-icon>
@@ -13,7 +13,7 @@
<label i18n for="hosts">1 host (without "http://") per line</label>
<textarea
- [placeholder]="placeholder" formControlName="hosts" type="text" id="hosts" name="hosts"
+ [placeholder]="placeholder()" formControlName="hosts" type="text" id="hosts" name="hosts"
class="form-control" [ngClass]="{ 'input-error': formErrors['hosts'] }" ngbAutofocus
></textarea>
@@ -34,7 +34,7 @@
(click)="hide()" (key.enter)="hide()"
>
- <input type="submit" [value]="action" class="peertube-button primary-button" [disabled]="!form.valid" />
+ <input type="submit" [value]="action()" class="peertube-button primary-button" [disabled]="!form.valid" />
</div>
</form>
</div>
diff --git a/client/src/app/shared/shared-moderation/batch-domains-modal.component.ts b/client/src/app/shared/shared-moderation/batch-domains-modal.component.ts
index 856c3ddd4f..6a1ac8e91d 100644
--- a/client/src/app/shared/shared-moderation/batch-domains-modal.component.ts
+++ b/client/src/app/shared/shared-moderation/batch-domains-modal.component.ts
@@ -1,5 +1,5 @@
import { NgClass, NgIf } from '@angular/common'
-import { Component, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core'
+import { Component, OnInit, inject, input, output, viewChild } from '@angular/core'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { FormReactive } from '@app/shared/shared-forms/form-reactive'
import { FormReactiveService } from '@app/shared/shared-forms/form-reactive.service'
@@ -16,30 +16,24 @@ import { GlobalIconComponent } from '../shared-icons/global-icon.component'
imports: [ GlobalIconComponent, FormsModule, ReactiveFormsModule, NgClass, NgIf ]
})
export class BatchDomainsModalComponent extends FormReactive implements OnInit {
- @ViewChild('modal', { static: true }) modal: NgbModal
- @Input() placeholder = 'example.com'
- @Input() action: string
- @Output() domains = new EventEmitter<string[]>()
+ protected formReactiveService = inject(FormReactiveService)
+ private modalService = inject(NgbModal)
- private openedModal: NgbModalRef
+ readonly modal = viewChild<NgbModal>('modal')
+ readonly placeholder = input('example.com')
+ readonly action = input<string>($localize`Process domains`)
+ readonly domains = output<string[]>()
- constructor (
- protected formReactiveService: FormReactiveService,
- private modalService: NgbModal
- ) {
- super()
- }
+ private openedModal: NgbModalRef
ngOnInit () {
- if (!this.action) this.action = $localize`Process domains`
-
this.buildForm({
hosts: UNIQUE_HOSTS_VALIDATOR
})
}
openModal () {
- this.openedModal = this.modalService.open(this.modal, { centered: true })
+ this.openedModal = this.modalService.open(this.modal(), { centered: true })
}
hide () {
diff --git a/client/src/app/shared/shared-moderation/blocklist.service.ts b/client/src/app/shared/shared-moderation/blocklist.service.ts
index 477e212139..c57a44d31a 100644
--- a/client/src/app/shared/shared-moderation/blocklist.service.ts
+++ b/client/src/app/shared/shared-moderation/blocklist.service.ts
@@ -2,7 +2,7 @@ import { SortMeta } from 'primeng/api'
import { from } from 'rxjs'
import { catchError, concatMap, map, toArray } from 'rxjs/operators'
import { HttpClient, HttpParams } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { RestExtractor, RestPagination, RestService } from '@app/core'
import { arrayify } from '@peertube/peertube-core-utils'
import { AccountBlock as AccountBlockServer, BlockStatus, ResultList, ServerBlock } from '@peertube/peertube-models'
@@ -10,20 +10,21 @@ import { environment } from '../../../environments/environment'
import { Account } from '../shared-main/account/account.model'
import { AccountBlock } from './account-block.model'
-export enum BlocklistComponentType { Account, Instance }
+export enum BlocklistComponentType {
+ Account,
+ Instance
+}
@Injectable()
export class BlocklistService {
+ private authHttp = inject(HttpClient)
+ private restExtractor = inject(RestExtractor)
+ private restService = inject(RestService)
+
static BASE_BLOCKLIST_URL = environment.apiUrl + '/api/v1/blocklist'
static BASE_USER_BLOCKLIST_URL = environment.apiUrl + '/api/v1/users/me/blocklist'
static BASE_SERVER_BLOCKLIST_URL = environment.apiUrl + '/api/v1/server/blocklist'
- constructor (
- private authHttp: HttpClient,
- private restExtractor: RestExtractor,
- private restService: RestService
- ) { }
-
/** ********************* Blocklist status ***********************/
getStatus (options: {
@@ -52,24 +53,24 @@ export class BlocklistService {
if (search) params = params.append('search', search)
return this.authHttp.get<ResultList<AccountBlock>>(BlocklistService.BASE_USER_BLOCKLIST_URL + '/accounts', { params })
- .pipe(
- map(res => this.restExtractor.applyToResultListData(res, this.formatAccountBlock.bind(this))),
- catchError(err => this.restExtractor.handleError(err))
- )
+ .pipe(
+ map(res => this.restExtractor.applyToResultListData(res, this.formatAccountBlock.bind(this))),
+ catchError(err => this.restExtractor.handleError(err))
+ )
}
blockAccountByUser (account: Pick<Account, 'nameWithHost'>) {
const body = { accountName: account.nameWithHost }
return this.authHttp.post(BlocklistService.BASE_USER_BLOCKLIST_URL + '/accounts', body)
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
unblockAccountByUser (account: Pick<Account, 'nameWithHost'>) {
const path = BlocklistService.BASE_USER_BLOCKLIST_URL + '/accounts/' + account.nameWithHost
return this.authHttp.delete(path)
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
/** ********************* User -> Server blocklist ***********************/
@@ -83,21 +84,21 @@ export class BlocklistService {
if (search) params = params.append('search', search)
return this.authHttp.get<ResultList<ServerBlock>>(BlocklistService.BASE_USER_BLOCKLIST_URL + '/servers', { params })
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
blockServerByUser (host: string) {
const body = { host }
return this.authHttp.post(BlocklistService.BASE_USER_BLOCKLIST_URL + '/servers', body)
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
unblockServerByUser (host: string) {
const path = BlocklistService.BASE_USER_BLOCKLIST_URL + '/servers/' + host
return this.authHttp.delete(path)
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
/** ********************* Instance -> Account blocklist ***********************/
@@ -111,10 +112,10 @@ export class BlocklistService {
if (search) params = params.append('search', search)
return this.authHttp.get<ResultList<AccountBlock>>(BlocklistService.BASE_SERVER_BLOCKLIST_URL + '/accounts', { params })
- .pipe(
- map(res => this.restExtractor.applyToResultListData(res, this.formatAccountBlock.bind(this))),
- catchError(err => this.restExtractor.handleError(err))
- )
+ .pipe(
+ map(res => this.restExtractor.applyToResultListData(res, this.formatAccountBlock.bind(this))),
+ catchError(err => this.restExtractor.handleError(err))
+ )
}
blockAccountByInstance (accountsArg: Pick<Account, 'nameWithHost'> | Pick<Account, 'nameWithHost'>[]) {
@@ -132,7 +133,7 @@ export class BlocklistService {
const path = BlocklistService.BASE_SERVER_BLOCKLIST_URL + '/accounts/' + account.nameWithHost
return this.authHttp.delete(path)
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
/** ********************* Instance -> Server blocklist ***********************/
@@ -146,21 +147,21 @@ export class BlocklistService {
if (search) params = params.append('search', search)
return this.authHttp.get<ResultList<ServerBlock>>(BlocklistService.BASE_SERVER_BLOCKLIST_URL + '/servers', { params })
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
blockServerByInstance (host: string) {
const body = { host }
return this.authHttp.post(BlocklistService.BASE_SERVER_BLOCKLIST_URL + '/servers', body)
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
unblockServerByInstance (host: string) {
const path = BlocklistService.BASE_SERVER_BLOCKLIST_URL + '/servers/' + host
return this.authHttp.delete(path)
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
private formatAccountBlock (accountBlock: AccountBlockServer) {
diff --git a/client/src/app/shared/shared-moderation/bulk.service.ts b/client/src/app/shared/shared-moderation/bulk.service.ts
index 36d1b0b1ed..696225d706 100644
--- a/client/src/app/shared/shared-moderation/bulk.service.ts
+++ b/client/src/app/shared/shared-moderation/bulk.service.ts
@@ -1,23 +1,21 @@
import { catchError } from 'rxjs/operators'
import { HttpClient } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { RestExtractor } from '@app/core'
import { BulkRemoveCommentsOfBody } from '@peertube/peertube-models'
import { environment } from '../../../environments/environment'
@Injectable()
export class BulkService {
- static BASE_BULK_URL = environment.apiUrl + '/api/v1/bulk'
+ private authHttp = inject(HttpClient)
+ private restExtractor = inject(RestExtractor)
- constructor (
- private authHttp: HttpClient,
- private restExtractor: RestExtractor
- ) { }
+ static BASE_BULK_URL = environment.apiUrl + '/api/v1/bulk'
removeCommentsOf (body: BulkRemoveCommentsOfBody) {
const url = BulkService.BASE_BULK_URL + '/remove-comments-of'
return this.authHttp.post(url, body)
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
}
diff --git a/client/src/app/shared/shared-moderation/report-modals/account-report.component.ts b/client/src/app/shared/shared-moderation/report-modals/account-report.component.ts
index a60c71fa84..57c29bc740 100644
--- a/client/src/app/shared/shared-moderation/report-modals/account-report.component.ts
+++ b/client/src/app/shared/shared-moderation/report-modals/account-report.component.ts
@@ -1,5 +1,5 @@
import { mapValues, pickBy } from 'lodash-es'
-import { Component, OnInit, ViewChild } from '@angular/core'
+import { Component, OnInit, inject, viewChild } from '@angular/core'
import { Notifier } from '@app/core'
import { ABUSE_REASON_VALIDATOR } from '@app/shared/form-validators/abuse-validators'
import { FormReactive } from '@app/shared/shared-forms/form-reactive'
@@ -32,7 +32,12 @@ import { Account } from '@app/shared/shared-main/account/account.model'
]
})
export class AccountReportComponent extends FormReactive implements OnInit {
- @ViewChild('modal', { static: true }) modal: NgbModal
+ protected formReactiveService = inject(FormReactiveService)
+ private modalService = inject(NgbModal)
+ private abuseService = inject(AbuseService)
+ private notifier = inject(Notifier)
+
+ readonly modal = viewChild<NgbModal>('modal')
error: string = null
predefinedReasons: { id: AbusePredefinedReasonsString, label: string, description?: string, help?: string }[] = []
@@ -41,15 +46,6 @@ export class AccountReportComponent extends FormReactive implements OnInit {
private openedModal: NgbModalRef
- constructor (
- protected formReactiveService: FormReactiveService,
- private modalService: NgbModal,
- private abuseService: AbuseService,
- private notifier: Notifier
- ) {
- super()
- }
-
get currentHost () {
return window.location.host
}
@@ -76,7 +72,7 @@ export class AccountReportComponent extends FormReactive implements OnInit {
this.modalTitle = $localize`Report ${this.account.displayName}`
- this.openedModal = this.modalService.open(this.modal, { centered: true, keyboard: false, size: 'lg' })
+ this.openedModal = this.modalService.open(this.modal(), { centered: true, keyboard: false, size: 'lg' })
}
hide () {
diff --git a/client/src/app/shared/shared-moderation/report-modals/comment-report.component.ts b/client/src/app/shared/shared-moderation/report-modals/comment-report.component.ts
index 990dbd642f..8ee8886588 100644
--- a/client/src/app/shared/shared-moderation/report-modals/comment-report.component.ts
+++ b/client/src/app/shared/shared-moderation/report-modals/comment-report.component.ts
@@ -1,5 +1,5 @@
import { mapValues, pickBy } from 'lodash-es'
-import { Component, Input, OnInit, ViewChild } from '@angular/core'
+import { Component, OnInit, inject, input, viewChild } from '@angular/core'
import { Notifier } from '@app/core'
import { ABUSE_REASON_VALIDATOR } from '@app/shared/form-validators/abuse-validators'
import { FormReactive } from '@app/shared/shared-forms/form-reactive'
@@ -32,9 +32,14 @@ import { VideoComment } from '@app/shared/shared-video-comment/video-comment.mod
]
})
export class CommentReportComponent extends FormReactive implements OnInit {
- @Input() comment: VideoComment = null
+ protected formReactiveService = inject(FormReactiveService)
+ private modalService = inject(NgbModal)
+ private abuseService = inject(AbuseService)
+ private notifier = inject(Notifier)
- @ViewChild('modal', { static: true }) modal: NgbModal
+ readonly comment = input<VideoComment>(null)
+
+ readonly modal = viewChild<NgbModal>('modal')
modalTitle: string
error: string = null
@@ -42,22 +47,13 @@ export class CommentReportComponent extends FormReactive implements OnInit {
private openedModal: NgbModalRef
- constructor (
- protected formReactiveService: FormReactiveService,
- private modalService: NgbModal,
- private abuseService: AbuseService,
- private notifier: Notifier
- ) {
- super()
- }
-
get currentHost () {
return window.location.host
}
get originHost () {
if (this.isRemote()) {
- return this.comment.account.host
+ return this.comment().account.host
}
return ''
@@ -75,7 +71,7 @@ export class CommentReportComponent extends FormReactive implements OnInit {
}
show () {
- this.openedModal = this.modalService.open(this.modal, { centered: true, keyboard: false, size: 'lg' })
+ this.openedModal = this.modalService.open(this.modal(), { centered: true, keyboard: false, size: 'lg' })
}
hide () {
@@ -91,7 +87,7 @@ export class CommentReportComponent extends FormReactive implements OnInit {
reason,
predefinedReasons,
comment: {
- id: this.comment.id
+ id: this.comment().id
}
}).subscribe({
next: () => {
@@ -104,6 +100,6 @@ export class CommentReportComponent extends FormReactive implements OnInit {
}
isRemote () {
- return !this.comment.isLocal
+ return !this.comment().isLocal
}
}
diff --git a/client/src/app/shared/shared-moderation/report-modals/video-report.component.html b/client/src/app/shared/shared-moderation/report-modals/video-report.component.html
index 2aee483124..e2d3677531 100644
--- a/client/src/app/shared/shared-moderation/report-modals/video-report.component.html
+++ b/client/src/app/shared/shared-moderation/report-modals/video-report.component.html
@@ -1,6 +1,6 @@
<ng-template #modal>
<div class="modal-header">
- <h4 i18n class="modal-title">Report video "{{ video.name }}"</h4>
+ <h4 i18n class="modal-title">Report video "{{ video().name }}"</h4>
<button class="border-0 p-0" title="Close this modal" i18n-title (click)="hide()">
<my-global-icon iconName="cross"></my-global-icon>
</button>
@@ -33,7 +33,7 @@
</div>
<div class="col-12 col-md-7">
- <my-embed [video]="video"></my-embed>
+ <my-embed [video]="video()"></my-embed>
<div class="mb-1 mt-3 start-at" formGroupName="timestamp">
<my-peertube-checkbox
@@ -43,7 +43,7 @@
<my-timestamp-input
[timestamp]="timestamp.startAt"
- [maxTimestamp]="video.duration"
+ [maxTimestamp]="video().duration"
formControlName="startAt"
inputName="startAt"
>
@@ -58,7 +58,7 @@
<my-timestamp-input
[timestamp]="timestamp.endAt"
- [maxTimestamp]="video.duration"
+ [maxTimestamp]="video().duration"
formControlName="endAt"
inputName="endAt"
>
diff --git a/client/src/app/shared/shared-moderation/report-modals/video-report.component.ts b/client/src/app/shared/shared-moderation/report-modals/video-report.component.ts
index 8689a32330..82bef131c0 100644
--- a/client/src/app/shared/shared-moderation/report-modals/video-report.component.ts
+++ b/client/src/app/shared/shared-moderation/report-modals/video-report.component.ts
@@ -1,5 +1,5 @@
import { mapValues, pickBy } from 'lodash-es'
-import { Component, Input, OnInit, ViewChild } from '@angular/core'
+import { Component, OnInit, inject, input, viewChild } from '@angular/core'
import { Notifier } from '@app/core'
import { ABUSE_REASON_VALIDATOR } from '@app/shared/form-validators/abuse-validators'
import { FormReactive } from '@app/shared/shared-forms/form-reactive'
@@ -36,31 +36,27 @@ import { Video } from '@app/shared/shared-main/video/video.model'
]
})
export class VideoReportComponent extends FormReactive implements OnInit {
- @Input() video: Video = null
+ protected formReactiveService = inject(FormReactiveService)
+ private modalService = inject(NgbModal)
+ private abuseService = inject(AbuseService)
+ private notifier = inject(Notifier)
- @ViewChild('modal', { static: true }) modal: NgbModal
+ readonly video = input<Video>(null)
+
+ readonly modal = viewChild<NgbModal>('modal')
error: string = null
predefinedReasons: { id: AbusePredefinedReasonsString, label: string, description?: string, help?: string }[] = []
private openedModal: NgbModalRef
- constructor (
- protected formReactiveService: FormReactiveService,
- private modalService: NgbModal,
- private abuseService: AbuseService,
- private notifier: Notifier
- ) {
- super()
- }
-
get currentHost () {
return window.location.host
}
get originHost () {
if (this.isRemote()) {
- return this.video.account.host
+ return this.video().account.host
}
return ''
@@ -86,7 +82,7 @@ export class VideoReportComponent extends FormReactive implements OnInit {
}
show () {
- this.openedModal = this.modalService.open(this.modal, { centered: true, keyboard: false, size: 'lg' })
+ this.openedModal = this.modalService.open(this.modal(), { centered: true, keyboard: false, size: 'lg' })
}
hide () {
@@ -103,7 +99,7 @@ export class VideoReportComponent extends FormReactive implements OnInit {
reason,
predefinedReasons,
video: {
- id: this.video.id,
+ id: this.video().id,
startAt: hasStart && startAt ? startAt : undefined,
endAt: hasEnd && endAt ? endAt : undefined
}
@@ -118,6 +114,6 @@ export class VideoReportComponent extends FormReactive implements OnInit {
}
isRemote () {
- return !this.video.isLocal
+ return !this.video().isLocal
}
}
diff --git a/client/src/app/shared/shared-moderation/server-blocklist.component.ts b/client/src/app/shared/shared-moderation/server-blocklist.component.ts
index 75fa955d3c..e5f90ff340 100644
--- a/client/src/app/shared/shared-moderation/server-blocklist.component.ts
+++ b/client/src/app/shared/shared-moderation/server-blocklist.component.ts
@@ -1,5 +1,5 @@
import { SortMeta } from 'primeng/api'
-import { Directive, OnInit, ViewChild } from '@angular/core'
+import { Directive, OnInit, inject, viewChild } from '@angular/core'
import { Notifier, RestPagination, RestTable } from '@app/core'
import { BatchDomainsModalComponent } from '@app/shared/shared-moderation/batch-domains-modal.component'
import { ServerBlock } from '@peertube/peertube-models'
@@ -8,7 +8,10 @@ import { BlocklistComponentType, BlocklistService } from './blocklist.service'
@Directive()
// eslint-disable-next-line @angular-eslint/directive-class-suffix
export class GenericServerBlocklistComponent extends RestTable implements OnInit {
- @ViewChild('batchDomainsModal') batchDomainsModal: BatchDomainsModalComponent
+ protected notifier = inject(Notifier)
+ protected blocklistService = inject(BlocklistService)
+
+ readonly batchDomainsModal = viewChild<BatchDomainsModalComponent>('batchDomainsModal')
// @ts-expect-error: "Abstract methods can only appear within an abstract class"
public abstract mode: BlocklistComponentType
@@ -18,13 +21,6 @@ export class GenericServerBlocklistComponent extends RestTable implements OnInit
sort: SortMeta = { field: 'createdAt', order: -1 }
pagination: RestPagination = { count: this.rowsPerPage, start: 0 }
- constructor (
- protected notifier: Notifier,
- protected blocklistService: BlocklistService
- ) {
- super()
- }
-
// @ts-expect-error: "Abstract methods can only appear within an abstract class"
public abstract getIdentifier (): string
@@ -33,9 +29,10 @@ export class GenericServerBlocklistComponent extends RestTable implements OnInit
}
unblockServer (serverBlock: ServerBlock) {
- const operation = (host: string) => this.mode === BlocklistComponentType.Account
- ? this.blocklistService.unblockServerByUser(host)
- : this.blocklistService.unblockServerByInstance(host)
+ const operation = (host: string) =>
+ this.mode === BlocklistComponentType.Account
+ ? this.blocklistService.unblockServerByUser(host)
+ : this.blocklistService.unblockServerByInstance(host)
const host = serverBlock.blockedServer.host
operation(host).subscribe(
@@ -52,13 +49,14 @@ export class GenericServerBlocklistComponent extends RestTable implements OnInit
}
addServersToBlock () {
- this.batchDomainsModal.openModal()
+ this.batchDomainsModal().openModal()
}
onDomainsToBlock (domains: string[]) {
- const operation = (domain: string) => this.mode === BlocklistComponentType.Account
- ? this.blocklistService.blockServerByUser(domain)
- : this.blocklistService.blockServerByInstance(domain)
+ const operation = (domain: string) =>
+ this.mode === BlocklistComponentType.Account
+ ? this.blocklistService.blockServerByUser(domain)
+ : this.blocklistService.blockServerByInstance(domain)
domains.forEach(domain => {
operation(domain).subscribe(
diff --git a/client/src/app/shared/shared-moderation/user-ban-modal.component.ts b/client/src/app/shared/shared-moderation/user-ban-modal.component.ts
index e6e5e2081e..c4e2606b9a 100644
--- a/client/src/app/shared/shared-moderation/user-ban-modal.component.ts
+++ b/client/src/app/shared/shared-moderation/user-ban-modal.component.ts
@@ -1,5 +1,5 @@
import { forkJoin } from 'rxjs'
-import { Component, EventEmitter, OnInit, Output, ViewChild } from '@angular/core'
+import { Component, OnInit, inject, output, viewChild } from '@angular/core'
import { Notifier } from '@app/core'
import { formatICU } from '@app/helpers'
import { FormReactive } from '@app/shared/shared-forms/form-reactive'
@@ -23,23 +23,19 @@ import { UserAdminService } from '../shared-users/user-admin.service'
imports: [ GlobalIconComponent, FormsModule, ReactiveFormsModule, NgClass, NgIf, PeertubeCheckboxComponent ]
})
export class UserBanModalComponent extends FormReactive implements OnInit {
- @ViewChild('modal', { static: true }) modal: NgbModal
- @Output() userBanned = new EventEmitter<User | User[]>()
+ protected formReactiveService = inject(FormReactiveService)
+ private modalService = inject(NgbModal)
+ private notifier = inject(Notifier)
+ private userAdminService = inject(UserAdminService)
+ private blocklistService = inject(BlocklistService)
+
+ readonly modal = viewChild<NgbModal>('modal')
+ readonly userBanned = output<User | User[]>()
private usersToBan: User | User[]
private openedModal: NgbModalRef
modalMessage = ''
- constructor (
- protected formReactiveService: FormReactiveService,
- private modalService: NgbModal,
- private notifier: Notifier,
- private userAdminService: UserAdminService,
- private blocklistService: BlocklistService
- ) {
- super()
- }
-
ngOnInit () {
this.buildForm({
reason: USER_BAN_REASON_VALIDATOR,
@@ -49,7 +45,7 @@ export class UserBanModalComponent extends FormReactive implements OnInit {
openModal (user: User | User[]) {
this.usersToBan = user
- this.openedModal = this.modalService.open(this.modal, { centered: true })
+ this.openedModal = this.modalService.open(this.modal(), { centered: true })
}
hide () {
diff --git a/client/src/app/shared/shared-moderation/user-moderation-dropdown.component.html b/client/src/app/shared/shared-moderation/user-moderation-dropdown.component.html
index f1680e385a..018f5f2453 100644
--- a/client/src/app/shared/shared-moderation/user-moderation-dropdown.component.html
+++ b/client/src/app/shared/shared-moderation/user-moderation-dropdown.component.html
@@ -2,8 +2,8 @@
<my-user-ban-modal #userBanModal (userBanned)="onUserBanned()"></my-user-ban-modal>
<my-action-dropdown
- [actions]="userActions" [entry]="{ user: user, account: account }"
- [buttonSize]="buttonSize" [placement]="placement" [label]="label"
- [container]="container" [buttonStyled]="buttonStyled"
+ [actions]="userActions" [entry]="{ user: user(), account: account() }"
+ [buttonSize]="buttonSize()" [placement]="placement()" [label]="label()"
+ [container]="container()" [buttonStyled]="buttonStyled()"
></my-action-dropdown>
</ng-container>
diff --git a/client/src/app/shared/shared-moderation/user-moderation-dropdown.component.ts b/client/src/app/shared/shared-moderation/user-moderation-dropdown.component.ts
index d7806e9104..8e97a1ed9c 100644
--- a/client/src/app/shared/shared-moderation/user-moderation-dropdown.component.ts
+++ b/client/src/app/shared/shared-moderation/user-moderation-dropdown.component.ts
@@ -1,4 +1,4 @@
-import { Component, EventEmitter, Input, OnChanges, OnInit, Output, ViewChild } from '@angular/core'
+import { Component, OnChanges, OnInit, inject, input, output, viewChild } from '@angular/core'
import { AuthService, ConfirmService, HooksService, Notifier, PluginService, ServerService } from '@app/core'
import { BulkRemoveCommentsOfBody, User, UserRight } from '@peertube/peertube-models'
import { BlocklistService } from './blocklist.service'
@@ -9,9 +9,10 @@ import { NgIf } from '@angular/common'
import { Account } from '../shared-main/account/account.model'
import { UserAdminService } from '../shared-users/user-admin.service'
-export type AccountMutedStatus =
- Pick<Account, 'id' | 'nameWithHost' | 'host' | 'userId' |
- 'mutedByInstance' | 'mutedByUser' | 'mutedServerByInstance' | 'mutedServerByUser'>
+export type AccountMutedStatus = Pick<
+ Account,
+ 'id' | 'nameWithHost' | 'host' | 'userId' | 'mutedByInstance' | 'mutedByUser' | 'mutedServerByInstance' | 'mutedServerByUser'
+>
export type UserModerationDisplayType = {
myAccount?: boolean
@@ -25,43 +26,44 @@ export type UserModerationDisplayType = {
imports: [ NgIf, UserBanModalComponent, ActionDropdownComponent ]
})
export class UserModerationDropdownComponent implements OnInit, OnChanges {
- @ViewChild('userBanModal') userBanModal: UserBanModalComponent
-
- @Input() user: User
- @Input() account: AccountMutedStatus
- @Input() prependActions: DropdownAction<{ user: User, account: AccountMutedStatus }>[]
-
- @Input() buttonSize: 'normal' | 'small' = 'normal'
- @Input() buttonStyled = true
- @Input() placement = 'right-top right-bottom auto'
- @Input() label: string
- @Input() container: 'body' | undefined = undefined
-
- @Input() displayOptions: UserModerationDisplayType = {
+ private authService = inject(AuthService)
+ private notifier = inject(Notifier)
+ private confirmService = inject(ConfirmService)
+ private serverService = inject(ServerService)
+ private userAdminService = inject(UserAdminService)
+ private blocklistService = inject(BlocklistService)
+ private bulkService = inject(BulkService)
+ private hooks = inject(HooksService)
+ private pluginService = inject(PluginService)
+
+ readonly userBanModal = viewChild<UserBanModalComponent>('userBanModal')
+
+ readonly user = input<User>(undefined)
+ readonly account = input<AccountMutedStatus>(undefined)
+ readonly prependActions = input<DropdownAction<{
+ user: User
+ account: AccountMutedStatus
+ }>[]>(undefined)
+
+ readonly buttonSize = input<'normal' | 'small'>('normal')
+ readonly buttonStyled = input(true)
+ readonly placement = input('right-top right-bottom auto')
+ readonly label = input<string>(undefined)
+ readonly container = input<'body' | undefined>(undefined)
+
+ readonly displayOptions = input<UserModerationDisplayType>({
myAccount: true,
instanceAccount: true,
instanceUser: true
- }
+ })
- @Output() userChanged = new EventEmitter()
- @Output() userDeleted = new EventEmitter()
+ readonly userChanged = output()
+ readonly userDeleted = output()
userActions: DropdownAction<{ user: User, account: AccountMutedStatus }>[][] = []
requiresEmailVerification = false
- constructor (
- private authService: AuthService,
- private notifier: Notifier,
- private confirmService: ConfirmService,
- private serverService: ServerService,
- private userAdminService: UserAdminService,
- private blocklistService: BlocklistService,
- private bulkService: BulkService,
- private hooks: HooksService,
- private pluginService: PluginService
- ) { }
-
ngOnInit () {
this.serverService.getConfig()
.subscribe(config => this.requiresEmailVerification = config.signup.requiresEmailVerification)
@@ -77,7 +79,7 @@ export class UserModerationDropdownComponent implements OnInit, OnChanges {
return
}
- this.userBanModal.openModal(user)
+ this.userBanModal().openModal(user)
}
onUserBanned () {
@@ -89,14 +91,14 @@ export class UserModerationDropdownComponent implements OnInit, OnChanges {
if (res === false) return
this.userAdminService.unbanUsers(user)
- .subscribe({
- next: () => {
- this.notifier.success($localize`User ${user.username} unbanned.`)
- this.userChanged.emit()
- },
-
- error: err => this.notifier.error(err.message)
- })
+ .subscribe({
+ next: () => {
+ this.notifier.success($localize`User ${user.username} unbanned.`)
+ this.userChanged.emit()
+ },
+
+ error: err => this.notifier.error(err.message)
+ })
}
async removeUser (user: User) {
@@ -105,8 +107,9 @@ export class UserModerationDropdownComponent implements OnInit, OnChanges {
return
}
- // eslint-disable-next-line max-len
- const message = $localize`If you remove this user, you won't be able to create another user or channel with <strong>${user.username}</strong> username!`
+ const message =
+ // eslint-disable-next-line max-len
+ $localize`If you remove this user, you won't be able to create another user or channel with <strong>${user.username}</strong> username!`
const res = await this.confirmService.confirm(message, $localize`Delete ${user.username}`)
if (res === false) return
@@ -135,114 +138,114 @@ export class UserModerationDropdownComponent implements OnInit, OnChanges {
blockAccountByUser (account: AccountMutedStatus) {
this.blocklistService.blockAccountByUser(account)
- .subscribe({
- next: () => {
- this.notifier.success($localize`Account ${account.nameWithHost} muted.`)
+ .subscribe({
+ next: () => {
+ this.notifier.success($localize`Account ${account.nameWithHost} muted.`)
- this.account.mutedByUser = true
- this.userChanged.emit()
- },
+ this.account().mutedByUser = true
+ this.userChanged.emit()
+ },
- error: err => this.notifier.error(err.message)
- })
+ error: err => this.notifier.error(err.message)
+ })
}
unblockAccountByUser (account: AccountMutedStatus) {
this.blocklistService.unblockAccountByUser(account)
- .subscribe({
- next: () => {
- this.notifier.success($localize`Account ${account.nameWithHost} unmuted.`)
+ .subscribe({
+ next: () => {
+ this.notifier.success($localize`Account ${account.nameWithHost} unmuted.`)
- this.account.mutedByUser = false
- this.userChanged.emit()
- },
+ this.account().mutedByUser = false
+ this.userChanged.emit()
+ },
- error: err => this.notifier.error(err.message)
- })
+ error: err => this.notifier.error(err.message)
+ })
}
blockServerByUser (host: string) {
this.blocklistService.blockServerByUser(host)
- .subscribe({
- next: () => {
- this.notifier.success($localize`${host} muted.`)
+ .subscribe({
+ next: () => {
+ this.notifier.success($localize`${host} muted.`)
- this.account.mutedServerByUser = true
- this.userChanged.emit()
- },
+ this.account().mutedServerByUser = true
+ this.userChanged.emit()
+ },
- error: err => this.notifier.error(err.message)
- })
+ error: err => this.notifier.error(err.message)
+ })
}
unblockServerByUser (host: string) {
this.blocklistService.unblockServerByUser(host)
- .subscribe({
- next: () => {
- this.notifier.success($localize`${host} unmuted.`)
+ .subscribe({
+ next: () => {
+ this.notifier.success($localize`${host} unmuted.`)
- this.account.mutedServerByUser = false
- this.userChanged.emit()
- },
+ this.account().mutedServerByUser = false
+ this.userChanged.emit()
+ },
- error: err => this.notifier.error(err.message)
- })
+ error: err => this.notifier.error(err.message)
+ })
}
blockAccountByInstance (account: AccountMutedStatus) {
this.blocklistService.blockAccountByInstance(account)
- .subscribe({
- next: () => {
- this.notifier.success($localize`Account ${account.nameWithHost} muted by your platform.`)
+ .subscribe({
+ next: () => {
+ this.notifier.success($localize`Account ${account.nameWithHost} muted by your platform.`)
- this.account.mutedByInstance = true
- this.userChanged.emit()
- },
+ this.account().mutedByInstance = true
+ this.userChanged.emit()
+ },
- error: err => this.notifier.error(err.message)
- })
+ error: err => this.notifier.error(err.message)
+ })
}
unblockAccountByInstance (account: AccountMutedStatus) {
this.blocklistService.unblockAccountByInstance(account)
- .subscribe({
- next: () => {
- this.notifier.success($localize`Account ${account.nameWithHost} unmuted by your platform.`)
+ .subscribe({
+ next: () => {
+ this.notifier.success($localize`Account ${account.nameWithHost} unmuted by your platform.`)
- this.account.mutedByInstance = false
- this.userChanged.emit()
- },
+ this.account().mutedByInstance = false
+ this.userChanged.emit()
+ },
- error: err => this.notifier.error(err.message)
- })
+ error: err => this.notifier.error(err.message)
+ })
}
blockServerByInstance (host: string) {
this.blocklistService.blockServerByInstance(host)
- .subscribe({
- next: () => {
- this.notifier.success($localize`Instance ${host} muted by the instance.`)
+ .subscribe({
+ next: () => {
+ this.notifier.success($localize`Instance ${host} muted by the instance.`)
- this.account.mutedServerByInstance = true
- this.userChanged.emit()
- },
+ this.account().mutedServerByInstance = true
+ this.userChanged.emit()
+ },
- error: err => this.notifier.error(err.message)
- })
+ error: err => this.notifier.error(err.message)
+ })
}
unblockServerByInstance (host: string) {
this.blocklistService.unblockServerByInstance(host)
- .subscribe({
- next: () => {
- this.notifier.success($localize`Instance ${host} unmuted by the instance.`)
+ .subscribe({
+ next: () => {
+ this.notifier.success($localize`Instance ${host} unmuted by the instance.`)
- this.account.mutedServerByInstance = false
- this.userChanged.emit()
- },
+ this.account().mutedServerByInstance = false
+ this.userChanged.emit()
+ },
- error: err => this.notifier.error(err.message)
- })
+ error: err => this.notifier.error(err.message)
+ })
}
async bulkRemoveCommentsOf (body: BulkRemoveCommentsOfBody) {
@@ -251,13 +254,13 @@ export class UserModerationDropdownComponent implements OnInit, OnChanges {
if (res === false) return
this.bulkService.removeCommentsOf(body)
- .subscribe({
- next: () => {
- this.notifier.success($localize`Will remove comments of this account (may take several minutes).`)
- },
+ .subscribe({
+ next: () => {
+ this.notifier.success($localize`Will remove comments of this account (may take several minutes).`)
+ },
- error: err => this.notifier.error(err.message)
- })
+ error: err => this.notifier.error(err.message)
+ })
}
getRouterUserEditLink (user: User) {
@@ -275,8 +278,9 @@ export class UserModerationDropdownComponent implements OnInit, OnChanges {
private async buildActions () {
const userActions: DropdownAction<{ user: User, account: AccountMutedStatus }>[][] = []
- if (this.prependActions && this.prependActions.length !== 0) {
- userActions.push(this.prependActions)
+ const prependActions = this.prependActions()
+ if (prependActions && prependActions.length !== 0) {
+ userActions.push(prependActions)
}
const myAccountModerationActions = this.buildMyAccountModerationActions()
@@ -289,7 +293,7 @@ export class UserModerationDropdownComponent implements OnInit, OnChanges {
}
private buildMyAccountModerationActions () {
- if (!this.account || !this.displayOptions.myAccount || !this.authService.isLoggedIn()) return []
+ if (!this.account() || !this.displayOptions().myAccount || !this.authService.isLoggedIn()) return []
const myAccountActions: DropdownAction<{ user: User, account: AccountMutedStatus }>[] = [
{
@@ -339,7 +343,9 @@ export class UserModerationDropdownComponent implements OnInit, OnChanges {
let instanceActions: DropdownAction<{ user: User, account: AccountMutedStatus }>[] = []
- if (this.user && this.displayOptions.instanceUser && authUser.hasRight(UserRight.MANAGE_USERS) && authUser.canManage(this.user)) {
+ const displayOptions = this.displayOptions()
+ const userValue = this.user()
+ if (userValue && displayOptions.instanceUser && authUser.hasRight(UserRight.MANAGE_USERS) && authUser.canManage(userValue)) {
instanceActions = instanceActions.concat([
{
label: $localize`Edit user`,
@@ -373,7 +379,8 @@ export class UserModerationDropdownComponent implements OnInit, OnChanges {
}
// Instance actions on account blocklists
- if (this.account && this.displayOptions.instanceAccount && authUser.hasRight(UserRight.MANAGE_ACCOUNTS_BLOCKLIST)) {
+ const accountValue = this.account()
+ if (accountValue && displayOptions.instanceAccount && authUser.hasRight(UserRight.MANAGE_ACCOUNTS_BLOCKLIST)) {
instanceActions = instanceActions.concat([
{
label: $localize`Mute this account`,
@@ -391,7 +398,7 @@ export class UserModerationDropdownComponent implements OnInit, OnChanges {
}
// Instance actions on server blocklists
- if (this.account && this.displayOptions.instanceAccount && authUser.hasRight(UserRight.MANAGE_SERVERS_BLOCKLIST)) {
+ if (accountValue && displayOptions.instanceAccount && authUser.hasRight(UserRight.MANAGE_SERVERS_BLOCKLIST)) {
instanceActions = instanceActions.concat([
{
label: $localize`Mute the platform`,
@@ -408,7 +415,7 @@ export class UserModerationDropdownComponent implements OnInit, OnChanges {
])
}
- if (this.account && this.displayOptions.instanceAccount && authUser.hasRight(UserRight.MANAGE_ANY_VIDEO_COMMENT)) {
+ if (accountValue && displayOptions.instanceAccount && authUser.hasRight(UserRight.MANAGE_ANY_VIDEO_COMMENT)) {
instanceActions = instanceActions.concat([
{
label: $localize`Remove comments from your platform`,
diff --git a/client/src/app/shared/shared-moderation/video-block.component.ts b/client/src/app/shared/shared-moderation/video-block.component.ts
index 646fb59f15..54981dae21 100644
--- a/client/src/app/shared/shared-moderation/video-block.component.ts
+++ b/client/src/app/shared/shared-moderation/video-block.component.ts
@@ -1,4 +1,4 @@
-import { Component, EventEmitter, OnInit, Output, ViewChild } from '@angular/core'
+import { Component, OnInit, inject, output, viewChild } from '@angular/core'
import { Notifier } from '@app/core'
import { formatICU } from '@app/helpers'
import { FormReactive } from '@app/shared/shared-forms/form-reactive'
@@ -20,9 +20,14 @@ import { NgIf, NgClass } from '@angular/common'
imports: [ NgIf, GlobalIconComponent, FormsModule, ReactiveFormsModule, NgClass, PeertubeCheckboxComponent ]
})
export class VideoBlockComponent extends FormReactive implements OnInit {
- @ViewChild('modal', { static: true }) modal: NgbModal
+ protected formReactiveService = inject(FormReactiveService)
+ private modalService = inject(NgbModal)
+ private videoBlocklistService = inject(VideoBlockService)
+ private notifier = inject(Notifier)
- @Output() videoBlocked = new EventEmitter()
+ readonly modal = viewChild<NgbModal>('modal')
+
+ readonly videoBlocked = output()
videos: Video[]
@@ -30,15 +35,6 @@ export class VideoBlockComponent extends FormReactive implements OnInit {
private openedModal: NgbModalRef
- constructor (
- protected formReactiveService: FormReactiveService,
- private modalService: NgbModal,
- private videoBlocklistService: VideoBlockService,
- private notifier: Notifier
- ) {
- super()
- }
-
ngOnInit () {
const defaultValues = { unfederate: 'true' }
@@ -67,7 +63,7 @@ export class VideoBlockComponent extends FormReactive implements OnInit {
show (videos: Video[]) {
this.videos = videos
- this.openedModal = this.modalService.open(this.modal, { centered: true, keyboard: false })
+ this.openedModal = this.modalService.open(this.modal(), { centered: true, keyboard: false })
}
hide () {
@@ -85,27 +81,27 @@ export class VideoBlockComponent extends FormReactive implements OnInit {
}))
this.videoBlocklistService.blockVideo(options)
- .subscribe({
- next: () => {
- const message = formatICU(
- $localize`{count, plural, =1 {Blocked {videoName}.} other {Blocked {count} videos.}}`,
- { count: this.videos.length, videoName: this.getSingleVideo().name }
- )
+ .subscribe({
+ next: () => {
+ const message = formatICU(
+ $localize`{count, plural, =1 {Blocked {videoName}.} other {Blocked {count} videos.}}`,
+ { count: this.videos.length, videoName: this.getSingleVideo().name }
+ )
- this.notifier.success(message)
- this.hide()
+ this.notifier.success(message)
+ this.hide()
- for (const o of options) {
- const video = this.videos.find(v => v.id === o.videoId)
+ for (const o of options) {
+ const video = this.videos.find(v => v.id === o.videoId)
- video.blacklisted = true
- video.blacklistedReason = o.reason
- }
+ video.blacklisted = true
+ video.blacklistedReason = o.reason
+ }
- this.videoBlocked.emit()
- },
+ this.videoBlocked.emit()
+ },
- error: err => this.notifier.error(err.message)
- })
+ error: err => this.notifier.error(err.message)
+ })
}
}
diff --git a/client/src/app/shared/shared-moderation/video-block.service.ts b/client/src/app/shared/shared-moderation/video-block.service.ts
index 18950c92b4..f6bfb517b6 100644
--- a/client/src/app/shared/shared-moderation/video-block.service.ts
+++ b/client/src/app/shared/shared-moderation/video-block.service.ts
@@ -2,7 +2,7 @@ import { SortMeta } from 'primeng/api'
import { from as observableFrom, Observable } from 'rxjs'
import { catchError, concatMap, toArray } from 'rxjs/operators'
import { HttpClient, HttpParams } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { RestExtractor, RestPagination, RestService } from '@app/core'
import { arrayify } from '@peertube/peertube-core-utils'
import { ResultList, VideoBlacklist, VideoBlacklistType, VideoBlacklistType_Type } from '@peertube/peertube-models'
@@ -10,13 +10,11 @@ import { environment } from '../../../environments/environment'
@Injectable()
export class VideoBlockService {
- private static BASE_VIDEOS_URL = environment.apiUrl + '/api/v1/videos/'
+ private authHttp = inject(HttpClient)
+ private restService = inject(RestService)
+ private restExtractor = inject(RestExtractor)
- constructor (
- private authHttp: HttpClient,
- private restService: RestService,
- private restExtractor: RestExtractor
- ) {}
+ private static BASE_VIDEOS_URL = environment.apiUrl + '/api/v1/videos/'
listBlocks (options: {
pagination: RestPagination
@@ -47,7 +45,7 @@ export class VideoBlockService {
if (type) params = params.append('type', type.toString())
return this.authHttp.get<ResultList<VideoBlacklist>>(VideoBlockService.BASE_VIDEOS_URL + 'blacklist', { params })
- .pipe(catchError(res => this.restExtractor.handleError(res)))
+ .pipe(catchError(res => this.restExtractor.handleError(res)))
}
unblockVideo (videoIdArgs: number | number[]) {
diff --git a/client/src/app/shared/shared-plugin-pages/plugin-pages.component.ts b/client/src/app/shared/shared-plugin-pages/plugin-pages.component.ts
index 6948082e8b..573dd68d68 100644
--- a/client/src/app/shared/shared-plugin-pages/plugin-pages.component.ts
+++ b/client/src/app/shared/shared-plugin-pages/plugin-pages.component.ts
@@ -1,4 +1,4 @@
-import { AfterViewInit, Component, ElementRef, OnDestroy, ViewChild } from '@angular/core'
+import { AfterViewInit, Component, ElementRef, OnDestroy, inject, viewChild } from '@angular/core'
import { ActivatedRoute, Router } from '@angular/router'
import { MetaService, PluginService } from '@app/core'
import { logger } from '@root-helpers/logger'
@@ -9,18 +9,14 @@ import { Subscription } from 'rxjs/internal/Subscription'
standalone: true
})
export class PluginPagesComponent implements OnDestroy, AfterViewInit {
- @ViewChild('root') root: ElementRef
+ private metaService = inject(MetaService)
+ private route = inject(ActivatedRoute)
+ private router = inject(Router)
+ private pluginService = inject(PluginService)
- private urlSub: Subscription
-
- constructor (
- private metaService: MetaService,
- private route: ActivatedRoute,
- private router: Router,
- private pluginService: PluginService
- ) {
+ readonly root = viewChild<ElementRef>('root')
- }
+ private urlSub: Subscription
ngAfterViewInit () {
this.urlSub = this.route.url.subscribe(() => {
@@ -71,6 +67,6 @@ export class PluginPagesComponent implements OnDestroy, AfterViewInit {
this.metaService.setTitle(registered.title)
}
- registered.onMount({ rootEl: this.root.nativeElement })
+ registered.onMount({ rootEl: this.root().nativeElement })
}
}
diff --git a/client/src/app/shared/shared-search/find-in-bulk.service.ts b/client/src/app/shared/shared-search/find-in-bulk.service.ts
index 443dd059cc..0e2428d293 100644
--- a/client/src/app/shared/shared-search/find-in-bulk.service.ts
+++ b/client/src/app/shared/shared-search/find-in-bulk.service.ts
@@ -1,7 +1,7 @@
import debug from 'debug'
import { Observable, Subject } from 'rxjs'
import { filter, first, map } from 'rxjs/operators'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { buildBulkObservable } from '@app/helpers'
import { AdvancedSearch } from './advanced-search.model'
import { SearchService } from './search.service'
@@ -11,13 +11,14 @@ import { VideoPlaylist } from '../shared-video-playlist/video-playlist.model'
const debugLogger = debug('peertube:search:FindInBulkService')
-type BulkObservables <P extends number | string, R> = {
+type BulkObservables<P extends number | string, R> = {
notifier: Subject<P>
result: Observable<{ params: P[], response: R }>
}
@Injectable()
export class FindInBulkService {
+ private searchService = inject(SearchService)
private advancedSearchForBulk: AdvancedSearch
@@ -25,9 +26,7 @@ export class FindInBulkService {
private getChannelInBulk: BulkObservables<string, { data: VideoChannel[] }>
private getPlaylistInBulk: BulkObservables<string, { data: VideoPlaylist[] }>
- constructor (
- private searchService: SearchService
- ) {
+ constructor () {
this.getVideoInBulk = this.buildBulkObservableObject(this.getVideosInBulk.bind(this))
this.getChannelInBulk = this.buildBulkObservableObject(this.getChannelsInBulk.bind(this))
this.getPlaylistInBulk = this.buildBulkObservableObject(this.getPlaylistsInBulk.bind(this))
@@ -65,7 +64,7 @@ export class FindInBulkService {
})
}
- private getData <P extends number | string, R> (options: {
+ private getData<P extends number | string, R> (options: {
observableObject: BulkObservables<P, { data: R[] }>
param: P
finder: (d: R) => boolean
@@ -129,7 +128,7 @@ export class FindInBulkService {
})
}
- private buildBulkObservableObject <P extends number | string, R> (bulkGet: (params: P[]) => Observable<R>) {
+ private buildBulkObservableObject<P extends number | string, R> (bulkGet: (params: P[]) => Observable<R>) {
const notifier = new Subject<P>()
return {
diff --git a/client/src/app/shared/shared-search/search.service.ts b/client/src/app/shared/shared-search/search.service.ts
index e184682b64..7958994374 100644
--- a/client/src/app/shared/shared-search/search.service.ts
+++ b/client/src/app/shared/shared-search/search.service.ts
@@ -1,7 +1,7 @@
import { Observable, of } from 'rxjs'
import { catchError, map, switchMap } from 'rxjs/operators'
import { HttpClient, HttpParams } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { ComponentPaginationLight, RestExtractor, RestPagination, RestService } from '@app/core'
import {
ResultList,
@@ -20,15 +20,13 @@ import { VideoPlaylistService } from '../shared-video-playlist/video-playlist.se
@Injectable()
export class SearchService {
- static BASE_SEARCH_URL = environment.apiUrl + '/api/v1/search/'
+ private authHttp = inject(HttpClient)
+ private restExtractor = inject(RestExtractor)
+ private restService = inject(RestService)
+ private videoService = inject(VideoService)
+ private playlistService = inject(VideoPlaylistService)
- constructor (
- private authHttp: HttpClient,
- private restExtractor: RestExtractor,
- private restService: RestService,
- private videoService: VideoService,
- private playlistService: VideoPlaylistService
- ) { }
+ static BASE_SEARCH_URL = environment.apiUrl + '/api/v1/search/'
searchVideos (parameters: {
search?: string
@@ -63,11 +61,11 @@ export class SearchService {
}
return this.authHttp
- .get<ResultList<VideoServerModel>>(url, { params })
- .pipe(
- switchMap(res => this.videoService.extractVideos(res)),
- catchError(err => this.restExtractor.handleError(err))
- )
+ .get<ResultList<VideoServerModel>>(url, { params })
+ .pipe(
+ switchMap(res => this.videoService.extractVideos(res)),
+ catchError(err => this.restExtractor.handleError(err))
+ )
}
searchVideoChannels (parameters: {
@@ -101,11 +99,11 @@ export class SearchService {
}
return this.authHttp
- .get<ResultList<VideoChannelServerModel>>(url, { params })
- .pipe(
- map(res => VideoChannelService.extractVideoChannels(res)),
- catchError(err => this.restExtractor.handleError(err))
- )
+ .get<ResultList<VideoChannelServerModel>>(url, { params })
+ .pipe(
+ map(res => VideoChannelService.extractVideoChannels(res)),
+ catchError(err => this.restExtractor.handleError(err))
+ )
}
searchVideoPlaylists (parameters: {
@@ -139,10 +137,10 @@ export class SearchService {
}
return this.authHttp
- .get<ResultList<VideoPlaylistServerModel>>(url, { params })
- .pipe(
- switchMap(res => this.playlistService.extractPlaylists(res)),
- catchError(err => this.restExtractor.handleError(err))
- )
+ .get<ResultList<VideoPlaylistServerModel>>(url, { params })
+ .pipe(
+ switchMap(res => this.playlistService.extractPlaylists(res)),
+ catchError(err => this.restExtractor.handleError(err))
+ )
}
}
diff --git a/client/src/app/shared/shared-share-modal/video-share.component.html b/client/src/app/shared/shared-share-modal/video-share.component.html
index 5b488651f9..1a61c4049f 100644
--- a/client/src/app/shared/shared-share-modal/video-share.component.html
+++ b/client/src/app/shared/shared-share-modal/video-share.component.html
@@ -10,13 +10,13 @@
<div class="modal-body">
- <div class="playlist" *ngIf="playlist">
- <h5 *ngIf="video" i18n class="text-center mb-4">Share the playlist</h5>
+ <div class="playlist" *ngIf="playlist()">
+ <h5 *ngIf="video()" i18n class="text-center mb-4">Share the playlist</h5>
<my-alert *ngIf="isPrivatePlaylist()" class="alert-private" type="warning">
<div i18n>This playlist is private so you won't be able to share it with external users</div>
- <a i18n class="peertube-button-link primary-button" [routerLink]="[ '/my-library/video-playlists/update', playlist.shortUUID ]" target="_blank" rel="noopener noreferrer">
+ <a i18n class="peertube-button-link primary-button" [routerLink]="[ '/my-library/video-playlists/update', playlist().shortUUID ]" target="_blank" rel="noopener noreferrer">
Update playlist privacy
</a>
</my-alert>
@@ -72,7 +72,7 @@
<div class="filters">
- <div class="form-group" *ngIf="video">
+ <div class="form-group" *ngIf="video()">
<my-peertube-checkbox
inputName="includeVideoInPlaylist" [(ngModel)]="customizations.includeVideoInPlaylist"
i18n-labelText labelText="Share the playlist at this video position"
@@ -100,13 +100,13 @@
</div>
- <div class="video" *ngIf="video">
- <h5 *ngIf="playlist" i18n class="text-center mb-4">Share the video</h5>
+ <div class="video" *ngIf="video()">
+ <h5 *ngIf="playlist()" i18n class="text-center mb-4">Share the video</h5>
<my-alert *ngIf="isPrivateVideo()" class="alert-private" type="warning">
<div i18n>This video is private so you won't be able to share it with external users</div>
- <a i18n class="peertube-button-link primary-button mt-3" [routerLink]="[ '/videos/', 'update', video.shortUUID ]" target="_blank" rel="noopener noreferrer">
+ <a i18n class="peertube-button-link primary-button mt-3" [routerLink]="[ '/videos/', 'update', video().shortUUID ]" target="_blank" rel="noopener noreferrer">
Update video privacy
</a>
</my-alert>
@@ -165,7 +165,7 @@
<div [ngbNavOutlet]="nav"></div>
<div class="filters">
- <div class="form-group start-at" *ngIf="!video.isLive">
+ <div class="form-group start-at" *ngIf="!video().isLive">
<my-peertube-checkbox
inputName="startAt" [(ngModel)]="customizations.startAtCheckbox"
i18n-labelText labelText="Start at"
@@ -173,14 +173,14 @@
<my-timestamp-input
[timestamp]="customizations.startAt"
- [maxTimestamp]="video.duration"
+ [maxTimestamp]="video().duration"
[disabled]="!customizations.startAtCheckbox"
[(ngModel)]="customizations.startAt"
>
</my-timestamp-input>
</div>
- <div *ngIf="videoCaptions.length !== 0" class="form-group video-caption-block">
+ <div *ngIf="videoCaptions().length !== 0" class="form-group video-caption-block">
<my-peertube-checkbox
inputName="subtitleCheckbox" [(ngModel)]="customizations.subtitleCheckbox"
i18n-labelText labelText="Auto select subtitle"
@@ -188,7 +188,7 @@
<div class="peertube-select-container">
<select [(ngModel)]="customizations.subtitle" [disabled]="!customizations.subtitleCheckbox" class="form-control">
- <option *ngFor="let caption of videoCaptions" [value]="caption.language.id">{{ caption.language.label }}</option>
+ <option *ngFor="let caption of videoCaptions()" [value]="caption.language.id">{{ caption.language.label }}</option>
</select>
</div>
</div>
@@ -212,7 +212,7 @@
<my-plugin-placeholder pluginId="share-modal-video-settings"></my-plugin-placeholder>
<div class="advanced-filters" [ngbCollapse]="isAdvancedCustomizationCollapsed" [animation]="true">
- <div class="form-group stop-at" *ngIf="!video.isLive">
+ <div class="form-group stop-at" *ngIf="!video().isLive">
<my-peertube-checkbox
inputName="stopAt" [(ngModel)]="customizations.stopAtCheckbox"
i18n-labelText labelText="Stop at"
@@ -220,7 +220,7 @@
<my-timestamp-input
[timestamp]="customizations.stopAt"
- [maxTimestamp]="video.duration"
+ [maxTimestamp]="video().duration"
[disabled]="!customizations.stopAtCheckbox"
[(ngModel)]="customizations.stopAt"
>
@@ -241,7 +241,7 @@
></my-peertube-checkbox>
</div>
- <div class="form-group" *ngIf="!video.isLive">
+ <div class="form-group" *ngIf="!video().isLive">
<my-peertube-checkbox
inputName="loop" [(ngModel)]="customizations.loop"
i18n-labelText labelText="Loop"
diff --git a/client/src/app/shared/shared-share-modal/video-share.component.ts b/client/src/app/shared/shared-share-modal/video-share.component.ts
index 4e3edb445a..94a5e7f4af 100644
--- a/client/src/app/shared/shared-share-modal/video-share.component.ts
+++ b/client/src/app/shared/shared-share-modal/video-share.component.ts
@@ -1,5 +1,5 @@
import { NgFor, NgIf } from '@angular/common'
-import { Component, ElementRef, Input, ViewChild } from '@angular/core'
+import { Component, ElementRef, inject, input, model, viewChild } from '@angular/core'
import { FormsModule } from '@angular/forms'
import { DomSanitizer, SafeHtml } from '@angular/platform-browser'
import { RouterLink } from '@angular/router'
@@ -81,12 +81,17 @@ type TabId = 'url' | 'qrcode' | 'embed'
]
})
export class VideoShareComponent {
- @ViewChild('modal', { static: true }) modal: ElementRef
+ private modalService = inject(NgbModal)
+ private sanitizer = inject(DomSanitizer)
+ private server = inject(ServerService)
+ private hooks = inject(HooksService)
- @Input() video: VideoDetails = null
- @Input() videoCaptions: VideoCaption[] = []
- @Input() playlist: VideoPlaylist = null
- @Input() playlistPosition: number = null
+ readonly modal = viewChild<ElementRef>('modal')
+
+ readonly video = input<VideoDetails>(null)
+ readonly videoCaptions = input<VideoCaption[]>([])
+ readonly playlist = input<VideoPlaylist>(null)
+ readonly playlistPosition = model<number>(null)
activeVideoId: TabId = 'url'
activePlaylistId: TabId = 'url'
@@ -105,17 +110,11 @@ export class VideoShareComponent {
playlistEmbedHTML: string
playlistEmbedSafeHTML: SafeHtml
- constructor (
- private modalService: NgbModal,
- private sanitizer: DomSanitizer,
- private server: ServerService,
- private hooks: HooksService
- ) { }
-
show (currentVideoTimestamp?: number, currentPlaylistPosition?: number) {
let subtitle: string
- if (this.videoCaptions && this.videoCaptions.length !== 0) {
- subtitle = this.videoCaptions[0].language.id
+ const videoCaptions = this.videoCaptions()
+ if (videoCaptions && videoCaptions.length !== 0) {
+ subtitle = videoCaptions[0].language.id
}
this.customizations = new Proxy({
@@ -123,7 +122,7 @@ export class VideoShareComponent {
startAt: currentVideoTimestamp ? Math.floor(currentVideoTimestamp) : 0,
stopAtCheckbox: false,
- stopAt: this.video?.duration,
+ stopAt: this.video()?.duration,
subtitleCheckbox: false,
subtitle,
@@ -145,7 +144,7 @@ export class VideoShareComponent {
includeVideoInPlaylist: false
}, {
set: (target, prop, value) => {
- (target as any)[prop] = value
+ ;(target as any)[prop] = value
if (prop === 'embedP2P') {
// Auto enabled warning title if P2P is enabled
@@ -158,12 +157,12 @@ export class VideoShareComponent {
}
})
- this.playlistPosition = currentPlaylistPosition
+ this.playlistPosition.set(currentPlaylistPosition)
this.onUpdate()
- this.modalService.open(this.modal, { centered: true }).shown.subscribe(() => {
- this.hooks.runAction('action:modal.share.shown', 'video-watch', { video: this.video, playlist: this.playlist })
+ this.modalService.open(this.modal(), { centered: true }).shown.subscribe(() => {
+ this.hooks.runAction('action:modal.share.shown', 'video-watch', { video: this.video(), playlist: this.playlist() })
})
}
@@ -171,8 +170,8 @@ export class VideoShareComponent {
getVideoUrl () {
const url = this.customizations.originUrl
- ? this.video.url
- : buildVideoLink(this.video, window.location.origin)
+ ? this.video().url
+ : buildVideoLink(this.video(), window.location.origin)
return this.hooks.wrapFun(
decorateVideoLink,
@@ -186,7 +185,7 @@ export class VideoShareComponent {
getVideoEmbedUrl () {
return this.hooks.wrapFun(
decorateVideoLink,
- { url: this.video.embedUrl, ...this.getVideoOptions(true) },
+ { url: this.video().embedUrl, ...this.getVideoOptions(true) },
'video-watch',
'filter:share.video-embed-url.build.params',
'filter:share.video-embed-url.build.result'
@@ -197,7 +196,7 @@ export class VideoShareComponent {
const { responsive } = options
return this.hooks.wrapFun(
buildVideoOrPlaylistEmbed,
- { embedUrl: await this.getVideoEmbedUrl(), embedTitle: this.video.name, responsive, aspectRatio: this.video.aspectRatio },
+ { embedUrl: await this.getVideoEmbedUrl(), embedTitle: this.video().name, responsive, aspectRatio: this.video().aspectRatio },
'video-watch',
'filter:share.video-embed-code.build.params',
'filter:share.video-embed-code.build.result'
@@ -207,7 +206,7 @@ export class VideoShareComponent {
// ---------------------------------------------------------------------------
getPlaylistUrl () {
- const url = buildPlaylistLink(this.playlist)
+ const url = buildPlaylistLink(this.playlist())
return this.hooks.wrapFun(
decoratePlaylistLink,
@@ -221,7 +220,7 @@ export class VideoShareComponent {
getPlaylistEmbedUrl () {
return this.hooks.wrapFun(
decoratePlaylistLink,
- { url: this.playlist.embedUrl, ...this.getPlaylistOptions() },
+ { url: this.playlist().embedUrl, ...this.getPlaylistOptions() },
'video-watch',
'filter:share.video-playlist-embed-url.build.params',
'filter:share.video-playlist-embed-url.build.result'
@@ -234,9 +233,9 @@ export class VideoShareComponent {
buildVideoOrPlaylistEmbed,
{
embedUrl: await this.getPlaylistEmbedUrl(),
- embedTitle: this.playlist.displayName,
+ embedTitle: this.playlist().displayName,
responsive,
- aspectRatio: this.video?.aspectRatio
+ aspectRatio: this.video()?.aspectRatio
},
'video-watch',
'filter:share.video-playlist-embed-code.build.params',
@@ -247,14 +246,14 @@ export class VideoShareComponent {
// ---------------------------------------------------------------------------
async onUpdate () {
- if (this.playlist) {
+ if (this.playlist()) {
this.playlistUrl = await this.getPlaylistUrl()
this.playlistEmbedUrl = await this.getPlaylistEmbedUrl()
this.playlistEmbedHTML = await this.getPlaylistEmbedCode({ responsive: this.customizations.responsive })
this.playlistEmbedSafeHTML = this.sanitizer.bypassSecurityTrustHtml(await this.getPlaylistEmbedCode({ responsive: false }))
}
- if (this.video) {
+ if (this.video()) {
this.videoUrl = await this.getVideoUrl()
this.videoEmbedUrl = await this.getVideoEmbedUrl()
this.videoEmbedHTML = await this.getVideoEmbedCode({ responsive: this.customizations.responsive })
@@ -275,27 +274,28 @@ export class VideoShareComponent {
}
isLocalVideo () {
- return this.video.isLocal
+ return this.video().isLocal
}
isPrivateVideo () {
- return this.video.privacy.id === VideoPrivacy.PRIVATE
+ return this.video().privacy.id === VideoPrivacy.PRIVATE
}
isPrivatePlaylist () {
- return this.playlist.privacy.id === VideoPlaylistPrivacy.PRIVATE
+ return this.playlist().privacy.id === VideoPlaylistPrivacy.PRIVATE
}
isPasswordProtectedVideo () {
- return this.video.privacy.id === VideoPrivacy.PASSWORD_PROTECTED
+ return this.video().privacy.id === VideoPrivacy.PASSWORD_PROTECTED
}
private getPlaylistOptions (baseUrl?: string) {
+ const playlistPosition = this.playlistPosition()
return {
baseUrl,
- playlistPosition: this.playlistPosition && this.customizations.includeVideoInPlaylist
- ? this.playlistPosition
+ playlistPosition: playlistPosition && this.customizations.includeVideoInPlaylist
+ ? playlistPosition
: undefined
}
}
diff --git a/client/src/app/shared/shared-support-modal/support-modal.component.html b/client/src/app/shared/shared-support-modal/support-modal.component.html
index 63811a9a91..1dfe5f5dde 100644
--- a/client/src/app/shared/shared-support-modal/support-modal.component.html
+++ b/client/src/app/shared/shared-support-modal/support-modal.component.html
@@ -1,6 +1,6 @@
<ng-template #modal let-hide="close">
<div class="modal-header">
- <h4 i18n class="modal-title">Support {{ name }}</h4>
+ <h4 i18n class="modal-title">Support {{ name() }}</h4>
<button class="border-0 p-0" title="Close this modal" i18n-title (click)="hide()">
<my-global-icon iconName="cross"></my-global-icon>
</button>
diff --git a/client/src/app/shared/shared-support-modal/support-modal.component.ts b/client/src/app/shared/shared-support-modal/support-modal.component.ts
index cf95cf1146..c758e32ac9 100644
--- a/client/src/app/shared/shared-support-modal/support-modal.component.ts
+++ b/client/src/app/shared/shared-support-modal/support-modal.component.ts
@@ -1,4 +1,4 @@
-import { Component, Input, OnChanges, ViewChild } from '@angular/core'
+import { Component, OnChanges, inject, input, viewChild } from '@angular/core'
import { MarkdownService } from '@app/core'
import { NgbModal } from '@ng-bootstrap/ng-bootstrap'
import { GlobalIconComponent } from '../shared-icons/global-icon.component'
@@ -9,24 +9,22 @@ import { GlobalIconComponent } from '../shared-icons/global-icon.component'
imports: [ GlobalIconComponent ]
})
export class SupportModalComponent implements OnChanges {
- @Input({ required: true }) name: string
- @Input({ required: true }) content: string
+ private markdownService = inject(MarkdownService)
+ private modalService = inject(NgbModal)
- @ViewChild('modal', { static: true }) modal: NgbModal
+ readonly name = input.required<string>()
+ readonly content = input.required<string>()
- htmlSupport = ''
+ readonly modal = viewChild<NgbModal>('modal')
- constructor (
- private markdownService: MarkdownService,
- private modalService: NgbModal
- ) { }
+ htmlSupport = ''
ngOnChanges () {
- this.markdownService.enhancedMarkdownToHTML({ markdown: this.content, withEmoji: true, withHtml: true })
+ this.markdownService.enhancedMarkdownToHTML({ markdown: this.content(), withEmoji: true, withHtml: true })
.then(r => this.htmlSupport = r)
}
show () {
- return this.modalService.open(this.modal, { centered: true })
+ return this.modalService.open(this.modal(), { centered: true })
}
}
diff --git a/client/src/app/shared/shared-tables/table-expander-icon.component.ts b/client/src/app/shared/shared-tables/table-expander-icon.component.ts
index da26bafadc..ebe2da1d18 100644
--- a/client/src/app/shared/shared-tables/table-expander-icon.component.ts
+++ b/client/src/app/shared/shared-tables/table-expander-icon.component.ts
@@ -1,16 +1,16 @@
-import { Component, Input } from '@angular/core'
+import { Component, input } from '@angular/core'
import { NgClass } from '@angular/common'
import { NgbTooltip } from '@ng-bootstrap/ng-bootstrap'
@Component({
selector: 'my-table-expander-icon',
template: `
-<button type="button" class="expander border-0 p-0" [ngbTooltip]="tooltip" [ariaLabel]="tooltip">
- <i [ngClass]="expanded ? 'chevron-down' : 'chevron-right'"></i>
+<button type="button" class="expander border-0 p-0" [ngbTooltip]="tooltip()" [ariaLabel]="tooltip()">
+ <i [ngClass]="expanded() ? 'chevron-down' : 'chevron-right'"></i>
</button>`,
imports: [ NgbTooltip, NgClass ]
})
export class TableExpanderIconComponent {
- @Input() expanded: boolean
- @Input() tooltip = $localize`Get more information`
+ readonly expanded = input<boolean>(undefined)
+ readonly tooltip = input($localize`Get more information`)
}
diff --git a/client/src/app/shared/shared-tables/video-cell.component.html b/client/src/app/shared/shared-tables/video-cell.component.html
index 38e7dea172..709e2869f5 100644
--- a/client/src/app/shared/shared-tables/video-cell.component.html
+++ b/client/src/app/shared/shared-tables/video-cell.component.html
@@ -1,7 +1,7 @@
-<a [href]="getVideoUrl()" class="table-video-link" [title]="video.name" target="_blank" rel="noopener noreferrer">
+<a [href]="getVideoUrl()" class="table-video-link" [title]="video().name" target="_blank" rel="noopener noreferrer">
<div class="table-video">
<div class="table-video-image">
- <img [src]="video.thumbnailPath" alt="">
+ <img [src]="video().thumbnailPath" alt="">
<ng-content select="[image]"></ng-content>
</div>
@@ -10,10 +10,10 @@
<div>
<ng-content select="[name]"></ng-content>
- {{ video.name }}
+ {{ video().name }}
</div>
- <div class="muted">by {{ video.channel?.displayName }} on {{ video.channel?.host }} </div>
+ <div class="muted">by {{ video().channel?.displayName }} on {{ video().channel?.host }} </div>
</div>
</div>
</a>
diff --git a/client/src/app/shared/shared-tables/video-cell.component.ts b/client/src/app/shared/shared-tables/video-cell.component.ts
index 30b5774f72..fb2ef9e7f7 100644
--- a/client/src/app/shared/shared-tables/video-cell.component.ts
+++ b/client/src/app/shared/shared-tables/video-cell.component.ts
@@ -1,4 +1,4 @@
-import { Component, Input } from '@angular/core'
+import { Component, input } from '@angular/core'
import { Video } from '../shared-main/video/video.model'
@Component({
@@ -8,9 +8,9 @@ import { Video } from '../shared-main/video/video.model'
standalone: true
})
export class VideoCellComponent {
- @Input() video: Video
+ readonly video = input<Video>(undefined)
getVideoUrl () {
- return Video.buildWatchUrl(this.video)
+ return Video.buildWatchUrl(this.video())
}
}
diff --git a/client/src/app/shared/shared-thumbnail/video-thumbnail.component.html b/client/src/app/shared/shared-thumbnail/video-thumbnail.component.html
index fda6a68396..4790186cca 100644
--- a/client/src/app/shared/shared-thumbnail/video-thumbnail.component.html
+++ b/client/src/app/shared/shared-thumbnail/video-thumbnail.component.html
@@ -1,23 +1,23 @@
-@if (videoHref) {
- <a [ariaLabel]="ariaLabel" [href]="videoHref" [target]="videoTarget" class="video-thumbnail" tabindex="-1">
+@if (videoHref()) {
+ <a [ariaLabel]="ariaLabel()" [href]="videoHref()" [target]="videoTarget()" class="video-thumbnail" tabindex="-1">
<ng-container *ngTemplateOutlet="aContent"></ng-container>
</a>
} @else {
- <a [ariaLabel]="ariaLabel" [routerLink]="getVideoRouterLink()" [queryParams]="queryParams" class="video-thumbnail" tabindex="-1">
+ <a [ariaLabel]="ariaLabel()" [routerLink]="getVideoRouterLink()" [queryParams]="queryParams()" class="video-thumbnail" tabindex="-1">
<ng-container *ngTemplateOutlet="aContent"></ng-container>
</a>
}
<ng-template #aContent>
- <img alt="" [attr.src]="getImageUrl()" [ngClass]="{ 'blur-filter': nsfw }" />
+ <img alt="" [attr.src]="getImageUrl()" [ngClass]="{ 'blur-filter': nsfw() }" />
- <div *ngIf="displayWatchLaterPlaylist" class="actions-overlay">
+ <div *ngIf="displayWatchLaterPlaylist()" class="actions-overlay">
<button
class="watch-icon-overlay button-unstyle"
placement="left" [ngbTooltip]="getWatchIconText()" container="body" #watchLaterTooltip="ngbTooltip"
- (click)="onWatchLaterClick($event)" [attr.aria-label]="inWatchLaterPlaylist ? removeFromWatchLaterText : addToWatchLaterText"
+ (click)="onWatchLaterClick($event)" [attr.aria-label]="inWatchLaterPlaylist() ? removeFromWatchLaterText : addToWatchLaterText"
>
- @if (inWatchLaterPlaylist) {
+ @if (inWatchLaterPlaylist()) {
<my-global-icon iconName="tick"></my-global-icon>
} @else {
<my-global-icon iconName="clock"></my-global-icon>
@@ -28,7 +28,7 @@
<div class="label-overlay warning"><ng-content select="label-warning"></ng-content></div>
<div class="label-overlay danger"><ng-content select="label-danger"></ng-content></div>
- @if (video.isLive) {
+ @if (video().isLive) {
<div class="live-overlay" [ngClass]="{ 'live-streaming': isLiveStreaming(), 'ended-live': isEndedLive() }">
@if (isLiveStreaming()) {
<ng-container i18n>LIVE</ng-container>
@@ -39,14 +39,14 @@
}
</div>
} @else {
- <div class="duration-overlay" [ariaLabel]="getDurationOverlayLabel()">{{ video.durationLabel }}</div>
+ <div class="duration-overlay" [ariaLabel]="getDurationOverlayLabel()">{{ video().durationLabel }}</div>
}
<div class="play-overlay">
<div class="icon"></div>
</div>
- <div class="progress-bar" *ngIf="!video.isLive && video.userHistory?.currentTime">
+ <div class="progress-bar" *ngIf="!video().isLive && video().userHistory?.currentTime">
<div [ngStyle]="{ 'width.%': getProgressPercent() }">
<span class="visually-hidden" i18n>You watched {{ getProgressPercent() }}% of this video</span>
</div>
diff --git a/client/src/app/shared/shared-thumbnail/video-thumbnail.component.ts b/client/src/app/shared/shared-thumbnail/video-thumbnail.component.ts
index 64ec1810dd..a8dfc8b148 100644
--- a/client/src/app/shared/shared-thumbnail/video-thumbnail.component.ts
+++ b/client/src/app/shared/shared-thumbnail/video-thumbnail.component.ts
@@ -1,5 +1,5 @@
import { NgClass, NgIf, NgStyle, NgTemplateOutlet } from '@angular/common'
-import { Component, EventEmitter, Input, Output, ViewChild } from '@angular/core'
+import { Component, inject, input, output, viewChild } from '@angular/core'
import { RouterLink } from '@angular/router'
import { ScreenService } from '@app/core'
import { NgbTooltip } from '@ng-bootstrap/ng-bootstrap'
@@ -14,33 +14,37 @@ import { Video } from '../shared-main/video/video.model'
imports: [ NgIf, RouterLink, NgTemplateOutlet, NgClass, NgbTooltip, GlobalIconComponent, NgStyle ]
})
export class VideoThumbnailComponent {
- @ViewChild('watchLaterTooltip') watchLaterTooltip: NgbTooltip
+ private screenService = inject(ScreenService)
- @Input() video: Video
- @Input() nsfw = false
+ readonly watchLaterTooltip = viewChild<NgbTooltip>('watchLaterTooltip')
- @Input() videoRouterLink: string | any[]
- @Input() queryParams: { [ p: string ]: any }
- @Input() videoHref: string
- @Input() videoTarget: string
+ readonly video = input<Video>(undefined)
+ readonly nsfw = input(false)
- @Input() displayWatchLaterPlaylist: boolean
- @Input() inWatchLaterPlaylist: boolean
+ readonly videoRouterLink = input<string | any[]>(undefined)
+ readonly queryParams = input<{
+ [p: string]: any
+ }>(undefined)
+ readonly videoHref = input<string>(undefined)
+ readonly videoTarget = input<string>(undefined)
- @Input({ required: true }) ariaLabel: string
+ readonly displayWatchLaterPlaylist = input<boolean>(undefined)
+ readonly inWatchLaterPlaylist = input<boolean>(undefined)
- @Output() watchLaterClick = new EventEmitter<boolean>()
+ readonly ariaLabel = input.required<string>()
+
+ readonly watchLaterClick = output<boolean>()
addToWatchLaterText: string
removeFromWatchLaterText: string
- constructor (private screenService: ScreenService) {
+ constructor () {
this.addToWatchLaterText = $localize`Add to watch later`
this.removeFromWatchLaterText = $localize`Remove from watch later`
}
getWatchIconText () {
- if (this.inWatchLaterPlaylist) return this.removeFromWatchLaterText
+ if (this.inWatchLaterPlaylist()) return this.removeFromWatchLaterText
return this.addToWatchLaterText
}
@@ -48,48 +52,52 @@ export class VideoThumbnailComponent {
isLiveStreaming () {
// In non moderator mode we only display published live
// If in moderator mode, the server adds the state info to the object
- if (!this.video.isLive) return false
+ const video = this.video()
+ if (!video.isLive) return false
- return !this.video.state || this.video.state?.id === VideoState.PUBLISHED
+ return !video.state || video.state?.id === VideoState.PUBLISHED
}
isEndedLive () {
- return this.video.state?.id === VideoState.LIVE_ENDED
+ return this.video().state?.id === VideoState.LIVE_ENDED
}
getImageUrl () {
- if (!this.video) return ''
+ const video = this.video()
+ if (!video) return ''
if (this.screenService.isInMobileView()) {
- return this.video.previewUrl
+ return video.previewUrl
}
- return this.video.thumbnailUrl
+ return video.thumbnailUrl
}
getProgressPercent () {
- if (!this.video.userHistory) return 0
+ const video = this.video()
+ if (!video.userHistory) return 0
- const currentTime = this.video.userHistory.currentTime
+ const currentTime = video.userHistory.currentTime
- return Math.round(currentTime / this.video.duration * 100)
+ return Math.round(currentTime / video.duration * 100)
}
getDurationOverlayLabel () {
- return $localize`Video duration is ${this.video.durationLabel}`
+ return $localize`Video duration is ${this.video().durationLabel}`
}
getVideoRouterLink () {
- if (this.videoRouterLink) return this.videoRouterLink
+ const videoRouterLink = this.videoRouterLink()
+ if (videoRouterLink) return videoRouterLink
- return Video.buildWatchUrl(this.video)
+ return Video.buildWatchUrl(this.video())
}
onWatchLaterClick (event: Event) {
- this.watchLaterClick.emit(this.inWatchLaterPlaylist)
+ this.watchLaterClick.emit(this.inWatchLaterPlaylist())
event.stopPropagation()
- this.watchLaterTooltip.close()
+ this.watchLaterTooltip().close()
return false
}
diff --git a/client/src/app/shared/shared-user-settings/user-interface-settings.component.html b/client/src/app/shared/shared-user-settings/user-interface-settings.component.html
index c17c8db789..3c454df5dd 100644
--- a/client/src/app/shared/shared-user-settings/user-interface-settings.component.html
+++ b/client/src/app/shared/shared-user-settings/user-interface-settings.component.html
@@ -6,5 +6,5 @@
<my-select-options inputId="theme" formControlName="theme" [items]="availableThemes"></my-select-options>
</div>
- <input *ngIf="!reactiveUpdate" type="submit" class="peertube-button primary-button" i18n-value value="Save interface settings" [disabled]="!form.valid">
+ <input *ngIf="!reactiveUpdate()" type="submit" class="peertube-button primary-button" i18n-value value="Save interface settings" [disabled]="!form.valid">
</form>
diff --git a/client/src/app/shared/shared-user-settings/user-interface-settings.component.ts b/client/src/app/shared/shared-user-settings/user-interface-settings.component.ts
index d2d75c3b0f..135c9f6f7d 100644
--- a/client/src/app/shared/shared-user-settings/user-interface-settings.component.ts
+++ b/client/src/app/shared/shared-user-settings/user-interface-settings.component.ts
@@ -1,11 +1,11 @@
import { Subject, Subscription } from 'rxjs'
-import { Component, Input, OnDestroy, OnInit } from '@angular/core'
+import { Component, OnDestroy, OnInit, inject, input } from '@angular/core'
import { AuthService, Notifier, ServerService, ThemeService, UserService } from '@app/core'
import { FormReactive } from '@app/shared/shared-forms/form-reactive'
import { FormReactiveService } from '@app/shared/shared-forms/form-reactive.service'
import { HTMLServerConfig, User, UserUpdateMe } from '@peertube/peertube-models'
import { SelectOptionsItem } from 'src/types'
-import { NgFor, NgIf } from '@angular/common'
+import { NgIf } from '@angular/common'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { SelectOptionsComponent } from '../shared-forms/select/select-options.component'
@@ -13,30 +13,26 @@ import { SelectOptionsComponent } from '../shared-forms/select/select-options.co
selector: 'my-user-interface-settings',
templateUrl: './user-interface-settings.component.html',
styleUrls: [ './user-interface-settings.component.scss' ],
- imports: [ FormsModule, ReactiveFormsModule, NgFor, NgIf, SelectOptionsComponent ]
+ imports: [ FormsModule, ReactiveFormsModule, NgIf, SelectOptionsComponent ]
})
export class UserInterfaceSettingsComponent extends FormReactive implements OnInit, OnDestroy {
- @Input() user: User
- @Input() reactiveUpdate = false
- @Input() notifyOnUpdate = true
- @Input() userInformationLoaded: Subject<any>
+ protected formReactiveService = inject(FormReactiveService)
+ private authService = inject(AuthService)
+ private notifier = inject(Notifier)
+ private userService = inject(UserService)
+ private themeService = inject(ThemeService)
+ private serverService = inject(ServerService)
+
+ readonly user = input<User>(undefined)
+ readonly reactiveUpdate = input(false)
+ readonly notifyOnUpdate = input(true)
+ readonly userInformationLoaded = input<Subject<any>>(undefined)
availableThemes: SelectOptionsItem[]
formValuesWatcher: Subscription
private serverConfig: HTMLServerConfig
- constructor (
- protected formReactiveService: FormReactiveService,
- private authService: AuthService,
- private notifier: Notifier,
- private userService: UserService,
- private themeService: ThemeService,
- private serverService: ServerService
- ) {
- super()
- }
-
get instanceName () {
return this.serverConfig.instance.name
}
@@ -56,13 +52,13 @@ export class UserInterfaceSettingsComponent extends FormReactive implements OnIn
theme: null
})
- this.userInformationLoaded
+ this.userInformationLoaded()
.subscribe(() => {
this.form.patchValue({
- theme: this.user.theme
+ theme: this.user().theme
})
- if (this.reactiveUpdate) {
+ if (this.reactiveUpdate()) {
this.formValuesWatcher = this.form.valueChanges.subscribe(() => this.updateInterfaceSettings())
}
})
@@ -85,7 +81,7 @@ export class UserInterfaceSettingsComponent extends FormReactive implements OnIn
next: () => {
this.authService.refreshUserInformation()
- if (this.notifyOnUpdate) this.notifier.success($localize`Interface settings updated.`)
+ if (this.notifyOnUpdate()) this.notifier.success($localize`Interface settings updated.`)
},
error: err => this.notifier.error(err.message)
@@ -95,7 +91,7 @@ export class UserInterfaceSettingsComponent extends FormReactive implements OnIn
}
this.userService.updateMyAnonymousProfile(details)
- if (this.notifyOnUpdate) this.notifier.success($localize`Interface settings updated.`)
+ if (this.notifyOnUpdate()) this.notifier.success($localize`Interface settings updated.`)
}
private getDefaultInstanceThemeLabel () {
@@ -107,5 +103,4 @@ export class UserInterfaceSettingsComponent extends FormReactive implements OnIn
return theme
}
-
}
diff --git a/client/src/app/shared/shared-user-settings/user-video-settings.component.html b/client/src/app/shared/shared-user-settings/user-video-settings.component.html
index 9e5c94813c..9721e2d3f5 100644
--- a/client/src/app/shared/shared-user-settings/user-video-settings.component.html
+++ b/client/src/app/shared/shared-user-settings/user-video-settings.component.html
@@ -76,5 +76,5 @@
</my-peertube-checkbox>
</div>
- <input *ngIf="!reactiveUpdate" type="submit" i18n-value value="Save video settings" [disabled]="!form.valid" class="peertube-button primary-button mt-3">
+ <input *ngIf="!reactiveUpdate()" type="submit" i18n-value value="Save video settings" [disabled]="!form.valid" class="peertube-button primary-button mt-3">
</form>
diff --git a/client/src/app/shared/shared-user-settings/user-video-settings.component.ts b/client/src/app/shared/shared-user-settings/user-video-settings.component.ts
index 52841117a3..af9b31e86d 100644
--- a/client/src/app/shared/shared-user-settings/user-video-settings.component.ts
+++ b/client/src/app/shared/shared-user-settings/user-video-settings.component.ts
@@ -1,13 +1,13 @@
import { pick } from 'lodash-es'
import { Subject, Subscription } from 'rxjs'
import { first } from 'rxjs/operators'
-import { Component, Input, OnDestroy, OnInit } from '@angular/core'
+import { Component, OnDestroy, OnInit, inject, input } from '@angular/core'
import { AuthService, Notifier, ServerService, User, UserService } from '@app/core'
import { FormReactive } from '@app/shared/shared-forms/form-reactive'
import { FormReactiveService } from '@app/shared/shared-forms/form-reactive.service'
import { NSFWPolicyType, UserUpdateMe } from '@peertube/peertube-models'
import { NgIf } from '@angular/common'
-import { RouterLink } from '@angular/router'
+
import { PeertubeCheckboxComponent } from '../shared-forms/peertube-checkbox.component'
import { SelectLanguagesComponent } from '../shared-forms/select/select-languages.component'
import { PeerTubeTemplateDirective } from '../shared-main/common/peertube-template.directive'
@@ -25,29 +25,24 @@ import { FormsModule, ReactiveFormsModule } from '@angular/forms'
PeerTubeTemplateDirective,
SelectLanguagesComponent,
PeertubeCheckboxComponent,
- RouterLink,
NgIf
]
})
export class UserVideoSettingsComponent extends FormReactive implements OnInit, OnDestroy {
- @Input() user: User = null
- @Input() reactiveUpdate = false
- @Input() notifyOnUpdate = true
- @Input() userInformationLoaded: Subject<any>
+ protected formReactiveService = inject(FormReactiveService)
+ private authService = inject(AuthService)
+ private notifier = inject(Notifier)
+ private userService = inject(UserService)
+ private serverService = inject(ServerService)
+
+ readonly user = input<User>(null)
+ readonly reactiveUpdate = input(false)
+ readonly notifyOnUpdate = input(true)
+ readonly userInformationLoaded = input<Subject<any>>(undefined)
defaultNSFWPolicy: NSFWPolicyType
formValuesWatcher: Subscription
- constructor (
- protected formReactiveService: FormReactiveService,
- private authService: AuthService,
- private notifier: Notifier,
- private userService: UserService,
- private serverService: ServerService
- ) {
- super()
- }
-
ngOnInit () {
this.buildForm({
nsfwPolicy: null,
@@ -57,21 +52,21 @@ export class UserVideoSettingsComponent extends FormReactive implements OnInit,
videoLanguages: null
})
- this.userInformationLoaded.pipe(first())
+ this.userInformationLoaded().pipe(first())
.subscribe(
() => {
const serverConfig = this.serverService.getHTMLConfig()
this.defaultNSFWPolicy = serverConfig.instance.defaultNSFWPolicy
this.form.patchValue({
- nsfwPolicy: this.user.nsfwPolicy || this.defaultNSFWPolicy,
- p2pEnabled: this.user.p2pEnabled,
- autoPlayVideo: this.user.autoPlayVideo === true,
- autoPlayNextVideo: this.user.autoPlayNextVideo,
- videoLanguages: this.user.videoLanguages
+ nsfwPolicy: this.user().nsfwPolicy || this.defaultNSFWPolicy,
+ p2pEnabled: this.user().p2pEnabled,
+ autoPlayVideo: this.user().autoPlayVideo === true,
+ autoPlayNextVideo: this.user().autoPlayNextVideo,
+ videoLanguages: this.user().videoLanguages
})
- if (this.reactiveUpdate) this.handleReactiveUpdate()
+ if (this.reactiveUpdate()) this.handleReactiveUpdate()
}
)
}
@@ -121,7 +116,7 @@ export class UserVideoSettingsComponent extends FormReactive implements OnInit,
this.formValuesWatcher = this.form.valueChanges.subscribe((formValue: any) => {
const updatedKey = Object.keys(formValue)
- .find(k => formValue[k] !== oldForm[k])
+ .find(k => formValue[k] !== oldForm[k])
oldForm = { ...this.form.value }
@@ -135,7 +130,7 @@ export class UserVideoSettingsComponent extends FormReactive implements OnInit,
next: () => {
this.authService.refreshUserInformation()
- if (this.notifyOnUpdate) this.notifier.success($localize`Video settings updated.`)
+ if (this.notifyOnUpdate()) this.notifier.success($localize`Video settings updated.`)
},
error: err => this.notifier.error(err.message)
@@ -145,7 +140,7 @@ export class UserVideoSettingsComponent extends FormReactive implements OnInit,
private updateAnonymousProfile (details: UserUpdateMe) {
this.userService.updateMyAnonymousProfile(details)
- if (this.notifyOnUpdate) {
+ if (this.notifyOnUpdate()) {
this.notifier.success($localize`Display/Video settings updated.`)
}
}
diff --git a/client/src/app/shared/shared-user-subscription/remote-subscribe.component.html b/client/src/app/shared/shared-user-subscription/remote-subscribe.component.html
index 343d756030..e8fcec5e70 100644
--- a/client/src/app/shared/shared-user-subscription/remote-subscribe.component.html
+++ b/client/src/app/shared/shared-user-subscription/remote-subscribe.component.html
@@ -7,14 +7,14 @@
</div>
<button type="submit" [disabled]="!form.valid" class="peertube-button primary-button">
- @if (interact) {
+ @if (interact()) {
<span i18n>Remote interact</span>
} @else {
<span i18n>Remote subscribe</span>
}
</button>
- <my-help *ngIf="!interact && showHelp">
+ <my-help *ngIf="!interact() && showHelp()">
<ng-template ptTemplate="customHtml">
<ng-container i18n>
You can subscribe to the channel via any ActivityPub-capable fediverse instance (PeerTube, Mastodon or Pleroma for example).
@@ -22,7 +22,7 @@
</ng-template>
</my-help>
- <my-help *ngIf="showHelp && interact">
+ <my-help *ngIf="showHelp() && interact()">
<ng-template ptTemplate="customHtml">
<ng-container i18n>
You can interact with this via any ActivityPub-capable fediverse instance (PeerTube, Mastodon or Pleroma for example).
diff --git a/client/src/app/shared/shared-user-subscription/remote-subscribe.component.ts b/client/src/app/shared/shared-user-subscription/remote-subscribe.component.ts
index 2284e08491..2b4ab1e47a 100644
--- a/client/src/app/shared/shared-user-subscription/remote-subscribe.component.ts
+++ b/client/src/app/shared/shared-user-subscription/remote-subscribe.component.ts
@@ -1,4 +1,4 @@
-import { Component, Input, OnInit } from '@angular/core'
+import { Component, OnInit, inject, input } from '@angular/core'
import { Notifier } from '@app/core'
import { FormReactive } from '@app/shared/shared-forms/form-reactive'
import { FormReactiveService } from '@app/shared/shared-forms/form-reactive.service'
@@ -15,16 +15,12 @@ import { FormsModule, ReactiveFormsModule } from '@angular/forms'
imports: [ FormsModule, ReactiveFormsModule, NgIf, HelpComponent, PeerTubeTemplateDirective ]
})
export class RemoteSubscribeComponent extends FormReactive implements OnInit {
- @Input() uri: string
- @Input() interact = false
- @Input() showHelp = false
+ protected formReactiveService = inject(FormReactiveService)
+ private notifier = inject(Notifier)
- constructor (
- protected formReactiveService: FormReactiveService,
- private notifier: Notifier
- ) {
- super()
- }
+ readonly uri = input<string>(undefined)
+ readonly interact = input(false)
+ readonly showHelp = input(false)
ngOnInit () {
this.buildForm({
@@ -60,7 +56,7 @@ export class RemoteSubscribeComponent extends FormReactive implements OnInit {
})
if (link?.template.includes('{uri}')) {
- return link.template.replace('{uri}', encodeURIComponent(this.uri))
+ return link.template.replace('{uri}', encodeURIComponent(this.uri()))
}
throw new Error('No subscribe template in webfinger response')
diff --git a/client/src/app/shared/shared-user-subscription/subscribe-button.component.ts b/client/src/app/shared/shared-user-subscription/subscribe-button.component.ts
index 6f6af19765..2d1c98019b 100644
--- a/client/src/app/shared/shared-user-subscription/subscribe-button.component.ts
+++ b/client/src/app/shared/shared-user-subscription/subscribe-button.component.ts
@@ -1,5 +1,5 @@
import { NgClass, NgIf, NgTemplateOutlet } from '@angular/common'
-import { Component, Input, OnChanges, ViewChild } from '@angular/core'
+import { Component, OnChanges, inject, input, viewChild } from '@angular/core'
import { AuthService, Notifier, RedirectService } from '@app/core'
import { NgbDropdown, NgbDropdownMenu, NgbDropdownToggle } from '@ng-bootstrap/ng-bootstrap'
import { FeedFormat } from '@peertube/peertube-models'
@@ -25,33 +25,32 @@ import { UserSubscriptionService } from './user-subscription.service'
]
})
export class SubscribeButtonComponent implements OnChanges {
+ private authService = inject(AuthService)
+ private redirectService = inject(RedirectService)
+ private notifier = inject(Notifier)
+ private userSubscriptionService = inject(UserSubscriptionService)
+ private videoService = inject(VideoService)
+
/**
* SubscribeButtonComponent can be used with a single VideoChannel passed as [VideoChannel],
* or with an account and a full list of that account's videoChannels. The latter is intended
* to allow mass un/subscription from an account's page, while keeping the channel-centric
* subscription model.
*/
- @Input() account: Account
- @Input() videoChannels: VideoChannel[]
- @Input() size: 'small' | 'normal' = 'normal'
+ readonly account = input<Account>(undefined)
+ readonly videoChannels = input<VideoChannel[]>(undefined)
+ readonly size = input<'small' | 'normal'>('normal')
- @ViewChild('dropdown') dropdown: NgbDropdown
+ readonly dropdown = viewChild<NgbDropdown>('dropdown')
subscribed = new Map<string, boolean>()
buttonClasses: Record<string, boolean> = {}
- constructor (
- private authService: AuthService,
- private redirectService: RedirectService,
- private notifier: Notifier,
- private userSubscriptionService: UserSubscriptionService,
- private videoService: VideoService
- ) { }
-
get handle () {
- return this.account
- ? this.account.nameWithHost
+ const account = this.account()
+ return account
+ ? account.nameWithHost
: this.videoChannel.name + '@' + this.videoChannel.host
}
@@ -60,29 +59,31 @@ export class SubscribeButtonComponent implements OnChanges {
}
get uri () {
- return this.account
- ? this.account.url
- : this.videoChannels[0].url
+ const account = this.account()
+ return account
+ ? account.url
+ : this.videoChannels()[0].url
}
get rssUri () {
- const rssFeed = this.account
+ const account = this.account()
+ const rssFeed = account
? this.videoService
- .getAccountFeedUrls(this.account.id)
- .find(i => i.format === FeedFormat.RSS)
+ .getAccountFeedUrls(account.id)
+ .find(i => i.format === FeedFormat.RSS)
: this.videoService
- .getVideoChannelFeedUrls(this.videoChannels[0].id)
- .find(i => i.format === FeedFormat.RSS)
+ .getVideoChannelFeedUrls(this.videoChannels()[0].id)
+ .find(i => i.format === FeedFormat.RSS)
return rssFeed.url
}
get videoChannel () {
- return this.videoChannels[0]
+ return this.videoChannels()[0]
}
get isAllChannelsSubscribed () {
- return this.subscribeStatus(true).length === this.videoChannels.length
+ return this.subscribeStatus(true).length === this.videoChannels().length
}
get isAtLeastOneChannelSubscribed () {
@@ -90,11 +91,11 @@ export class SubscribeButtonComponent implements OnChanges {
}
get isBigButton () {
- return this.isUserLoggedIn() && this.videoChannels.length > 1 && this.isAtLeastOneChannelSubscribed
+ return this.isUserLoggedIn() && this.videoChannels().length > 1 && this.isAtLeastOneChannelSubscribed
}
get isSingleSubscribe () {
- return !this.account
+ return !this.account()
}
ngOnChanges () {
@@ -105,7 +106,8 @@ export class SubscribeButtonComponent implements OnChanges {
// ---------------------------------------------------------------------------
subscribe () {
- if (this.dropdown) this.dropdown.close()
+ const dropdown = this.dropdown()
+ if (dropdown) dropdown.close()
if (this.isUserLoggedIn()) {
return this.localSubscribe()
@@ -117,7 +119,7 @@ export class SubscribeButtonComponent implements OnChanges {
private localSubscribe () {
const subscribedStatus = this.subscribeStatus(false)
- const observableBatch = this.videoChannels
+ const observableBatch = this.videoChannels()
.map(videoChannel => this.getChannelHandler(videoChannel))
.filter(handle => subscribedStatus.includes(handle))
.map(handle => this.userSubscriptionService.addSubscription(handle))
@@ -127,11 +129,11 @@ export class SubscribeButtonComponent implements OnChanges {
next: () => {
this.buildClasses()
+ const account = this.account()
this.notifier.success(
- this.account
- ? $localize`Subscribed to all current channels of ${this.account.displayName}. You will be notified of all their new videos.`
- : $localize`Subscribed to ${this.videoChannels[0].displayName}. You will be notified of all their new videos.`,
-
+ account
+ ? $localize`Subscribed to all current channels of ${account.displayName}. You will be notified of all their new videos.`
+ : $localize`Subscribed to ${this.videoChannels()[0].displayName}. You will be notified of all their new videos.`,
$localize`Subscribed`
)
},
@@ -143,7 +145,8 @@ export class SubscribeButtonComponent implements OnChanges {
// ---------------------------------------------------------------------------
unsubscribe () {
- if (this.dropdown) this.dropdown.close()
+ const dropdown = this.dropdown()
+ if (dropdown) dropdown.close()
if (this.isUserLoggedIn()) {
this.localUnsubscribe()
@@ -153,21 +156,21 @@ export class SubscribeButtonComponent implements OnChanges {
private localUnsubscribe () {
const subscribeStatus = this.subscribeStatus(true)
- const observableBatch = this.videoChannels
- .map(videoChannel => this.getChannelHandler(videoChannel))
- .filter(handle => subscribeStatus.includes(handle))
- .map(handle => this.userSubscriptionService.deleteSubscription(handle))
+ const observableBatch = this.videoChannels()
+ .map(videoChannel => this.getChannelHandler(videoChannel))
+ .filter(handle => subscribeStatus.includes(handle))
+ .map(handle => this.userSubscriptionService.deleteSubscription(handle))
concat(...observableBatch)
.subscribe({
complete: () => {
this.buildClasses()
+ const account = this.account()
this.notifier.success(
- this.account
- ? $localize`Unsubscribed from all channels of ${this.account.nameWithHost}`
- : $localize`Unsubscribed from ${this.videoChannels[0].nameWithHost}`,
-
+ account
+ ? $localize`Unsubscribed from all channels of ${account.nameWithHost}`
+ : $localize`Unsubscribed from ${this.videoChannels()[0].nameWithHost}`,
$localize`Unsubscribed`
)
},
@@ -210,7 +213,7 @@ export class SubscribeButtonComponent implements OnChanges {
private loadSubscribedStatus () {
if (!this.isUserLoggedIn()) return
- for (const videoChannel of this.videoChannels) {
+ for (const videoChannel of this.videoChannels()) {
const handle = this.getChannelHandler(videoChannel)
this.subscribed.set(handle, false)
diff --git a/client/src/app/shared/shared-user-subscription/user-subscription.service.ts b/client/src/app/shared/shared-user-subscription/user-subscription.service.ts
index 1bb96014ba..56934c6a91 100644
--- a/client/src/app/shared/shared-user-subscription/user-subscription.service.ts
+++ b/client/src/app/shared/shared-user-subscription/user-subscription.service.ts
@@ -2,7 +2,7 @@ import debug from 'debug'
import { merge, Observable, of, ReplaySubject, Subject } from 'rxjs'
import { catchError, filter, map, switchMap, tap } from 'rxjs/operators'
import { HttpClient, HttpParams } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { ComponentPaginationLight, RestExtractor, RestService } from '@app/core'
import { buildBulkObservable } from '@app/helpers'
import { ActorFollow, ResultList, VideoChannel as VideoChannelServer, VideoSortField } from '@peertube/peertube-models'
@@ -14,11 +14,16 @@ import { VideoChannelService } from '../shared-main/channel/video-channel.servic
const debugLogger = debug('peertube:subscriptions:UserSubscriptionService')
-type SubscriptionExistResult = { [ uri: string ]: boolean }
-type SubscriptionExistResultObservable = { [ uri: string ]: Observable<boolean> }
+type SubscriptionExistResult = { [uri: string]: boolean }
+type SubscriptionExistResultObservable = { [uri: string]: Observable<boolean> }
@Injectable()
export class UserSubscriptionService {
+ private authHttp = inject(HttpClient)
+ private restExtractor = inject(RestExtractor)
+ private videoService = inject(VideoService)
+ private restService = inject(RestService)
+
static BASE_USER_SUBSCRIPTIONS_URL = environment.apiUrl + '/api/v1/users/me/subscriptions'
static BASE_VIDEO_CHANNELS_URL = environment.apiUrl + '/api/v1/video-channels'
static BASE_ACCOUNTS_URL = environment.apiUrl + '/api/v1/accounts'
@@ -31,19 +36,13 @@ export class UserSubscriptionService {
private myAccountSubscriptionCacheObservable: SubscriptionExistResultObservable = {}
private myAccountSubscriptionCacheSubject = new Subject<SubscriptionExistResult>()
- constructor (
- private authHttp: HttpClient,
- private restExtractor: RestExtractor,
- private videoService: VideoService,
- private restService: RestService
- ) {
+ constructor () {
this.existsObservable = merge(
buildBulkObservable({
time: 200,
notifierObservable: this.existsSubject,
bulkGet: this.doSubscriptionsExist.bind(this)
}).pipe(map(r => r.response)),
-
this.myAccountSubscriptionCacheSubject
)
}
@@ -95,11 +94,11 @@ export class UserSubscriptionService {
if (skipCount) params = params.set('skipCount', skipCount + '')
return this.authHttp
- .get<ResultList<Video>>(UserSubscriptionService.BASE_USER_SUBSCRIPTIONS_URL + '/videos', { params })
- .pipe(
- switchMap(res => this.videoService.extractVideos(res)),
- catchError(err => this.restExtractor.handleError(err))
- )
+ .get<ResultList<Video>>(UserSubscriptionService.BASE_USER_SUBSCRIPTIONS_URL + '/videos', { params })
+ .pipe(
+ switchMap(res => this.videoService.extractVideos(res)),
+ catchError(err => this.restExtractor.handleError(err))
+ )
}
/**
@@ -110,14 +109,14 @@ export class UserSubscriptionService {
const url = UserSubscriptionService.BASE_USER_SUBSCRIPTIONS_URL + '/' + nameWithHost
return this.authHttp.delete(url)
- .pipe(
- tap(() => {
- this.myAccountSubscriptionCache[nameWithHost] = false
-
- this.myAccountSubscriptionCacheSubject.next(this.myAccountSubscriptionCache)
- }),
- catchError(err => this.restExtractor.handleError(err))
- )
+ .pipe(
+ tap(() => {
+ this.myAccountSubscriptionCache[nameWithHost] = false
+
+ this.myAccountSubscriptionCacheSubject.next(this.myAccountSubscriptionCache)
+ }),
+ catchError(err => this.restExtractor.handleError(err))
+ )
}
addSubscription (nameWithHost: string) {
@@ -125,14 +124,14 @@ export class UserSubscriptionService {
const body = { uri: nameWithHost }
return this.authHttp.post(url, body)
- .pipe(
- tap(() => {
- this.myAccountSubscriptionCache[nameWithHost] = true
-
- this.myAccountSubscriptionCacheSubject.next(this.myAccountSubscriptionCache)
- }),
- catchError(err => this.restExtractor.handleError(err))
- )
+ .pipe(
+ tap(() => {
+ this.myAccountSubscriptionCache[nameWithHost] = true
+
+ this.myAccountSubscriptionCacheSubject.next(this.myAccountSubscriptionCache)
+ }),
+ catchError(err => this.restExtractor.handleError(err))
+ )
}
listSubscriptions (parameters: {
@@ -149,10 +148,10 @@ export class UserSubscriptionService {
if (search) params = params.append('search', search)
return this.authHttp.get<ResultList<VideoChannelServer>>(url, { params })
- .pipe(
- map(res => VideoChannelService.extractVideoChannels(res)),
- catchError(err => this.restExtractor.handleError(err))
- )
+ .pipe(
+ map(res => VideoChannelService.extractVideoChannels(res)),
+ catchError(err => this.restExtractor.handleError(err))
+ )
}
/**
@@ -169,10 +168,10 @@ export class UserSubscriptionService {
}
const obs = this.existsObservable
- .pipe(
- filter(existsResult => existsResult[nameWithHost] !== undefined),
- map(existsResult => existsResult[nameWithHost])
- )
+ .pipe(
+ filter(existsResult => existsResult[nameWithHost] !== undefined),
+ map(existsResult => existsResult[nameWithHost])
+ )
this.myAccountSubscriptionCacheObservable[nameWithHost] = obs
return obs
@@ -204,14 +203,14 @@ export class UserSubscriptionService {
params = this.restService.addObjectParams(params, { uris })
return this.authHttp.get<SubscriptionExistResult>(url, { params })
- .pipe(
- tap(res => {
- this.myAccountSubscriptionCache = {
- ...this.myAccountSubscriptionCache,
- ...res
- }
- }),
- catchError(err => this.restExtractor.handleError(err))
- )
+ .pipe(
+ tap(res => {
+ this.myAccountSubscriptionCache = {
+ ...this.myAccountSubscriptionCache,
+ ...res
+ }
+ }),
+ catchError(err => this.restExtractor.handleError(err))
+ )
}
}
diff --git a/client/src/app/shared/shared-users/two-factor.service.ts b/client/src/app/shared/shared-users/two-factor.service.ts
index cb4450e8f2..80e210bcff 100644
--- a/client/src/app/shared/shared-users/two-factor.service.ts
+++ b/client/src/app/shared/shared-users/two-factor.service.ts
@@ -1,15 +1,13 @@
import { catchError } from 'rxjs/operators'
import { HttpClient } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { RestExtractor, UserService } from '@app/core'
import { TwoFactorEnableResult } from '@peertube/peertube-models'
@Injectable()
export class TwoFactorService {
- constructor (
- private authHttp: HttpClient,
- private restExtractor: RestExtractor
- ) { }
+ private authHttp = inject(HttpClient)
+ private restExtractor = inject(RestExtractor)
// ---------------------------------------------------------------------------
@@ -22,7 +20,7 @@ export class TwoFactorService {
const url = UserService.BASE_USERS_URL + userId + '/two-factor/request'
return this.authHttp.post<TwoFactorEnableResult>(url, { currentPassword })
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
confirmTwoFactorRequest (options: {
@@ -35,7 +33,7 @@ export class TwoFactorService {
const url = UserService.BASE_USERS_URL + userId + '/two-factor/confirm-request'
return this.authHttp.post(url, { requestToken, otpToken })
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
disableTwoFactor (options: {
diff --git a/client/src/app/shared/shared-users/user-admin.service.ts b/client/src/app/shared/shared-users/user-admin.service.ts
index cc706343f2..294193017e 100644
--- a/client/src/app/shared/shared-users/user-admin.service.ts
+++ b/client/src/app/shared/shared-users/user-admin.service.ts
@@ -2,7 +2,7 @@ import { SortMeta } from 'primeng/api'
import { from, Observable } from 'rxjs'
import { catchError, concatMap, map, switchMap, toArray } from 'rxjs/operators'
import { HttpClient, HttpParams } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { RestExtractor, RestPagination, RestService, ServerService, UserService } from '@app/core'
import { getBytes } from '@root-helpers/bytes'
import { arrayify, peertubeTranslate } from '@peertube/peertube-core-utils'
@@ -10,22 +10,19 @@ import { ResultList, User as UserServerModel, UserCreate, UserUpdate } from '@pe
@Injectable()
export class UserAdminService {
-
- constructor (
- private authHttp: HttpClient,
- private restExtractor: RestExtractor,
- private restService: RestService,
- private serverService: ServerService
- ) { }
+ private authHttp = inject(HttpClient)
+ private restExtractor = inject(RestExtractor)
+ private restService = inject(RestService)
+ private serverService = inject(ServerService)
addUser (userCreate: UserCreate) {
return this.authHttp.post(UserService.BASE_USERS_URL, userCreate)
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
updateUser (userId: number, userUpdate: UserUpdate) {
return this.authHttp.put(UserService.BASE_USERS_URL + userId, userUpdate)
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
updateUsers (users: UserServerModel[], userUpdate: UserUpdate) {
@@ -105,7 +102,7 @@ export class UserAdminService {
)
}
- private formatUser (user: UserServerModel, translations: { [ id: string ]: string } = {}) {
+ private formatUser (user: UserServerModel, translations: { [id: string]: string } = {}) {
let videoQuota
if (user.videoQuota === -1) {
videoQuota = '∞'
diff --git a/client/src/app/shared/shared-video-comment/video-comment-list-admin-owner.component.ts b/client/src/app/shared/shared-video-comment/video-comment-list-admin-owner.component.ts
index 0faf02e20d..a22234a7fd 100644
--- a/client/src/app/shared/shared-video-comment/video-comment-list-admin-owner.component.ts
+++ b/client/src/app/shared/shared-video-comment/video-comment-list-admin-owner.component.ts
@@ -1,5 +1,5 @@
import { NgClass, NgIf } from '@angular/common'
-import { Component, Input, OnDestroy, OnInit } from '@angular/core'
+import { Component, OnDestroy, OnInit, inject, input } from '@angular/core'
import { ActivatedRoute, Router, RouterLink } from '@angular/router'
import { AuthService, ConfirmService, HooksService, MarkdownService, Notifier, PluginService, RestPagination, RestTable } from '@app/core'
import { formatICU } from '@app/helpers'
@@ -39,8 +39,19 @@ import { TableExpanderIconComponent } from '../shared-tables/table-expander-icon
RouterLink
]
})
-export class VideoCommentListAdminOwnerComponent extends RestTable <VideoCommentForAdminOrUser> implements OnInit, OnDestroy {
- @Input({ required: true }) mode: 'user' | 'admin'
+export class VideoCommentListAdminOwnerComponent extends RestTable<VideoCommentForAdminOrUser> implements OnInit, OnDestroy {
+ protected router = inject(Router)
+ protected route = inject(ActivatedRoute)
+ private auth = inject(AuthService)
+ private notifier = inject(Notifier)
+ private confirmService = inject(ConfirmService)
+ private videoCommentService = inject(VideoCommentService)
+ private markdownRenderer = inject(MarkdownService)
+ private bulkService = inject(BulkService)
+ private hooks = inject(HooksService)
+ private pluginService = inject(PluginService)
+
+ readonly mode = input.required<'user' | 'admin'>()
comments: VideoCommentForAdminOrUser[]
totalRecords = 0
@@ -57,25 +68,10 @@ export class VideoCommentListAdminOwnerComponent extends RestTable <VideoComment
return this.auth.getUser()
}
- constructor (
- protected router: Router,
- protected route: ActivatedRoute,
- private auth: AuthService,
- private notifier: Notifier,
- private confirmService: ConfirmService,
- private videoCommentService: VideoCommentService,
- private markdownRenderer: MarkdownService,
- private bulkService: BulkService,
- private hooks: HooksService,
- private pluginService: PluginService
- ) {
- super()
- }
-
async ngOnInit () {
this.initialize()
- if (this.mode === 'admin') {
+ if (this.mode() === 'admin') {
this.pluginService.addAction('admin-video-comment-list:load-data', () => this.reloadDataInternal())
}
@@ -86,7 +82,7 @@ export class VideoCommentListAdminOwnerComponent extends RestTable <VideoComment
}
ngOnDestroy () {
- if (this.mode === 'admin') {
+ if (this.mode() === 'admin') {
this.pluginService.removeAction('admin-video-comment-list:load-data')
}
}
@@ -97,25 +93,25 @@ export class VideoCommentListAdminOwnerComponent extends RestTable <VideoComment
{
label: $localize`Delete this comment`,
handler: comment => this.removeComment(comment),
- isDisplayed: () => this.mode === 'user' || this.authUser.hasRight(UserRight.MANAGE_ANY_VIDEO_COMMENT)
+ isDisplayed: () => this.mode() === 'user' || this.authUser.hasRight(UserRight.MANAGE_ANY_VIDEO_COMMENT)
},
{
label: $localize`Delete all comments of this account`,
description: $localize`Comments are deleted after a few minutes`,
handler: comment => this.removeCommentsOfAccount(comment),
- isDisplayed: () => this.mode === 'admin' && this.authUser.hasRight(UserRight.MANAGE_ANY_VIDEO_COMMENT)
+ isDisplayed: () => this.mode() === 'admin' && this.authUser.hasRight(UserRight.MANAGE_ANY_VIDEO_COMMENT)
}
],
[
{
label: $localize`Approve this comment`,
handler: comment => this.approveComments([ comment ]),
- isDisplayed: comment => this.mode === 'user' && comment.heldForReview
+ isDisplayed: comment => this.mode() === 'user' && comment.heldForReview
}
]
]
- this.videoCommentActions = this.mode === 'admin'
+ this.videoCommentActions = this.mode() === 'admin'
? await this.hooks.wrapObject(videoCommentActions, 'admin-comments', 'filter:admin-video-comments-list.actions.create.result')
: videoCommentActions
}
@@ -125,24 +121,24 @@ export class VideoCommentListAdminOwnerComponent extends RestTable <VideoComment
{
label: $localize`Delete`,
handler: comments => this.removeComments(comments),
- isDisplayed: () => this.mode === 'user' || this.authUser.hasRight(UserRight.MANAGE_ANY_VIDEO_COMMENT),
+ isDisplayed: () => this.mode() === 'user' || this.authUser.hasRight(UserRight.MANAGE_ANY_VIDEO_COMMENT),
iconName: 'delete'
},
{
label: $localize`Approve`,
handler: comments => this.approveComments(comments),
- isDisplayed: comments => this.mode === 'user' && comments.every(c => c.heldForReview),
+ isDisplayed: comments => this.mode() === 'user' && comments.every(c => c.heldForReview),
iconName: 'tick'
}
]
- this.bulkActions = this.mode === 'admin'
+ this.bulkActions = this.mode() === 'admin'
? await this.hooks.wrapObject(bulkActions, 'admin-comments', 'filter:admin-video-comments-list.bulk-actions.create.result')
: bulkActions
}
private buildInputFilters () {
- if (this.mode === 'admin') {
+ if (this.mode() === 'admin') {
this.inputFilters = [
{
title: $localize`Advanced filters`,
@@ -196,7 +192,7 @@ export class VideoCommentListAdminOwnerComponent extends RestTable <VideoComment
}
protected async reloadDataInternal () {
- const method = this.mode === 'admin'
+ const method = this.mode() === 'admin'
? this.videoCommentService.listAdminVideoComments.bind(this.videoCommentService)
: this.videoCommentService.listVideoCommentsOfMyVideos.bind(this.videoCommentService)
diff --git a/client/src/app/shared/shared-video-comment/video-comment.service.ts b/client/src/app/shared/shared-video-comment/video-comment.service.ts
index 73faa0b97b..ed85b5cf58 100644
--- a/client/src/app/shared/shared-video-comment/video-comment.service.ts
+++ b/client/src/app/shared/shared-video-comment/video-comment.service.ts
@@ -1,5 +1,5 @@
import { HttpClient, HttpParams } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { ComponentPaginationLight, RestExtractor, RestPagination, RestService } from '@app/core'
import { objectLineFeedToHtml } from '@app/helpers'
import {
@@ -22,27 +22,25 @@ import { VideoComment } from './video-comment.model'
@Injectable()
export class VideoCommentService {
+ private authHttp = inject(HttpClient)
+ private restExtractor = inject(RestExtractor)
+ private restService = inject(RestService)
+
static BASE_FEEDS_URL = environment.apiUrl + '/feeds/video-comments.'
private static BASE_VIDEO_URL = environment.apiUrl + '/api/v1/videos/'
private static BASE_ME_URL = environment.apiUrl + '/api/v1/users/me/'
- constructor (
- private authHttp: HttpClient,
- private restExtractor: RestExtractor,
- private restService: RestService
- ) {}
-
addCommentThread (videoId: string, comment: VideoCommentCreate, videoPassword?: string) {
const headers = VideoPasswordService.buildVideoPasswordHeader(videoPassword)
const url = VideoCommentService.BASE_VIDEO_URL + videoId + '/comment-threads'
const normalizedComment = objectLineFeedToHtml(comment, 'text')
return this.authHttp.post<{ comment: VideoCommentServerModel }>(url, normalizedComment, { headers })
- .pipe(
- map(data => this.extractVideoComment(data.comment)),
- catchError(err => this.restExtractor.handleError(err))
- )
+ .pipe(
+ map(data => this.extractVideoComment(data.comment)),
+ catchError(err => this.restExtractor.handleError(err))
+ )
}
addCommentReply (options: { videoId: string, inReplyToCommentId: number, comment: VideoCommentCreate, videoPassword?: string }) {
@@ -52,10 +50,10 @@ export class VideoCommentService {
const normalizedComment = objectLineFeedToHtml(comment, 'text')
return this.authHttp.post<{ comment: VideoCommentServerModel }>(url, normalizedComment, { headers })
- .pipe(
- map(data => this.extractVideoComment(data.comment)),
- catchError(err => this.restExtractor.handleError(err))
- )
+ .pipe(
+ map(data => this.extractVideoComment(data.comment)),
+ catchError(err => this.restExtractor.handleError(err))
+ )
}
// ---------------------------------------------------------------------------
@@ -139,10 +137,10 @@ export class VideoCommentService {
const url = VideoCommentService.BASE_VIDEO_URL + videoId + '/comment-threads'
return this.authHttp.get<ThreadsResultList<VideoComment>>(url, { params, headers })
- .pipe(
- map(result => this.extractVideoComments(result)),
- catchError(err => this.restExtractor.handleError(err))
- )
+ .pipe(
+ map(result => this.extractVideoComments(result)),
+ catchError(err => this.restExtractor.handleError(err))
+ )
}
getVideoThreadComments (parameters: {
@@ -155,11 +153,11 @@ export class VideoCommentService {
const headers = VideoPasswordService.buildVideoPasswordHeader(videoPassword)
return this.authHttp
- .get<VideoCommentThreadTreeServerModel>(url, { headers })
- .pipe(
- map(tree => this.extractVideoCommentTree(tree)),
- catchError(err => this.restExtractor.handleError(err))
- )
+ .get<VideoCommentThreadTreeServerModel>(url, { headers })
+ .pipe(
+ map(tree => this.extractVideoCommentTree(tree)),
+ catchError(err => this.restExtractor.handleError(err))
+ )
}
// ---------------------------------------------------------------------------
@@ -168,8 +166,8 @@ export class VideoCommentService {
const url = `${VideoCommentService.BASE_VIDEO_URL + videoId}/comments/${commentId}`
return this.authHttp
- .delete(url)
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .delete(url)
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
deleteVideoComments (comments: { videoId: number | string, commentId: number }[]) {
diff --git a/client/src/app/shared/shared-video-live/live-stream-information.component.ts b/client/src/app/shared/shared-video-live/live-stream-information.component.ts
index 4c5fd49009..4b3b13ffa6 100644
--- a/client/src/app/shared/shared-video-live/live-stream-information.component.ts
+++ b/client/src/app/shared/shared-video-live/live-stream-information.component.ts
@@ -1,5 +1,5 @@
import { NgFor, NgIf } from '@angular/common'
-import { Component, ElementRef, ViewChild } from '@angular/core'
+import { Component, ElementRef, inject, viewChild } from '@angular/core'
import { RouterLink } from '@angular/router'
import { Video } from '@app/shared/shared-main/video/video.model'
import { NgbModal } from '@ng-bootstrap/ng-bootstrap'
@@ -30,17 +30,15 @@ import { LiveVideoService } from './live-video.service'
providers: [ LiveVideoService ]
})
export class LiveStreamInformationComponent {
- @ViewChild('modal', { static: true }) modal: ElementRef
+ private modalService = inject(NgbModal)
+ private liveVideoService = inject(LiveVideoService)
+
+ readonly modal = viewChild<ElementRef>('modal')
video: Video
live: LiveVideo
latestLiveSessions: LiveVideoSession[] = []
- constructor (
- private modalService: NgbModal,
- private liveVideoService: LiveVideoService
- ) { }
-
show (video: Video) {
this.video = video
this.live = undefined
@@ -48,7 +46,7 @@ export class LiveStreamInformationComponent {
this.loadLiveInfo(video)
this.modalService
- .open(this.modal, { centered: true })
+ .open(this.modal(), { centered: true })
}
getVideoUrl (video: { shortUUID: string }) {
@@ -58,7 +56,7 @@ export class LiveStreamInformationComponent {
getErrorLabel (session: LiveVideoSession) {
if (!session.error) return undefined
- const errors: { [ id in LiveVideoErrorType ]: string } = {
+ const errors: { [id in LiveVideoErrorType]: string } = {
[LiveVideoError.BAD_SOCKET_HEALTH]: $localize`Server too slow`,
[LiveVideoError.BLACKLISTED]: $localize`Live blacklisted`,
[LiveVideoError.DURATION_EXCEEDED]: $localize`Max duration exceeded`,
diff --git a/client/src/app/shared/shared-video-live/live-video.service.ts b/client/src/app/shared/shared-video-live/live-video.service.ts
index 29913ed369..49909cf762 100644
--- a/client/src/app/shared/shared-video-live/live-video.service.ts
+++ b/client/src/app/shared/shared-video-live/live-video.service.ts
@@ -1,6 +1,6 @@
import { catchError } from 'rxjs/operators'
import { HttpClient } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { RestExtractor } from '@app/core'
import { LiveVideo, LiveVideoCreate, LiveVideoSession, LiveVideoUpdate, ResultList, VideoCreateResult } from '@peertube/peertube-models'
import { environment } from '../../../environments/environment'
@@ -8,35 +8,33 @@ import { VideoService } from '../shared-main/video/video.service'
@Injectable()
export class LiveVideoService {
- static BASE_VIDEO_LIVE_URL = environment.apiUrl + '/api/v1/videos/live/'
+ private authHttp = inject(HttpClient)
+ private restExtractor = inject(RestExtractor)
- constructor (
- private authHttp: HttpClient,
- private restExtractor: RestExtractor
- ) {}
+ static BASE_VIDEO_LIVE_URL = environment.apiUrl + '/api/v1/videos/live/'
goLive (video: LiveVideoCreate) {
return this.authHttp
- .post<{ video: VideoCreateResult }>(LiveVideoService.BASE_VIDEO_LIVE_URL, video)
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .post<{ video: VideoCreateResult }>(LiveVideoService.BASE_VIDEO_LIVE_URL, video)
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
getVideoLive (videoId: number | string) {
return this.authHttp
- .get<LiveVideo>(LiveVideoService.BASE_VIDEO_LIVE_URL + videoId)
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .get<LiveVideo>(LiveVideoService.BASE_VIDEO_LIVE_URL + videoId)
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
listSessions (videoId: number | string) {
return this.authHttp
- .get<ResultList<LiveVideoSession>>(LiveVideoService.BASE_VIDEO_LIVE_URL + videoId + '/sessions')
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .get<ResultList<LiveVideoSession>>(LiveVideoService.BASE_VIDEO_LIVE_URL + videoId + '/sessions')
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
findLiveSessionFromVOD (videoId: number | string) {
return this.authHttp
- .get<LiveVideoSession>(VideoService.BASE_VIDEO_URL + '/' + videoId + '/live-session')
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .get<LiveVideoSession>(VideoService.BASE_VIDEO_URL + '/' + videoId + '/live-session')
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
updateLive (videoId: number | string, liveUpdate: LiveVideoUpdate) {
diff --git a/client/src/app/shared/shared-video-miniature/download/subtitle-files-download.component.ts b/client/src/app/shared/shared-video-miniature/download/subtitle-files-download.component.ts
index 089bb23623..2e1e5cbc5d 100644
--- a/client/src/app/shared/shared-video-miniature/download/subtitle-files-download.component.ts
+++ b/client/src/app/shared/shared-video-miniature/download/subtitle-files-download.component.ts
@@ -1,5 +1,5 @@
import { NgFor, NgIf } from '@angular/common'
-import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'
+import { Component, OnInit, input, output } from '@angular/core'
import { NgbNavModule } from '@ng-bootstrap/ng-bootstrap'
import { VideoCaption } from '@peertube/peertube-models'
import { logger } from '@root-helpers/logger'
@@ -16,21 +16,22 @@ import { InputTextComponent } from '../../shared-forms/input-text.component'
]
})
export class SubtitleFilesDownloadComponent implements OnInit {
- @Input({ required: true }) videoCaptions: VideoCaption[]
+ readonly videoCaptions = input.required<VideoCaption[]>()
- @Output() downloaded = new EventEmitter<void>()
+ readonly downloaded = output()
activeNavId: string
getCaptions () {
- if (!this.videoCaptions) return []
+ const videoCaptions = this.videoCaptions()
+ if (!videoCaptions) return []
- return this.videoCaptions
+ return videoCaptions
}
ngOnInit () {
if (this.hasCaptions()) {
- this.activeNavId = this.videoCaptions[0].language.id
+ this.activeNavId = this.videoCaptions()[0].language.id
}
}
diff --git a/client/src/app/shared/shared-video-miniature/download/video-download.component.ts b/client/src/app/shared/shared-video-miniature/download/video-download.component.ts
index b10995955a..b5d2428cd3 100644
--- a/client/src/app/shared/shared-video-miniature/download/video-download.component.ts
+++ b/client/src/app/shared/shared-video-miniature/download/video-download.component.ts
@@ -1,5 +1,5 @@
import { NgClass, NgIf, NgTemplateOutlet } from '@angular/common'
-import { Component, ElementRef, Input, ViewChild } from '@angular/core'
+import { Component, ElementRef, inject, input, viewChild } from '@angular/core'
import { FormsModule } from '@angular/forms'
import { AuthService, HooksService } from '@app/core'
import { GlobalIconComponent } from '@app/shared/shared-icons/global-icon.component'
@@ -33,9 +33,15 @@ type DownloadType = 'video-generate' | 'video-files' | 'subtitle-files'
]
})
export class VideoDownloadComponent {
- @ViewChild('modal', { static: true }) modal: ElementRef
+ private modalService = inject(NgbModal)
+ private authService = inject(AuthService)
+ private videoService = inject(VideoService)
+ private videoFileTokenService = inject(VideoFileTokenService)
+ private hooks = inject(HooksService)
- @Input() videoPassword: string
+ readonly modal = viewChild<ElementRef>('modal')
+
+ readonly videoPassword = input<string>(undefined)
video: VideoDetails
type: DownloadType = 'video-generate'
@@ -48,14 +54,6 @@ export class VideoDownloadComponent {
private videoCaptions: VideoCaption[]
private activeModal: NgbModalRef
- constructor (
- private modalService: NgbModal,
- private authService: AuthService,
- private videoService: VideoService,
- private videoFileTokenService: VideoFileTokenService,
- private hooks: HooksService
- ) {}
-
getCaptions () {
if (!this.videoCaptions) return []
@@ -71,7 +69,7 @@ export class VideoDownloadComponent {
this.video = video
this.videoCaptions = videoCaptions
- this.activeModal = this.modalService.open(this.modal, { centered: true })
+ this.activeModal = this.modalService.open(this.modal(), { centered: true })
this.getOriginalVideoFileObs()
.subscribe(source => {
@@ -80,7 +78,7 @@ export class VideoDownloadComponent {
}
if (this.originalVideoFile || videoRequiresFileToken(this.video)) {
- this.videoFileTokenService.getVideoFileToken({ videoUUID: this.video.uuid, videoPassword: this.videoPassword })
+ this.videoFileTokenService.getVideoFileToken({ videoUUID: this.video.uuid, videoPassword: this.videoPassword() })
.subscribe(({ token }) => {
this.videoFileToken = token
diff --git a/client/src/app/shared/shared-video-miniature/download/video-files-download.component.html b/client/src/app/shared/shared-video-miniature/download/video-files-download.component.html
index 705f4abc26..49427b13a6 100644
--- a/client/src/app/shared/shared-video-miniature/download/video-files-download.component.html
+++ b/client/src/app/shared/shared-video-miniature/download/video-files-download.component.html
@@ -14,7 +14,7 @@
</div>
</ng-template>
- <ng-container *ngIf="originalVideoFile" ngbNavItem="original">
+ <ng-container *ngIf="originalVideoFile()" ngbNavItem="original">
<a ngbNavLink>
<ng-container i18n>Original file</ng-container>
@@ -91,7 +91,7 @@
<div *ngIf="hasMetadata()" [ngbNavOutlet]="navMetadata"></div>
- <div [hidden]="originalVideoFile || !getVideoFile()?.torrentDownloadUrl" class="download-type">
+ <div [hidden]="originalVideoFile() || !getVideoFile()?.torrentDownloadUrl" class="download-type">
<div class="peertube-radio-container">
<input type="radio" name="download" id="download-direct" [(ngModel)]="downloadType" value="direct">
<label i18n for="download-direct">Direct download</label>
diff --git a/client/src/app/shared/shared-video-miniature/download/video-files-download.component.ts b/client/src/app/shared/shared-video-miniature/download/video-files-download.component.ts
index 4390b1f19f..2cc500ed40 100644
--- a/client/src/app/shared/shared-video-miniature/download/video-files-download.component.ts
+++ b/client/src/app/shared/shared-video-miniature/download/video-files-download.component.ts
@@ -1,5 +1,5 @@
import { KeyValuePipe, NgFor, NgIf, NgTemplateOutlet } from '@angular/common'
-import { Component, EventEmitter, Inject, Input, LOCALE_ID, OnInit, Output } from '@angular/core'
+import { Component, LOCALE_ID, OnInit, inject, input, output } from '@angular/core'
import { FormsModule } from '@angular/forms'
import { AlertComponent } from '@app/shared/shared-main/common/alert.component'
import {
@@ -42,11 +42,14 @@ type FileMetadata = { [key: string]: { label: string, value: string | number } }
]
})
export class VideoFilesDownloadComponent implements OnInit {
- @Input({ required: true }) video: VideoDetails
- @Input() originalVideoFile: VideoSource
- @Input() videoFileToken: string
+ private localeId = inject(LOCALE_ID)
+ private videoService = inject(VideoService)
- @Output() downloaded = new EventEmitter<void>()
+ readonly video = input.required<VideoDetails>()
+ readonly originalVideoFile = input<VideoSource>(undefined)
+ readonly videoFileToken = input<string>(undefined)
+
+ readonly downloaded = output()
downloadType: 'direct' | 'torrent' = 'direct'
@@ -61,26 +64,23 @@ export class VideoFilesDownloadComponent implements OnInit {
private bytesPipe: BytesPipe
private numbersPipe: NumberFormatterPipe
- constructor (
- @Inject(LOCALE_ID) private localeId: string,
- private videoService: VideoService
- ) {
+ constructor () {
this.bytesPipe = new BytesPipe()
this.numbersPipe = new NumberFormatterPipe(this.localeId)
}
ngOnInit () {
-
if (this.hasFiles()) {
this.onResolutionIdChange(this.getVideoFiles()[0].resolution.id)
}
}
getVideoFiles () {
- if (!this.video) return []
- if (this.video.files.length !== 0) return this.video.files
+ const video = this.video()
+ if (!video) return []
+ if (video.files.length !== 0) return video.files
- const hls = this.video.getHlsPlaylist()
+ const hls = video.getHlsPlaylist()
if (hls) return hls.files
return []
@@ -102,7 +102,7 @@ export class VideoFilesDownloadComponent implements OnInit {
let metadata: VideoFileMetadata
if (this.activeResolutionId === 'original') {
- metadata = this.originalVideoFile.metadata
+ metadata = this.originalVideoFile().metadata
} else {
const videoFile = this.getVideoFile()
if (!videoFile) return
@@ -143,11 +143,11 @@ export class VideoFilesDownloadComponent implements OnInit {
getVideoFileLink () {
const suffix = this.activeResolutionId === 'original' || this.isConfidentialVideo()
- ? '?videoFileToken=' + this.videoFileToken
+ ? '?videoFileToken=' + this.videoFileToken()
: ''
if (this.activeResolutionId === 'original') {
- return this.originalVideoFile.fileDownloadUrl + suffix
+ return this.originalVideoFile().fileDownloadUrl + suffix
}
const file = this.getVideoFile()
@@ -165,7 +165,7 @@ export class VideoFilesDownloadComponent implements OnInit {
// ---------------------------------------------------------------------------
isConfidentialVideo () {
- return this.activeResolutionId === 'original' || videoRequiresFileToken(this.video)
+ return this.activeResolutionId === 'original' || videoRequiresFileToken(this.video())
}
// ---------------------------------------------------------------------------
diff --git a/client/src/app/shared/shared-video-miniature/download/video-generate-download.component.html b/client/src/app/shared/shared-video-miniature/download/video-generate-download.component.html
index 9de7d6759d..2853efe0cd 100644
--- a/client/src/app/shared/shared-video-miniature/download/video-generate-download.component.html
+++ b/client/src/app/shared/shared-video-miniature/download/video-generate-download.component.html
@@ -1,12 +1,12 @@
<div class="form-group">
- <div *ngIf="originalVideoFile" class="peertube-radio-container">
+ <div *ngIf="originalVideoFile()" class="peertube-radio-container">
<input type="radio" name="video-file" id="original-file" [(ngModel)]="videoFileChosen" value="file-original">
<label for="original-file">
<strong i18n>Original file</strong>
- <span class="muted">{{ originalVideoFile.size | bytes: 1 }} | {{ originalVideoFile.width }}x{{ originalVideoFile.height }}</span>
+ <span class="muted">{{ originalVideoFile().size | bytes: 1 }} | {{ originalVideoFile().width }}x{{ originalVideoFile().height }}</span>
<my-global-icon i18n-ngbTooltip ngbTooltip="Other users cannot download the original file" iconName="shield"></my-global-icon>
</label>
diff --git a/client/src/app/shared/shared-video-miniature/download/video-generate-download.component.ts b/client/src/app/shared/shared-video-miniature/download/video-generate-download.component.ts
index f69fcf4f7b..4c6fec4686 100644
--- a/client/src/app/shared/shared-video-miniature/download/video-generate-download.component.ts
+++ b/client/src/app/shared/shared-video-miniature/download/video-generate-download.component.ts
@@ -1,5 +1,5 @@
import { NgIf } from '@angular/common'
-import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'
+import { Component, OnInit, inject, input, output } from '@angular/core'
import { FormsModule } from '@angular/forms'
import { PeertubeCheckboxComponent } from '@app/shared/shared-forms/peertube-checkbox.component'
import { VideoService } from '@app/shared/shared-main/video/video.service'
@@ -25,19 +25,18 @@ import { VideoDetails } from '../../shared-main/video/video-details.model'
]
})
export class VideoGenerateDownloadComponent implements OnInit {
- @Input({ required: true }) video: VideoDetails
- @Input() originalVideoFile: VideoSource
- @Input() videoFileToken: string
+ private videoService = inject(VideoService)
- @Output() downloaded = new EventEmitter<void>()
+ readonly video = input.required<VideoDetails>()
+ readonly originalVideoFile = input<VideoSource>(undefined)
+ readonly videoFileToken = input<string>(undefined)
+
+ readonly downloaded = output()
includeAudio = true
videoFileChosen = ''
videoFiles: VideoFile[]
- constructor (private videoService: VideoService) {
- }
-
ngOnInit () {
this.videoFiles = this.buildVideoFiles()
if (this.videoFiles.length === 0) return
@@ -81,11 +80,11 @@ export class VideoGenerateDownloadComponent implements OnInit {
getVideoFileLink () {
const suffix = this.videoFileChosen === 'file-original' || this.isConfidentialVideo()
- ? '?videoFileToken=' + this.videoFileToken
+ ? '?videoFileToken=' + this.videoFileToken()
: ''
if (this.videoFileChosen === 'file-original') {
- return this.originalVideoFile.fileDownloadUrl + suffix
+ return this.originalVideoFile().fileDownloadUrl + suffix
}
const file = this.findCurrentFile()
@@ -97,24 +96,25 @@ export class VideoGenerateDownloadComponent implements OnInit {
files.push(this.findAudioFileOnly())
}
- return this.videoService.generateDownloadUrl({ video: this.video, videoFileToken: this.videoFileToken, files })
+ return this.videoService.generateDownloadUrl({ video: this.video(), videoFileToken: this.videoFileToken(), files })
}
// ---------------------------------------------------------------------------
isConfidentialVideo () {
- return this.videoFileChosen === 'file-original' || videoRequiresFileToken(this.video)
+ return this.videoFileChosen === 'file-original' || videoRequiresFileToken(this.video())
}
// ---------------------------------------------------------------------------
private buildVideoFiles () {
- if (!this.video) return []
+ const video = this.video()
+ if (!video) return []
- const hls = this.video.getHlsPlaylist()
+ const hls = video.getHlsPlaylist()
if (hls) return hls.files
- return this.video.files
+ return video.files
}
private findCurrentFile () {
diff --git a/client/src/app/shared/shared-video-miniature/video-actions-dropdown.component.html b/client/src/app/shared/shared-video-miniature/video-actions-dropdown.component.html
index 4fb67f6b5d..b70add2a31 100644
--- a/client/src/app/shared/shared-video-miniature/video-actions-dropdown.component.html
+++ b/client/src/app/shared/shared-video-miniature/video-actions-dropdown.component.html
@@ -1,7 +1,7 @@
<ng-container *ngIf="videoActions.length !== 0">
<div
- *ngIf="isUserLoggedIn() && displayOptions.playlist"
+ *ngIf="isUserLoggedIn() && displayOptions().playlist"
role="button" aria-label="Open video actions" i18n-aria-label
class="playlist-dropdown" ngbDropdown #playlistDropdown="ngbDropdown" autoClose="outside"
container="body" [placement]="getPlaylistDropdownPlacement()"
@@ -10,19 +10,19 @@
<div ngbDropdownMenu>
@defer (when dropdownOpened) {
- <my-video-add-to-playlist #playlistAdd [video]="video"></my-video-add-to-playlist>
+ <my-video-add-to-playlist #playlistAdd [video]="video()"></my-video-add-to-playlist>
}
</div>
</div>
<my-action-dropdown
- [actions]="videoActions" [label]="label" [entry]="{ video: video }"
- [buttonSize]="buttonSize" [placement]="placement" [buttonDirection]="buttonDirection" [buttonStyled]="buttonStyled"
+ [actions]="videoActions" [label]="label()" [entry]="{ video: video() }"
+ [buttonSize]="buttonSize()" [placement]="placement()" [buttonDirection]="buttonDirection()" [buttonStyled]="buttonStyled()"
container="body" (openChange)="dropdownOpened = true"
></my-action-dropdown>
<my-video-download #videoDownloadModal></my-video-download>
- <my-video-report #videoReportModal [video]="video"></my-video-report>
+ <my-video-report #videoReportModal [video]="video()"></my-video-report>
<my-video-block #videoBlockModal (videoBlocked)="onVideoBlocked()"></my-video-block>
- <my-live-stream-information #liveStreamInformationModal *ngIf="displayOptions.liveInfo"></my-live-stream-information>
+ <my-live-stream-information #liveStreamInformationModal *ngIf="displayOptions().liveInfo"></my-live-stream-information>
</ng-container>
diff --git a/client/src/app/shared/shared-video-miniature/video-actions-dropdown.component.ts b/client/src/app/shared/shared-video-miniature/video-actions-dropdown.component.ts
index f29ff552e0..f6fa12d1c5 100644
--- a/client/src/app/shared/shared-video-miniature/video-actions-dropdown.component.ts
+++ b/client/src/app/shared/shared-video-miniature/video-actions-dropdown.component.ts
@@ -1,5 +1,5 @@
import { NgIf } from '@angular/common'
-import { Component, EventEmitter, Input, OnChanges, Output, ViewChild, booleanAttribute } from '@angular/core'
+import { Component, OnChanges, booleanAttribute, inject, input, output, viewChild } from '@angular/core'
import { AuthService, ConfirmService, Notifier, ScreenService, ServerService } from '@app/core'
import { NgbDropdown, NgbDropdownAnchor, NgbDropdownMenu } from '@ng-bootstrap/ng-bootstrap'
import { VideoCaption } from '@peertube/peertube-models'
@@ -60,18 +60,29 @@ export type VideoActionsDisplayType = {
]
})
export class VideoActionsDropdownComponent implements OnChanges {
- @ViewChild('playlistDropdown') playlistDropdown: NgbDropdown
- @ViewChild('playlistAdd') playlistAdd: VideoAddToPlaylistComponent
-
- @ViewChild('videoDownloadModal') videoDownloadModal: VideoDownloadComponent
- @ViewChild('videoReportModal') videoReportModal: VideoReportComponent
- @ViewChild('videoBlockModal') videoBlockModal: VideoBlockComponent
- @ViewChild('liveStreamInformationModal') liveStreamInformationModal: LiveStreamInformationComponent
-
- @Input() video: Video | VideoDetails
- @Input() videoCaptions: VideoCaption[] = []
-
- @Input() displayOptions: VideoActionsDisplayType = {
+ private authService = inject(AuthService)
+ private notifier = inject(Notifier)
+ private confirmService = inject(ConfirmService)
+ private blocklistService = inject(BlocklistService)
+ private videoBlocklistService = inject(VideoBlockService)
+ private screenService = inject(ScreenService)
+ private videoService = inject(VideoService)
+ private videoCaptionService = inject(VideoCaptionService)
+ private redundancyService = inject(RedundancyService)
+ private serverService = inject(ServerService)
+
+ readonly playlistDropdown = viewChild<NgbDropdown>('playlistDropdown')
+ readonly playlistAdd = viewChild<VideoAddToPlaylistComponent>('playlistAdd')
+
+ readonly videoDownloadModal = viewChild<VideoDownloadComponent>('videoDownloadModal')
+ readonly videoReportModal = viewChild<VideoReportComponent>('videoReportModal')
+ readonly videoBlockModal = viewChild<VideoBlockComponent>('videoBlockModal')
+ readonly liveStreamInformationModal = viewChild<LiveStreamInformationComponent>('liveStreamInformationModal')
+
+ readonly video = input<Video | VideoDetails>(undefined)
+ readonly videoCaptions = input<VideoCaption[]>([])
+
+ readonly displayOptions = input<VideoActionsDisplayType>({
playlist: false,
download: true,
update: true,
@@ -87,29 +98,31 @@ export class VideoActionsDropdownComponent implements OnChanges {
stats: true,
generateTranscription: false,
transcriptionWidget: false
- }
- @Input() placement = 'auto'
- @Input() moreActions: DropdownAction<{ video: Video }>[][] = []
- @Input({ transform: booleanAttribute }) actionAvailabilityHint = false
+ })
+ readonly placement = input('auto')
+ readonly moreActions = input<DropdownAction<{
+ video: Video
+ }>[][]>([])
+ readonly actionAvailabilityHint = input(false, { transform: booleanAttribute })
- @Input() label: string
+ readonly label = input<string>(undefined)
- @Input({ transform: booleanAttribute }) buttonStyled = false
- @Input() buttonSize: DropdownButtonSize = 'normal'
- @Input() buttonDirection: DropdownDirection = 'vertical'
+ readonly buttonStyled = input(false, { transform: booleanAttribute })
+ readonly buttonSize = input<DropdownButtonSize>('normal')
+ readonly buttonDirection = input<DropdownDirection>('vertical')
- @Input() transcriptionWidgetOpened: boolean
+ readonly transcriptionWidgetOpened = input<boolean>(undefined)
- @Output() videoFilesRemoved = new EventEmitter()
- @Output() videoRemoved = new EventEmitter()
- @Output() videoUnblocked = new EventEmitter()
- @Output() videoBlocked = new EventEmitter()
- @Output() videoAccountMuted = new EventEmitter()
- @Output() transcodingCreated = new EventEmitter()
- @Output() modalOpened = new EventEmitter()
+ readonly videoFilesRemoved = output()
+ readonly videoRemoved = output()
+ readonly videoUnblocked = output()
+ readonly videoBlocked = output()
+ readonly videoAccountMuted = output()
+ readonly transcodingCreated = output()
+ readonly modalOpened = output()
- @Output() showTranscriptionWidget = new EventEmitter()
- @Output() hideTranscriptionWidget = new EventEmitter()
+ readonly showTranscriptionWidget = output()
+ readonly hideTranscriptionWidget = output()
videoActions: DropdownAction<{ video: Video }>[][] = []
@@ -117,25 +130,13 @@ export class VideoActionsDropdownComponent implements OnChanges {
private hasMutedAccount = false
- constructor (
- private authService: AuthService,
- private notifier: Notifier,
- private confirmService: ConfirmService,
- private blocklistService: BlocklistService,
- private videoBlocklistService: VideoBlockService,
- private screenService: ScreenService,
- private videoService: VideoService,
- private videoCaptionService: VideoCaptionService,
- private redundancyService: RedundancyService,
- private serverService: ServerService
- ) { }
-
get user () {
return this.authService.getUser()
}
ngOnChanges () {
- if (this.playlistAdd) this.playlistAdd.reload()
+ const playlistAdd = this.playlistAdd()
+ if (playlistAdd) playlistAdd.reload()
this.buildActions()
}
@@ -151,31 +152,32 @@ export class VideoActionsDropdownComponent implements OnChanges {
showDownloadModal () {
this.modalOpened.emit()
- const obs = this.video instanceof VideoDetails
- ? of(this.video)
- : this.videoService.getVideo({ videoId: this.video.uuid })
+ const video = this.video()
+ const obs = video instanceof VideoDetails
+ ? of(video)
+ : this.videoService.getVideo({ videoId: video.uuid })
obs.subscribe((videoDetails: VideoDetails) => {
- this.videoDownloadModal.show(videoDetails, this.videoCaptions)
+ this.videoDownloadModal().show(videoDetails, this.videoCaptions())
})
}
showReportModal () {
this.modalOpened.emit()
- this.videoReportModal.show()
+ this.videoReportModal().show()
}
showBlockModal () {
this.modalOpened.emit()
- this.videoBlockModal.show([ this.video ])
+ this.videoBlockModal().show([ this.video() ])
}
showLiveInfoModal (video: Video) {
this.modalOpened.emit()
- this.liveStreamInformationModal.show(video)
+ this.liveStreamInformationModal().show(video)
}
// ---------------------------------------------------------------------------
@@ -185,69 +187,72 @@ export class VideoActionsDropdownComponent implements OnChanges {
isVideoUpdatable () {
if (!this.user) return false
- return this.video.isUpdatableBy(this.user)
+ return this.video().isUpdatableBy(this.user)
}
isVideoEditable () {
if (!this.user) return false
- return this.video.isEditableBy(this.user, this.serverService.getHTMLConfig().videoStudio.enabled)
+ return this.video().isEditableBy(this.user, this.serverService.getHTMLConfig().videoStudio.enabled)
}
isVideoStatsAvailable () {
if (!this.user) return false
- return this.video.isLocal && this.video.isOwnerOrHasSeeAllVideosRight(this.user)
+ const video = this.video()
+ return video.isLocal && video.isOwnerOrHasSeeAllVideosRight(this.user)
}
isVideoRemovable () {
if (!this.user) return false
- return this.video.isRemovableBy(this.user)
+ return this.video().isRemovableBy(this.user)
}
isVideoBlockable () {
if (!this.user) return false
- return this.video.isBlockableBy(this.user)
+ return this.video().isBlockableBy(this.user)
}
isVideoUnblockable () {
if (!this.user) return false
- return this.video.isUnblockableBy(this.user)
+ return this.video().isUnblockableBy(this.user)
}
isVideoLiveInfoAvailable () {
if (!this.user) return false
- return this.video.isLiveInfoAvailableBy(this.user)
+ return this.video().isLiveInfoAvailableBy(this.user)
}
canGenerateTranscription () {
if (!this.user) return false
- return this.video.canGenerateTranscription(this.user, this.serverService.getHTMLConfig().videoTranscription.enabled)
+ return this.video().canGenerateTranscription(this.user, this.serverService.getHTMLConfig().videoTranscription.enabled)
}
// ---------------------------------------------------------------------------
isVideoDownloadableByAnonymous () {
+ const video = this.video()
return (
- this.video &&
- this.video.isLive !== true &&
- this.video instanceof VideoDetails &&
- this.video.downloadEnabled
+ video &&
+ video.isLive !== true &&
+ video instanceof VideoDetails &&
+ video.downloadEnabled
)
}
isVideoDownloadableByUser () {
if (!this.user) return false
+ const video = this.video()
return (
- this.video &&
- this.video.isLive !== true &&
- this.video.isOwnerOrHasSeeAllVideosRight(this.user)
+ video &&
+ video.isLive !== true &&
+ video.isOwnerOrHasSeeAllVideosRight(this.user)
)
}
@@ -256,25 +261,26 @@ export class VideoActionsDropdownComponent implements OnChanges {
canVideoBeDuplicated () {
if (!this.user) return false
- return !this.video.isLive && this.video.canBeDuplicatedBy(this.user)
+ const video = this.video()
+ return !video.isLive && video.canBeDuplicatedBy(this.user)
}
isVideoAccountMutable () {
if (!this.user) return false
- return this.video.account.id !== this.user.account.id
+ return this.video().account.id !== this.user.account.id
}
canRemoveVideoFiles () {
if (!this.user) return false
- return this.video.canRemoveAllHLSOrWebFiles(this.user)
+ return this.video().canRemoveAllHLSOrWebFiles(this.user)
}
canRunTranscoding () {
if (!this.user) return false
- return this.video.canRunTranscoding(this.user)
+ return this.video().canRunTranscoding(this.user)
}
// ---------------------------------------------------------------------------
@@ -282,93 +288,95 @@ export class VideoActionsDropdownComponent implements OnChanges {
// ---------------------------------------------------------------------------
async unblockVideo () {
- const confirmMessage = $localize`Do you really want to unblock ${this.video.name}? It will be available again in the videos list.`
+ const confirmMessage = $localize`Do you really want to unblock ${this.video().name}? It will be available again in the videos list.`
- const res = await this.confirmService.confirm(confirmMessage, $localize`Unblock ${this.video.name}`)
+ const res = await this.confirmService.confirm(confirmMessage, $localize`Unblock ${this.video().name}`)
if (res === false) return
- this.videoBlocklistService.unblockVideo(this.video.id)
- .subscribe({
- next: () => {
- this.notifier.success($localize`Video ${this.video.name} unblocked.`)
+ this.videoBlocklistService.unblockVideo(this.video().id)
+ .subscribe({
+ next: () => {
+ const video = this.video()
+ this.notifier.success($localize`Video ${video.name} unblocked.`)
- this.video.blacklisted = false
- this.video.blacklistedReason = null
+ video.blacklisted = false
+ video.blacklistedReason = null
- this.videoUnblocked.emit()
- },
+ this.videoUnblocked.emit()
+ },
- error: err => this.notifier.error(err.message)
- })
+ error: err => this.notifier.error(err.message)
+ })
}
async removeVideo () {
this.modalOpened.emit()
- let message = $localize`Do you really want to delete ${this.video.name}?`
- if (this.video.isLive) {
+ let message = $localize`Do you really want to delete ${this.video().name}?`
+ const video = this.video()
+ if (video.isLive) {
message += ' ' + $localize`The live stream will be automatically terminated and replays won't be saved.`
}
- const res = await this.confirmService.confirm(message, $localize`Delete ${this.video.name}`)
+ const res = await this.confirmService.confirm(message, $localize`Delete ${video.name}`)
if (res === false) return
- this.videoService.removeVideo(this.video.id)
- .subscribe({
- next: () => {
- this.notifier.success($localize`Video ${this.video.name} deleted.`)
- this.videoRemoved.emit()
- },
+ this.videoService.removeVideo(video.id)
+ .subscribe({
+ next: () => {
+ this.notifier.success($localize`Video ${this.video().name} deleted.`)
+ this.videoRemoved.emit()
+ },
- error: err => this.notifier.error(err.message)
- })
+ error: err => this.notifier.error(err.message)
+ })
}
duplicateVideo () {
- this.redundancyService.addVideoRedundancy(this.video)
- .subscribe({
- next: () => {
- const message = $localize`${this.video.name} will be duplicated by your platform.`
- this.notifier.success(message)
- },
+ this.redundancyService.addVideoRedundancy(this.video())
+ .subscribe({
+ next: () => {
+ const message = $localize`${this.video().name} will be duplicated by your platform.`
+ this.notifier.success(message)
+ },
- error: err => this.notifier.error(err.message)
- })
+ error: err => this.notifier.error(err.message)
+ })
}
muteVideoAccount () {
- const params = { nameWithHost: Actor.CREATE_BY_STRING(this.video.account.name, this.video.account.host) }
+ const params = { nameWithHost: Actor.CREATE_BY_STRING(this.video().account.name, this.video().account.host) }
this.blocklistService.blockAccountByUser(params)
- .subscribe({
- next: () => {
- this.notifier.success($localize`Account ${params.nameWithHost} muted.`)
- this.hasMutedAccount = true
- this.videoAccountMuted.emit()
- },
+ .subscribe({
+ next: () => {
+ this.notifier.success($localize`Account ${params.nameWithHost} muted.`)
+ this.hasMutedAccount = true
+ this.videoAccountMuted.emit()
+ },
- error: err => this.notifier.error(err.message)
- })
+ error: err => this.notifier.error(err.message)
+ })
}
unmuteVideoAccount () {
- const params = { nameWithHost: Actor.CREATE_BY_STRING(this.video.account.name, this.video.account.host) }
+ const params = { nameWithHost: Actor.CREATE_BY_STRING(this.video().account.name, this.video().account.host) }
this.blocklistService.unblockAccountByUser(params)
- .subscribe({
- next: () => {
- this.hasMutedAccount = false
- this.notifier.success($localize`Account ${params.nameWithHost} unmuted.`)
- },
+ .subscribe({
+ next: () => {
+ this.hasMutedAccount = false
+ this.notifier.success($localize`Account ${params.nameWithHost} unmuted.`)
+ },
- error: err => this.notifier.error(err.message)
- })
+ error: err => this.notifier.error(err.message)
+ })
}
async removeVideoFiles (video: Video, type: 'hls' | 'web-videos') {
- const confirmMessage = $localize`Do you really want to remove "${this.video.name}" files?`
+ const confirmMessage = $localize`Do you really want to remove "${this.video().name}" files?`
- const res = await this.confirmService.confirm(confirmMessage, $localize`Remove "${this.video.name}" files`)
+ const res = await this.confirmService.confirm(confirmMessage, $localize`Remove "${this.video().name}" files`)
if (res === false) return
this.videoService.removeVideoFiles([ video.id ], type)
@@ -424,8 +432,8 @@ export class VideoActionsDropdownComponent implements OnChanges {
[
{
label: $localize`Save to playlist`,
- handler: () => this.playlistDropdown.toggle(),
- isDisplayed: () => this.authService.isLoggedIn() && this.displayOptions.playlist,
+ handler: () => this.playlistDropdown().toggle(),
+ isDisplayed: () => this.authService.isLoggedIn() && this.displayOptions().playlist,
iconName: 'playlist-add'
}
],
@@ -434,13 +442,13 @@ export class VideoActionsDropdownComponent implements OnChanges {
label: $localize`Download`,
handler: () => this.showDownloadModal(),
isDisplayed: () => {
- if (!this.displayOptions.download) return false
+ if (!this.displayOptions().download) return false
return this.isVideoDownloadableByAnonymous() || this.isVideoDownloadableByUser()
},
iconName: 'download',
ownerOrModeratorPrivilege: () => {
- if (!this.actionAvailabilityHint) return undefined
+ if (!this.actionAvailabilityHint()) return undefined
if (this.isVideoDownloadableByAnonymous()) return undefined
return $localize`This option is visible only to you`
@@ -450,10 +458,11 @@ export class VideoActionsDropdownComponent implements OnChanges {
label: $localize`Show transcription`,
handler: () => this.showTranscriptionWidget.emit(),
isDisplayed: () => {
- if (!this.displayOptions.transcriptionWidget) return false
- if (this.transcriptionWidgetOpened) return false
+ if (!this.displayOptions().transcriptionWidget) return false
+ if (this.transcriptionWidgetOpened()) return false
- return Array.isArray(this.videoCaptions) && this.videoCaptions.length !== 0
+ const videoCaptions = this.videoCaptions()
+ return Array.isArray(videoCaptions) && videoCaptions.length !== 0
},
iconName: 'video-lang'
},
@@ -461,9 +470,9 @@ export class VideoActionsDropdownComponent implements OnChanges {
label: $localize`Hide transcription`,
handler: () => this.hideTranscriptionWidget.emit(),
isDisplayed: () => {
- if (!this.displayOptions.transcriptionWidget) return false
+ if (!this.displayOptions().transcriptionWidget) return false
- return this.transcriptionWidgetOpened === true
+ return this.transcriptionWidgetOpened() === true
},
iconName: 'video-lang'
}
@@ -472,55 +481,55 @@ export class VideoActionsDropdownComponent implements OnChanges {
{
label: $localize`Display live information`,
handler: ({ video }) => this.showLiveInfoModal(video),
- isDisplayed: () => this.displayOptions.liveInfo && this.isVideoLiveInfoAvailable(),
+ isDisplayed: () => this.displayOptions().liveInfo && this.isVideoLiveInfoAvailable(),
iconName: 'live'
},
{
label: $localize`Update`,
linkBuilder: ({ video }) => [ '/videos/update', video.shortUUID ],
iconName: 'edit',
- isDisplayed: () => this.authService.isLoggedIn() && this.displayOptions.update && this.isVideoUpdatable()
+ isDisplayed: () => this.authService.isLoggedIn() && this.displayOptions().update && this.isVideoUpdatable()
},
{
label: $localize`Studio`,
linkBuilder: ({ video }) => [ '/studio/edit', video.shortUUID ],
iconName: 'film',
- isDisplayed: () => this.authService.isLoggedIn() && this.displayOptions.studio && this.isVideoEditable()
+ isDisplayed: () => this.authService.isLoggedIn() && this.displayOptions().studio && this.isVideoEditable()
},
{
label: $localize`Stats`,
linkBuilder: ({ video }) => [ '/stats/videos', video.shortUUID ],
iconName: 'stats',
- isDisplayed: () => this.authService.isLoggedIn() && this.displayOptions.stats && this.isVideoStatsAvailable()
+ isDisplayed: () => this.authService.isLoggedIn() && this.displayOptions().stats && this.isVideoStatsAvailable()
},
{
label: $localize`Block`,
handler: () => this.showBlockModal(),
iconName: 'no',
- isDisplayed: () => this.authService.isLoggedIn() && this.displayOptions.blacklist && this.isVideoBlockable()
+ isDisplayed: () => this.authService.isLoggedIn() && this.displayOptions().blacklist && this.isVideoBlockable()
},
{
label: $localize`Unblock`,
handler: () => this.unblockVideo(),
iconName: 'undo',
- isDisplayed: () => this.authService.isLoggedIn() && this.displayOptions.blacklist && this.isVideoUnblockable()
+ isDisplayed: () => this.authService.isLoggedIn() && this.displayOptions().blacklist && this.isVideoUnblockable()
},
{
label: $localize`Mirror`,
handler: () => this.duplicateVideo(),
- isDisplayed: () => this.authService.isLoggedIn() && this.displayOptions.duplicate && this.canVideoBeDuplicated(),
+ isDisplayed: () => this.authService.isLoggedIn() && this.displayOptions().duplicate && this.canVideoBeDuplicated(),
iconName: 'cloud-download'
},
{
label: $localize`Delete`,
handler: () => this.removeVideo(),
- isDisplayed: () => this.authService.isLoggedIn() && this.displayOptions.delete && this.isVideoRemovable(),
+ isDisplayed: () => this.authService.isLoggedIn() && this.displayOptions().delete && this.isVideoRemovable(),
iconName: 'delete'
},
{
label: $localize`Report`,
handler: () => this.showReportModal(),
- isDisplayed: () => this.authService.isLoggedIn() && this.displayOptions.report,
+ isDisplayed: () => this.authService.isLoggedIn() && this.displayOptions().report,
iconName: 'flag'
}
],
@@ -528,25 +537,25 @@ export class VideoActionsDropdownComponent implements OnChanges {
{
label: $localize`Run HLS transcoding`,
handler: ({ video }) => this.runTranscoding(video, 'hls'),
- isDisplayed: () => this.displayOptions.transcoding && this.canRunTranscoding(),
+ isDisplayed: () => this.displayOptions().transcoding && this.canRunTranscoding(),
iconName: 'cog'
},
{
label: $localize`Run Web Video transcoding`,
handler: ({ video }) => this.runTranscoding(video, 'web-video'),
- isDisplayed: () => this.displayOptions.transcoding && this.canRunTranscoding(),
+ isDisplayed: () => this.displayOptions().transcoding && this.canRunTranscoding(),
iconName: 'cog'
},
{
label: $localize`Delete HLS files`,
handler: ({ video }) => this.removeVideoFiles(video, 'hls'),
- isDisplayed: () => this.displayOptions.removeFiles && this.canRemoveVideoFiles(),
+ isDisplayed: () => this.displayOptions().removeFiles && this.canRemoveVideoFiles(),
iconName: 'delete'
},
{
label: $localize`Delete Web Video files`,
handler: ({ video }) => this.removeVideoFiles(video, 'web-videos'),
- isDisplayed: () => this.displayOptions.removeFiles && this.canRemoveVideoFiles(),
+ isDisplayed: () => this.displayOptions().removeFiles && this.canRemoveVideoFiles(),
iconName: 'delete'
}
],
@@ -554,7 +563,7 @@ export class VideoActionsDropdownComponent implements OnChanges {
{
label: $localize`Generate caption`,
handler: ({ video }) => this.generateCaption(video),
- isDisplayed: () => this.displayOptions.generateTranscription && this.canGenerateTranscription(),
+ isDisplayed: () => this.displayOptions().generateTranscription && this.canGenerateTranscription(),
iconName: 'video-lang'
}
],
@@ -562,20 +571,20 @@ export class VideoActionsDropdownComponent implements OnChanges {
{
label: $localize`Mute account`,
handler: () => this.muteVideoAccount(),
- isDisplayed: () => this.authService.isLoggedIn() && this.displayOptions.mute && this.isVideoAccountMutable(),
+ isDisplayed: () => this.authService.isLoggedIn() && this.displayOptions().mute && this.isVideoAccountMutable(),
iconName: 'no'
},
{
label: $localize`Unmute account`,
handler: () => this.unmuteVideoAccount(),
isDisplayed: () => {
- return this.authService.isLoggedIn() && this.displayOptions.mute && this.isVideoAccountMutable() && this.hasMutedAccount
+ return this.authService.isLoggedIn() && this.displayOptions().mute && this.isVideoAccountMutable() && this.hasMutedAccount
},
iconName: 'undo'
}
]
]
- this.videoActions = this.videoActions.concat(this.moreActions)
+ this.videoActions = this.videoActions.concat(this.moreActions())
}
}
diff --git a/client/src/app/shared/shared-video-miniature/video-filters-header.component.html b/client/src/app/shared/shared-video-miniature/video-filters-header.component.html
index 81d44173cb..0ad4bc9b10 100644
--- a/client/src/app/shared/shared-video-miniature/video-filters-header.component.html
+++ b/client/src/app/shared/shared-video-miniature/video-filters-header.component.html
@@ -12,8 +12,8 @@
<div class="d-flex flex-wrap-reverse align-items-start justify-content-between">
<div class="gap-3">
- <div class="scope-info" *ngIf="!hideScope" [ngClass]="{ 'opacity-0': totalFollowing === undefined }">
- @if (filters.scope === 'local' || totalFollowing === 0) {
+ <div class="scope-info" *ngIf="!hideScope()" [ngClass]="{ 'opacity-0': totalFollowing === undefined }">
+ @if (filters().scope === 'local' || totalFollowing === 0) {
<ng-container i18n>Videos on <strong>{{ instanceName }}</strong></ng-container>
} @else {
<ng-container i18n>Videos on <strong>{{ instanceName }}</strong> and <strong>{{ totalFollowing }}</strong> other platforms</ng-container>
@@ -22,7 +22,7 @@
<div class="filters-summary">
<div class="d-inline-block active-filters">
- @for (filter of filters.getActiveFilters(); track filter.key + (filter.value || '')) {
+ @for (filter of filters().getActiveFilters(); track filter.key + (filter.value || '')) {
@if (filter.key !== 'scope') {
<div class="d-inline-block active-filter">
<span i18n *ngIf="filter.value">{{ filter.label }}: </span>
@@ -81,7 +81,7 @@
<div class="peertube-radio-container">
<input formControlName="nsfw" type="radio" name="nsfw" id="nsfwBoth" value="both" />
- <label for="nsfwBoth">{{ filters.getNSFWDisplayLabel() }}</label>
+ <label for="nsfwBoth">{{ filters().getNSFWDisplayLabel() }}</label>
</div>
<div class="peertube-radio-container">
@@ -91,7 +91,7 @@
</div>
</div>
- <div class="section" *ngIf="totalFollowing && !hideScope">
+ <div class="section" *ngIf="totalFollowing && !hideScope()">
<div class="section-title">
<ng-container i18n>Platforms order</ng-container>
diff --git a/client/src/app/shared/shared-video-miniature/video-filters-header.component.ts b/client/src/app/shared/shared-video-miniature/video-filters-header.component.ts
index 68e44c327c..27fc7c0100 100644
--- a/client/src/app/shared/shared-video-miniature/video-filters-header.component.ts
+++ b/client/src/app/shared/shared-video-miniature/video-filters-header.component.ts
@@ -1,5 +1,5 @@
import { NgClass, NgIf } from '@angular/common'
-import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'
+import { Component, OnInit, inject, input, output } from '@angular/core'
import { FormBuilder, FormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms'
import { RouterLink } from '@angular/router'
import { AuthService, RedirectService } from '@app/core'
@@ -49,11 +49,19 @@ type QuickFilter = {
providers: [ InstanceFollowService ]
})
export class VideoFiltersHeaderComponent implements OnInit {
- @Input() filters: VideoFilters
- @Input() displayModerationBlock = false
- @Input() hideScope = false
+ private auth = inject(AuthService)
+ private serverService = inject(ServerService)
+ private fb = inject(FormBuilder)
+ private modalService = inject(PeertubeModalService)
+ private redirectService = inject(RedirectService)
+ private server = inject(ServerService)
+ private followService = inject(InstanceFollowService)
- @Output() filtersChanged = new EventEmitter()
+ readonly filters = input<VideoFilters>(undefined)
+ readonly displayModerationBlock = input(false)
+ readonly hideScope = input(false)
+
+ readonly filtersChanged = output()
areFiltersCollapsed = true
@@ -70,17 +78,6 @@ export class VideoFiltersHeaderComponent implements OnInit {
private videoCategories: VideoConstant<number>[] = []
private videoLanguages: VideoConstant<string>[] = []
- constructor (
- private auth: AuthService,
- private serverService: ServerService,
- private fb: FormBuilder,
- private modalService: PeertubeModalService,
- private redirectService: RedirectService,
- private server: ServerService,
- private followService: InstanceFollowService
- ) {
- }
-
ngOnInit () {
this.instanceName = this.server.getHTMLConfig().instance.name
@@ -96,14 +93,14 @@ export class VideoFiltersHeaderComponent implements OnInit {
this.patchForm(false)
- this.filters.onChange(() => {
+ this.filters().onChange(() => {
this.patchForm(false)
})
this.form.valueChanges.subscribe(values => {
debugLogger('Loading values from form: %O', values)
- this.filters.load(values)
+ this.filters().load(values)
this.filtersChanged.emit()
})
@@ -127,7 +124,7 @@ export class VideoFiltersHeaderComponent implements OnInit {
canSeeAllVideos () {
if (!this.auth.isLoggedIn()) return false
- if (!this.displayModerationBlock) return false
+ if (!this.displayModerationBlock()) return false
return this.auth.getUser().hasRight(UserRight.SEE_ALL_VIDEOS)
}
@@ -137,7 +134,7 @@ export class VideoFiltersHeaderComponent implements OnInit {
onQuickFilter (e: Event, quickFilter: QuickFilter) {
e.preventDefault()
- this.filters.load(quickFilter.filters)
+ this.filters().load(quickFilter.filters)
this.filtersChanged.emit()
}
@@ -148,14 +145,14 @@ export class VideoFiltersHeaderComponent implements OnInit {
{
label: $localize`Recently added`,
iconName: 'add',
- isActive: () => this.filters.sort === '-publishedAt',
+ isActive: () => this.filters().sort === '-publishedAt',
filters: { sort: '-publishedAt' }
},
{
label: $localize`Trending`,
iconName: 'trending',
- isActive: () => this.filters.sort === trendingSort,
+ isActive: () => this.filters().sort === trendingSort,
filters: { sort: trendingSort }
}
]
@@ -225,7 +222,7 @@ export class VideoFiltersHeaderComponent implements OnInit {
}
private patchForm (emitEvent: boolean) {
- const defaultValues = this.filters.toFormObject()
+ const defaultValues = this.filters().toFormObject()
this.form.patchValue(defaultValues, { emitEvent })
debugLogger('Patched form: %O', defaultValues)
diff --git a/client/src/app/shared/shared-video-miniature/video-miniature.component.html b/client/src/app/shared/shared-video-miniature/video-miniature.component.html
index e0bc686a0d..fb0f4c04bb 100644
--- a/client/src/app/shared/shared-video-miniature/video-miniature.component.html
+++ b/client/src/app/shared/shared-video-miniature/video-miniature.component.html
@@ -1,10 +1,10 @@
<div class="video-miniature" [ngClass]="getClasses()" (mouseenter)="loadActions()" (focusin)="loadActions()">
<my-video-thumbnail
[ariaLabel]="getAriaLabel()"
- [video]="video" [nsfw]="isVideoBlur" [videoRouterLink]="videoRouterLink" [videoHref]="videoHref" [videoTarget]="videoTarget"
+ [video]="video()" [nsfw]="isVideoBlur" [videoRouterLink]="videoRouterLink" [videoHref]="videoHref" [videoTarget]="videoTarget"
[displayWatchLaterPlaylist]="isWatchLaterPlaylistDisplayed()" [inWatchLaterPlaylist]="inWatchLaterPlaylist" (watchLaterClick)="onWatchLaterClick($event)"
>
- @if (displayOptions.privacyLabel) {
+ @if (displayOptions().privacyLabel) {
<ng-container ngProjectAs="label-warning" *ngIf="isUnlistedVideo()" i18n>Unlisted</ng-container>
<ng-container ngProjectAs="label-danger" *ngIf="isPrivateVideo()" i18n>Private</ng-container>
<ng-container ngProjectAs="label-danger" *ngIf="isPasswordProtectedVideo()" i18n>Password protected</ng-container>
@@ -12,24 +12,24 @@
</my-video-thumbnail>
<div class="video-info">
- <div *ngIf="displayOptions.avatar || displayOptions.by" class="owner min-width-0">
- @if (displayOptions.avatar) {
+ <div *ngIf="displayOptions().avatar || displayOptions().by" class="owner min-width-0">
+ @if (displayOptions().avatar) {
@if (displayOwnerVideoChannel()) {
<my-actor-avatar
- [title]="channelLinkTitle" actorType="channel" [size]="actorImageSize"
- [actor]="video.channel" [internalHref]="[ '/c', video.byVideoChannel ]"
+ [title]="channelLinkTitle" actorType="channel" [size]="actorImageSize()"
+ [actor]="video().channel" [internalHref]="[ '/c', video().byVideoChannel ]"
></my-actor-avatar>
} @else if (displayOwnerAccount()) {
<my-actor-avatar
- [title]="channelLinkTitle" actorType="account" [size]="actorImageSize"
- [actor]="video.account" [internalHref]="[ '/c', video.byVideoChannel ]"
+ [title]="channelLinkTitle" actorType="account" [size]="actorImageSize()"
+ [actor]="video().account" [internalHref]="[ '/c', video().byVideoChannel ]"
></my-actor-avatar>
}
}
- <div class="owner-container" *ngIf="displayOptions.by">
- <a class="owner-label ellipsis" [routerLink]="[ '/c', video.byVideoChannel ]" [title]="displayOwnerAccount() ? authorAccount : authorChannel">
+ <div class="owner-container" *ngIf="displayOptions().by">
+ <a class="owner-label ellipsis" [routerLink]="[ '/c', video().byVideoChannel ]" [title]="displayOwnerAccount() ? authorAccount : authorChannel">
@if (displayOwnerAccount()) {
{{ authorAccount }}
} @else if (displayOwnerVideoChannel()) {
@@ -37,7 +37,7 @@
}
</a>
- <my-actor-host *ngIf="!video.isLocal" [host]="video.account.host"></my-actor-host>
+ <my-actor-host *ngIf="!video().isLocal" [host]="video().account.host"></my-actor-host>
</div>
</div>
@@ -45,46 +45,46 @@
<my-link
[internalLink]="videoRouterLink" [href]="videoHref" [target]="videoTarget" inheritParentStyle="true"
[ariaLabel]="getAriaLabel()"
- [title]="video.name" class="video-name" className="ellipsis-multiline-2" [ngClass]="{ 'blur-filter': isVideoBlur }"
+ [title]="video().name" class="video-name" className="ellipsis-multiline-2" [ngClass]="{ 'blur-filter': isVideoBlur }"
>
- {{ video.name }}
+ {{ video().name }}
</my-link>
<div class="video-actions">
<my-video-actions-dropdown
- *ngIf="showActions" [video]="video" [displayOptions]="videoActionsDisplayOptions" placement="bottom-left bottom-right left auto"
+ *ngIf="showActions" [video]="video()" [displayOptions]="videoActionsDisplayOptions()" placement="bottom-left bottom-right left auto"
(videoRemoved)="onVideoRemoved()" (videoBlocked)="onVideoBlocked()" (videoUnblocked)="onVideoUnblocked()" (videoAccountMuted)="onVideoAccountMuted()"
></my-video-actions-dropdown>
</div>
</div>
<div class="date-and-views">
- <my-date-toggle *ngIf="displayOptions.date" [date]="video.publishedAt"></my-date-toggle>
+ <my-date-toggle *ngIf="displayOptions().date" [date]="video().publishedAt"></my-date-toggle>
<span class="views">
- <ng-container *ngIf="displayOptions.date && displayOptions.views"> • </ng-container>
+ <ng-container *ngIf="displayOptions().date && displayOptions().views"> • </ng-container>
- <my-video-views-counter *ngIf="displayOptions.views" [isLive]="video.isLive" [viewers]="video.viewers" [views]="video.views"></my-video-views-counter>
+ <my-video-views-counter *ngIf="displayOptions().views" [isLive]="video().isLive" [viewers]="video().viewers" [views]="video().views"></my-video-views-counter>
</span>
</div>
<div class="video-info-privacy fw-semibold">
- <ng-container *ngIf="displayOptions.privacyText">{{ video.privacy.label }}</ng-container>
- <ng-container *ngIf="displayOptions.privacyText && displayOptions.state && getStateLabel(video)"> - </ng-container>
- <ng-container *ngIf="displayOptions.state">{{ getStateLabel(video) }}</ng-container>
+ <ng-container *ngIf="displayOptions().privacyText">{{ video().privacy.label }}</ng-container>
+ <ng-container *ngIf="displayOptions().privacyText && displayOptions().state && getStateLabel(video())"> - </ng-container>
+ <ng-container *ngIf="displayOptions().state">{{ getStateLabel(video()) }}</ng-container>
</div>
- <div *ngIf="containedInPlaylists" class="badges">
- <a *ngFor="let playlist of containedInPlaylists" class="pt-badge badge-secondary" [routerLink]="['/w/p/', playlist.playlistShortUUID]">
+ <div *ngIf="containedInPlaylists()" class="badges">
+ <a *ngFor="let playlist of containedInPlaylists()" class="pt-badge badge-secondary" [routerLink]="['/w/p/', playlist.playlistShortUUID]">
{{ playlist.playlistDisplayName }}
</a>
- <span *ngIf="displayOptions.blacklistInfo && video.blacklisted" class="pt-badge badge-danger video-info-blocked">
+ <span *ngIf="displayOptions().blacklistInfo && video().blacklisted" class="pt-badge badge-danger video-info-blocked">
<span class="fw-semibold" i18n>Blocked</span>
- <span *ngIf="video.blacklistedReason"> - {{ video.blacklistedReason }}</span>
+ <span *ngIf="video().blacklistedReason"> - {{ video().blacklistedReason }}</span>
</span>
- <span i18n *ngIf="displayOptions.nsfw && video.nsfw" class="pt-badge badge-danger video-info-nsfw">Sensitive</span>
+ <span i18n *ngIf="displayOptions().nsfw && video().nsfw" class="pt-badge badge-danger video-info-nsfw">Sensitive</span>
</div>
</div>
</div>
diff --git a/client/src/app/shared/shared-video-miniature/video-miniature.component.ts b/client/src/app/shared/shared-video-miniature/video-miniature.component.ts
index 8f68e57b50..8088d0cc56 100644
--- a/client/src/app/shared/shared-video-miniature/video-miniature.component.ts
+++ b/client/src/app/shared/shared-video-miniature/video-miniature.component.ts
@@ -3,14 +3,13 @@ import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
- EventEmitter,
- Inject,
- Input,
LOCALE_ID,
OnInit,
- Output,
booleanAttribute,
- numberAttribute
+ numberAttribute,
+ inject,
+ input,
+ output
} from '@angular/core'
import { RouterLink } from '@angular/router'
import { AuthService, ScreenService, ServerService, User } from '@app/core'
@@ -41,6 +40,7 @@ export type MiniatureDisplayOptions = {
by?: boolean
forceChannelInBy?: boolean
}
+
@Component({
selector: 'my-video-miniature',
styleUrls: [ './video-miniature.component.scss' ],
@@ -61,11 +61,19 @@ export type MiniatureDisplayOptions = {
]
})
export class VideoMiniatureComponent implements OnInit {
- @Input() user: User
- @Input() video: Video
- @Input() containedInPlaylists: VideoExistInPlaylist[]
-
- @Input() displayOptions: MiniatureDisplayOptions = {
+ private screenService = inject(ScreenService)
+ private serverService = inject(ServerService)
+ private authService = inject(AuthService)
+ private videoPlaylistService = inject(VideoPlaylistService)
+ private videoService = inject(VideoService)
+ private cd = inject(ChangeDetectorRef)
+ private localeId = inject(LOCALE_ID)
+
+ readonly user = input<User>(undefined)
+ readonly video = input<Video>(undefined)
+ readonly containedInPlaylists = input<VideoExistInPlaylist[]>(undefined)
+
+ readonly displayOptions = input<MiniatureDisplayOptions>({
date: true,
views: true,
by: true,
@@ -75,10 +83,10 @@ export class VideoMiniatureComponent implements OnInit {
state: false,
blacklistInfo: false,
forceChannelInBy: false
- }
+ })
- @Input() displayVideoActions = true
- @Input() videoActionsDisplayOptions: VideoActionsDisplayType = {
+ readonly displayVideoActions = input(true)
+ readonly videoActionsDisplayOptions = input<VideoActionsDisplayType>({
playlist: true,
download: false,
update: true,
@@ -89,18 +97,18 @@ export class VideoMiniatureComponent implements OnInit {
mute: true,
studio: false,
stats: false
- }
+ })
- @Input({ transform: numberAttribute }) actorImageSize = 34
+ readonly actorImageSize = input(34, { transform: numberAttribute })
- @Input({ transform: booleanAttribute }) displayAsRow = false
+ readonly displayAsRow = input(false, { transform: booleanAttribute })
- @Input() videoLinkType: LinkType = 'internal'
+ readonly videoLinkType = input<LinkType>('internal')
- @Output() videoBlocked = new EventEmitter()
- @Output() videoUnblocked = new EventEmitter()
- @Output() videoRemoved = new EventEmitter()
- @Output() videoAccountMuted = new EventEmitter()
+ readonly videoBlocked = output()
+ readonly videoUnblocked = output()
+ readonly videoRemoved = output()
+ readonly videoAccountMuted = output()
showActions = false
serverConfig: HTMLServerConfig
@@ -122,30 +130,20 @@ export class VideoMiniatureComponent implements OnInit {
private ownerDisplayType: 'account' | 'videoChannel'
private actionsLoaded = false
- constructor (
- private screenService: ScreenService,
- private serverService: ServerService,
- private authService: AuthService,
- private videoPlaylistService: VideoPlaylistService,
- private videoService: VideoService,
- private cd: ChangeDetectorRef,
- @Inject(LOCALE_ID) private localeId: string
- ) {}
-
get authorAccount () {
return this.serverConfig.client.videos.miniature.preferAuthorDisplayName
- ? this.video.account.displayName
- : this.video.account.name
+ ? this.video().account.displayName
+ : this.video().account.name
}
get authorChannel () {
return this.serverConfig.client.videos.miniature.preferAuthorDisplayName
- ? this.video.channel.displayName
- : this.video.channel.name
+ ? this.video().channel.displayName
+ : this.video().channel.name
}
get isVideoBlur () {
- return this.video.isVideoNSFWForUser(this.user, this.serverConfig)
+ return this.video().isVideoNSFWForUser(this.user(), this.serverConfig)
}
ngOnInit () {
@@ -154,7 +152,7 @@ export class VideoMiniatureComponent implements OnInit {
this.setUpBy()
- this.channelLinkTitle = $localize`${this.video.channel.name} (channel page)`
+ this.channelLinkTitle = $localize`${this.video().channel.name} (channel page)`
// We rely on mouseenter to lazy load actions
if (this.screenService.isInTouchScreen()) {
@@ -163,20 +161,22 @@ export class VideoMiniatureComponent implements OnInit {
}
buildVideoLink () {
- if (this.videoLinkType === 'internal' || !this.video.url) {
- this.videoRouterLink = Video.buildWatchUrl(this.video)
+ const videoLinkType = this.videoLinkType()
+ const video = this.video()
+ if (videoLinkType === 'internal' || !video.url) {
+ this.videoRouterLink = Video.buildWatchUrl(video)
return
}
- if (this.videoLinkType === 'external') {
+ if (videoLinkType === 'external') {
this.videoRouterLink = null
- this.videoHref = this.video.url
+ this.videoHref = video.url
this.videoTarget = '_blank'
return
}
// Lazy load
- this.videoRouterLink = [ '/search/lazy-load-video', { url: this.video.url } ]
+ this.videoRouterLink = [ '/search/lazy-load-video', { url: video.url } ]
}
displayOwnerAccount () {
@@ -188,15 +188,15 @@ export class VideoMiniatureComponent implements OnInit {
}
isUnlistedVideo () {
- return this.video.privacy.id === VideoPrivacy.UNLISTED
+ return this.video().privacy.id === VideoPrivacy.UNLISTED
}
isPrivateVideo () {
- return this.video.privacy.id === VideoPrivacy.PRIVATE
+ return this.video().privacy.id === VideoPrivacy.PRIVATE
}
isPasswordProtectedVideo () {
- return this.video.privacy.id === VideoPrivacy.PASSWORD_PROTECTED
+ return this.video().privacy.id === VideoPrivacy.PASSWORD_PROTECTED
}
getStateLabel (video: Video) {
@@ -243,12 +243,12 @@ export class VideoMiniatureComponent implements OnInit {
}
getAriaLabel () {
- return $localize`Watch video ${this.video.name}`
+ return $localize`Watch video ${this.video().name}`
}
loadActions () {
if (this.actionsLoaded) return
- if (this.displayVideoActions) this.showActions = true
+ if (this.displayVideoActions()) this.showActions = true
this.loadWatchLater()
@@ -283,7 +283,7 @@ export class VideoMiniatureComponent implements OnInit {
}
addToWatchLater () {
- const body = { videoId: this.video.id }
+ const body = { videoId: this.video().id }
this.videoPlaylistService.addVideoInPlaylist(this.watchLaterPlaylist.id, body)
.subscribe(
@@ -294,57 +294,63 @@ export class VideoMiniatureComponent implements OnInit {
}
removeFromWatchLater () {
- this.videoPlaylistService.removeVideoFromPlaylist(this.watchLaterPlaylist.id, this.watchLaterPlaylist.playlistElementId, this.video.id)
- .subscribe(
- _ => { /* empty */ }
- )
+ this.videoPlaylistService.removeVideoFromPlaylist(
+ this.watchLaterPlaylist.id,
+ this.watchLaterPlaylist.playlistElementId,
+ this.video().id
+ )
+ .subscribe(
+ _ => {
+ // empty
+ }
+ )
}
isWatchLaterPlaylistDisplayed () {
return !this.screenService.isInTouchScreen() &&
- this.displayVideoActions &&
+ this.displayVideoActions() &&
this.isUserLoggedIn() &&
this.inWatchLaterPlaylist !== undefined
}
getClasses () {
return {
- 'display-as-row': this.displayAsRow,
- 'has-avatar': this.displayOptions.avatar
+ 'display-as-row': this.displayAsRow(),
+ 'has-avatar': this.displayOptions().avatar
}
}
private setUpBy () {
- if (this.displayOptions.forceChannelInBy) {
+ if (this.displayOptions().forceChannelInBy) {
this.ownerDisplayType = 'videoChannel'
return
}
- this.ownerDisplayType = this.videoService.buildDefaultOwnerDisplayType(this.video)
+ this.ownerDisplayType = this.videoService.buildDefaultOwnerDisplayType(this.video())
}
private loadWatchLater () {
- if (this.screenService.isInTouchScreen() || !this.displayVideoActions || !this.isUserLoggedIn()) return
+ if (this.screenService.isInTouchScreen() || !this.displayVideoActions() || !this.isUserLoggedIn()) return
this.authService.userInformationLoaded
- .pipe(switchMap(() => this.videoPlaylistService.listenToVideoPlaylistChange(this.video.id)))
- .subscribe(existResult => {
- const watchLaterPlaylist = this.authService.getUser().specialPlaylists.find(p => p.type === VideoPlaylistType.WATCH_LATER)
- const existsInWatchLater = existResult.find(r => r.playlistId === watchLaterPlaylist.id)
- this.inWatchLaterPlaylist = false
-
- this.watchLaterPlaylist = {
- id: watchLaterPlaylist.id
- }
+ .pipe(switchMap(() => this.videoPlaylistService.listenToVideoPlaylistChange(this.video().id)))
+ .subscribe(existResult => {
+ const watchLaterPlaylist = this.authService.getUser().specialPlaylists.find(p => p.type === VideoPlaylistType.WATCH_LATER)
+ const existsInWatchLater = existResult.find(r => r.playlistId === watchLaterPlaylist.id)
+ this.inWatchLaterPlaylist = false
+
+ this.watchLaterPlaylist = {
+ id: watchLaterPlaylist.id
+ }
- if (existsInWatchLater) {
- this.inWatchLaterPlaylist = true
- this.watchLaterPlaylist.playlistElementId = existsInWatchLater.playlistElementId
- }
+ if (existsInWatchLater) {
+ this.inWatchLaterPlaylist = true
+ this.watchLaterPlaylist.playlistElementId = existsInWatchLater.playlistElementId
+ }
- this.cd.markForCheck()
- })
+ this.cd.markForCheck()
+ })
- this.videoPlaylistService.runVideoExistsInPlaylistCheck(this.video.id)
+ this.videoPlaylistService.runVideoExistsInPlaylistCheck(this.video().id)
}
}
diff --git a/client/src/app/shared/shared-video-miniature/videos-list.component.html b/client/src/app/shared/shared-video-miniature/videos-list.component.html
index ce3dc32396..118ee2bd6a 100644
--- a/client/src/app/shared/shared-video-miniature/videos-list.component.html
+++ b/client/src/app/shared/shared-video-miniature/videos-list.component.html
@@ -1,7 +1,7 @@
<div class="margin-content">
<div class="videos-header">
- <div *ngIf="headerActions.length !== 0" class="action-block mb-4">
- <ng-container *ngFor="let action of headerActions">
+ <div *ngIf="headerActions().length !== 0" class="action-block mb-4">
+ <ng-container *ngFor="let action of headerActions()">
@if (action.routerLink) {
<my-button theme="secondary" [ptRouterLink]="action.routerLink" [icon]="action.iconName">{{ action.label }}</my-button>
}
@@ -10,8 +10,8 @@
</div>
<my-video-filters-header
- *ngIf="displayFilters" class="d-block"
- [displayModerationBlock]="displayModerationBlock" [hideScope]="hideScopeFilter" [filters]="filters"
+ *ngIf="displayFilters()" class="d-block"
+ [displayModerationBlock]="builtDisplayModerationBlock" [hideScope]="hideScopeFilter()" [filters]="filters"
(filtersChanged)="onFiltersChanged(true)"
></my-video-filters-header>
@@ -19,8 +19,8 @@
<div
myInfiniteScroller (nearOfBottom)="onNearOfBottom()" [dataObservable]="onVideosDataSubject.asObservable()"
- [setAngularState]="true" [parentDisabled]="disabled"
- class="videos" [ngClass]="{ 'display-as-row': displayAsRow }"
+ [setAngularState]="true" [parentDisabled]="disabled()"
+ class="videos" [ngClass]="{ 'display-as-row': displayAsRow() }"
>
<ng-container *ngIf="highlightedLives.length !== 0">
<h2 class="date-title">
@@ -31,15 +31,15 @@
<ng-container *ngFor="let live of highlightedLives; trackBy: videoById;">
<div class="video-wrapper">
<my-video-miniature
- [video]="live" [user]="userMiniature" [displayAsRow]="displayAsRow"
- [displayVideoActions]="displayVideoActions" [displayOptions]="displayOptions"
+ [video]="live" [user]="userMiniature" [displayAsRow]="displayAsRow()"
+ [displayVideoActions]="displayVideoActions()" [displayOptions]="builtDisplayOptions"
(videoBlocked)="removeVideoFromArray(live)" (videoRemoved)="removeVideoFromArray(live)"
>
</my-video-miniature>
</div>
</ng-container>
- <h2 *ngIf="!groupByDate" class="date-title">
+ <h2 *ngIf="!groupByDate()" class="date-title">
<my-global-icon class="pt-icon me-1" iconName="videos"></my-global-icon> Videos
</h2>
</ng-container>
@@ -51,8 +51,8 @@
<div class="video-wrapper">
<my-video-miniature
- [video]="video" [user]="userMiniature" [displayAsRow]="displayAsRow"
- [displayVideoActions]="displayVideoActions" [displayOptions]="displayOptions"
+ [video]="video" [user]="userMiniature" [displayAsRow]="displayAsRow()"
+ [displayVideoActions]="displayVideoActions()" [displayOptions]="builtDisplayOptions"
(videoBlocked)="removeVideoFromArray(video)" (videoRemoved)="removeVideoFromArray(video)"
>
</my-video-miniature>
diff --git a/client/src/app/shared/shared-video-miniature/videos-list.component.ts b/client/src/app/shared/shared-video-miniature/videos-list.component.ts
index dc8a4b755c..25b18ff8fe 100644
--- a/client/src/app/shared/shared-video-miniature/videos-list.component.ts
+++ b/client/src/app/shared/shared-video-miniature/videos-list.component.ts
@@ -1,5 +1,5 @@
import { NgClass, NgFor, NgIf } from '@angular/common'
-import { Component, EventEmitter, Input, OnChanges, OnDestroy, OnInit, Output, SimpleChanges, booleanAttribute } from '@angular/core'
+import { Component, OnChanges, OnDestroy, OnInit, SimpleChanges, booleanAttribute, inject, input, output } from '@angular/core'
import { ActivatedRoute } from '@angular/router'
import {
AuthService,
@@ -63,31 +63,42 @@ enum GroupDate {
]
})
export class VideosListComponent implements OnInit, OnChanges, OnDestroy {
- @Input() getVideosObservableFunction: (pagination: ComponentPaginationLight, filters: VideoFilters) => Observable<ResultList<Video>>
- @Input() getSyndicationItemsFunction: (filters: VideoFilters) => Promise<Syndication[]> | Syndication[]
+ private notifier = inject(Notifier)
+ private authService = inject(AuthService)
+ private userService = inject(UserService)
+ private route = inject(ActivatedRoute)
+ private screenService = inject(ScreenService)
+ private peertubeRouter = inject(PeerTubeRouterService)
- @Input() defaultSort: VideoSortField
- @Input() defaultScope: VideoFilterScope = 'federated'
- @Input({ transform: booleanAttribute }) displayFilters = false
- @Input({ transform: booleanAttribute }) displayModerationBlock = false
+ // eslint-disable-next-line max-len
+ readonly getVideosObservableFunction = input<(pagination: ComponentPaginationLight, filters: VideoFilters) => Observable<ResultList<Video>>>(undefined)
+ readonly getSyndicationItemsFunction = input<(filters: VideoFilters) => Promise<Syndication[]> | Syndication[]>(undefined)
- @Input({ transform: booleanAttribute }) loadUserVideoPreferences = false
+ readonly defaultSort = input<VideoSortField>(undefined)
+ readonly defaultScope = input<VideoFilterScope>('federated')
+ readonly displayFilters = input(false, { transform: booleanAttribute })
- @Input({ transform: booleanAttribute }) displayAsRow = false
- @Input({ transform: booleanAttribute }) displayVideoActions = true
- @Input({ transform: booleanAttribute }) groupByDate = false
- @Input({ transform: booleanAttribute }) highlightLives = false
+ readonly displayModerationBlock = input(false, { transform: booleanAttribute })
+ builtDisplayModerationBlock: boolean
- @Input() headerActions: HeaderAction[] = []
+ readonly loadUserVideoPreferences = input(false, { transform: booleanAttribute })
- @Input({ transform: booleanAttribute }) hideScopeFilter = false
+ readonly displayAsRow = input(false, { transform: booleanAttribute })
+ readonly displayVideoActions = input(true, { transform: booleanAttribute })
+ readonly groupByDate = input(false, { transform: booleanAttribute })
+ readonly highlightLives = input(false, { transform: booleanAttribute })
- @Input() displayOptions: MiniatureDisplayOptions
+ readonly headerActions = input<HeaderAction[]>([])
- @Input({ transform: booleanAttribute }) disabled = false
+ readonly hideScopeFilter = input(false, { transform: booleanAttribute })
- @Output() filtersChanged = new EventEmitter<VideoFilters>()
- @Output() videosLoaded = new EventEmitter<Video[]>()
+ readonly displayOptions = input<MiniatureDisplayOptions>(undefined)
+ builtDisplayOptions: MiniatureDisplayOptions
+
+ readonly disabled = input(false, { transform: booleanAttribute })
+
+ readonly filtersChanged = output<VideoFilters>()
+ readonly videosLoaded = output<Video[]>()
videos: Video[] = []
highlightedLives: Video[] = []
@@ -133,26 +144,15 @@ export class VideosListComponent implements OnInit, OnChanges, OnDestroy {
private alreadyDoneSearch = false
- constructor (
- private notifier: Notifier,
- private authService: AuthService,
- private userService: UserService,
- private route: ActivatedRoute,
- private screenService: ScreenService,
- private peertubeRouter: PeerTubeRouterService
- ) {
-
- }
-
ngOnInit () {
this.subscribeToVideoRequests()
- const hiddenFilters = this.hideScopeFilter
+ const hiddenFilters = this.hideScopeFilter()
? [ 'scope' ]
: []
- this.filters = new VideoFilters(this.defaultSort, this.defaultScope, hiddenFilters)
- this.filters.load({ scope: this.defaultScope, ...this.route.snapshot.queryParams })
+ this.filters = new VideoFilters(this.defaultSort(), this.defaultScope(), hiddenFilters)
+ this.filters.load({ scope: this.defaultScope(), ...this.route.snapshot.queryParams })
this.groupedDateLabels = {
[GroupDate.UNKNOWN]: null,
@@ -174,7 +174,7 @@ export class VideosListComponent implements OnInit, OnChanges, OnDestroy {
.subscribe(user => {
this.userMiniature = user
- if (this.loadUserVideoPreferences) {
+ if (this.loadUserVideoPreferences()) {
this.loadUserSettings(user)
}
@@ -183,11 +183,6 @@ export class VideosListComponent implements OnInit, OnChanges, OnDestroy {
this.subscribeToAnonymousUpdate()
this.subscribeToSearchChange()
})
-
- // Display avatar in mobile view
- if (this.screenService.isInMobileView()) {
- this.displayOptions.avatar = true
- }
}
ngOnDestroy () {
@@ -197,12 +192,21 @@ export class VideosListComponent implements OnInit, OnChanges, OnDestroy {
}
ngOnChanges (changes: SimpleChanges) {
- if (changes['displayOptions'] || !this.displayOptions) {
- this.displayOptions = {
+ if (changes['displayModerationBlock'] !== undefined) {
+ this.builtDisplayModerationBlock = changes['displayModerationBlock'].currentValue
+ }
+
+ if (changes['displayOptions'] || !this.builtDisplayOptions) {
+ this.builtDisplayOptions = {
...this.defaultDisplayOptions,
...(changes['displayOptions']?.currentValue ?? {})
}
+
+ // Display avatar in mobile view
+ if (this.screenService.isInMobileView()) {
+ this.builtDisplayOptions.avatar = true
+ }
}
if (!this.filters) return
@@ -211,12 +215,12 @@ export class VideosListComponent implements OnInit, OnChanges, OnDestroy {
if (changes['defaultScope']) {
updated = true
- this.filters.setDefaultScope(this.defaultScope)
+ this.filters.setDefaultScope(this.defaultScope())
}
if (changes['defaultSort']) {
updated = true
- this.filters.setDefaultSort(this.defaultSort)
+ this.filters.setDefaultSort(this.defaultSort())
}
if (!updated) return
@@ -224,7 +228,7 @@ export class VideosListComponent implements OnInit, OnChanges, OnDestroy {
const customizedByUser = this.hasBeenCustomizedByUser()
if (!customizedByUser) {
- if (this.loadUserVideoPreferences) {
+ if (this.loadUserVideoPreferences()) {
this.loadUserSettings(this.userMiniature)
}
@@ -240,7 +244,7 @@ export class VideosListComponent implements OnInit, OnChanges, OnDestroy {
}
onNearOfBottom () {
- if (this.disabled) return
+ if (this.disabled()) return
// No more results
if (this.lastQueryLength !== undefined && this.lastQueryLength < this.pagination.itemsPerPage) return
@@ -259,7 +263,7 @@ export class VideosListComponent implements OnInit, OnChanges, OnDestroy {
this.videos = []
this.highlightedLives = []
- if (this.highlightLives && (!this.filters.live || this.filters.live === 'both')) {
+ if (this.highlightLives() && (!this.filters.live || this.filters.live === 'both')) {
liveFilters = this.filters.clone()
liveFilters.live = 'true'
@@ -270,11 +274,11 @@ export class VideosListComponent implements OnInit, OnChanges, OnDestroy {
this.videoRequests.next({
reset,
- obsVideos: this.getVideosObservableFunction(this.pagination, videoFilters ?? this.filters),
+ obsVideos: this.getVideosObservableFunction()(this.pagination, videoFilters ?? this.filters),
obsHighlightedLives: liveFilters
- ? this.getVideosObservableFunction(this.pagination, liveFilters)
- : of(({ data: this.highlightedLives }))
+ ? this.getVideosObservableFunction()(this.pagination, liveFilters)
+ : of({ data: this.highlightedLives })
})
}
@@ -332,7 +336,6 @@ export class VideosListComponent implements OnInit, OnChanges, OnDestroy {
const period = periods[i]
if (currentGroupedDate <= period.value && period.validator(publishedDate)) {
-
if (currentGroupedDate !== period.value) {
if (period.value !== GroupDate.OLDER) onlyOlderPeriod = false
@@ -350,7 +353,7 @@ export class VideosListComponent implements OnInit, OnChanges, OnDestroy {
}
getCurrentGroupedDateLabel (video: Video) {
- if (this.groupByDate === false) return undefined
+ if (this.groupByDate() === false) return undefined
return this.groupedDateLabels[this.groupedDates[video.id]]
}
@@ -380,7 +383,7 @@ export class VideosListComponent implements OnInit, OnChanges, OnDestroy {
this.authService.userInformationLoaded
.subscribe(() => {
const user = this.authService.getUser()
- this.displayModerationBlock = user.hasRight(UserRight.SEE_ALL_VIDEOS)
+ this.builtDisplayModerationBlock = user.hasRight(UserRight.SEE_ALL_VIDEOS)
})
}
@@ -400,7 +403,7 @@ export class VideosListComponent implements OnInit, OnChanges, OnDestroy {
}
private reloadSyndicationItems () {
- Promise.resolve(this.getSyndicationItemsFunction(this.filters))
+ Promise.resolve(this.getSyndicationItemsFunction()(this.filters))
.then(items => {
if (!items || items.length === 0) this.syndicationItems = undefined
else this.syndicationItems = items
@@ -433,7 +436,7 @@ export class VideosListComponent implements OnInit, OnChanges, OnDestroy {
this.userSub = this.userService.listenAnonymousUpdate()
.pipe(switchMap(() => this.userService.getAnonymousOrLoggedUser()))
.subscribe(user => {
- if (this.loadUserVideoPreferences) {
+ if (this.loadUserVideoPreferences()) {
this.loadUserSettings(user)
}
@@ -475,7 +478,7 @@ export class VideosListComponent implements OnInit, OnChanges, OnDestroy {
this.videos = this.videos.concat(videos)
- if (this.groupByDate) this.buildGroupedDateLabels()
+ if (this.groupByDate()) this.buildGroupedDateLabels()
this.onVideosDataSubject.next(videos)
this.videosLoaded.emit(this.videos)
diff --git a/client/src/app/shared/shared-video-miniature/videos-selection.component.html b/client/src/app/shared/shared-video-miniature/videos-selection.component.html
index 722239c339..906a8b9bd5 100644
--- a/client/src/app/shared/shared-video-miniature/videos-selection.component.html
+++ b/client/src/app/shared/shared-video-miniature/videos-selection.component.html
@@ -1,20 +1,20 @@
-<div class="no-results" i18n *ngIf="hasDoneFirstQuery && videos.length === 0">{{ noResultMessage }}</div>
+<div class="no-results" i18n *ngIf="hasDoneFirstQuery && videos.length === 0">{{ noResultMessage() }}</div>
<div
class="videos"
myInfiniteScroller (nearOfBottom)="onNearOfBottom()" [dataObservable]="onDataSubject.asObservable()"
- [parentDisabled]="disabled" [setAngularState]="true"
+ [parentDisabled]="disabled()" [setAngularState]="true"
>
<div class="video" *ngFor="let video of videos; let i = index; trackBy: videoById">
- <div class="checkbox-container" *ngIf="enableSelection">
+ <div class="checkbox-container" *ngIf="enableSelection()">
<my-peertube-checkbox [inputName]="'video-check-' + video.id" [(ngModel)]="_selection[video.id]"></my-peertube-checkbox>
</div>
<my-video-miniature
- [containedInPlaylists]="videosContainedInPlaylists ? videosContainedInPlaylists[video.id] : undefined"
- [video]="video" [displayAsRow]="true" [displayOptions]="miniatureDisplayOptions"
- [displayVideoActions]="false" [user]="user"
+ [containedInPlaylists]="videosContainedInPlaylists() ? videosContainedInPlaylists()[video.id] : undefined"
+ [video]="video" [displayAsRow]="true" [displayOptions]="miniatureDisplayOptions()"
+ [displayVideoActions]="false" [user]="user()"
></my-video-miniature>
@if (isInSelectionMode() === false) {
diff --git a/client/src/app/shared/shared-video-miniature/videos-selection.component.ts b/client/src/app/shared/shared-video-miniature/videos-selection.component.ts
index a0106af01b..47912a3dbc 100644
--- a/client/src/app/shared/shared-video-miniature/videos-selection.component.ts
+++ b/client/src/app/shared/shared-video-miniature/videos-selection.component.ts
@@ -1,5 +1,5 @@
import { NgFor, NgIf, NgTemplateOutlet } from '@angular/common'
-import { AfterContentInit, Component, ContentChildren, EventEmitter, Input, Output, QueryList, TemplateRef } from '@angular/core'
+import { AfterContentInit, Component, Input, TemplateRef, inject, input, output, contentChildren } from '@angular/core'
import { FormsModule } from '@angular/forms'
import { ComponentPagination, Notifier, resetCurrentPage, User } from '@app/core'
import { objectKeysTyped } from '@peertube/peertube-core-utils'
@@ -12,7 +12,7 @@ import { PeerTubeTemplateDirective } from '../shared-main/common/peertube-templa
import { Video } from '../shared-main/video/video.model'
import { MiniatureDisplayOptions, VideoMiniatureComponent } from './video-miniature.component'
-export type SelectionType = { [ id: number ]: boolean }
+export type SelectionType = { [id: number]: boolean }
@Component({
selector: 'my-videos-selection',
@@ -21,25 +21,27 @@ export type SelectionType = { [ id: number ]: boolean }
imports: [ NgIf, InfiniteScrollerDirective, NgFor, PeertubeCheckboxComponent, FormsModule, VideoMiniatureComponent, NgTemplateOutlet ]
})
export class VideosSelectionComponent implements AfterContentInit {
- @Input() videosContainedInPlaylists: VideosExistInPlaylists
- @Input() user: User
- @Input() pagination: ComponentPagination
+ private notifier = inject(Notifier)
- @Input() titlePage: string
+ readonly videosContainedInPlaylists = input<VideosExistInPlaylists>(undefined)
+ readonly user = input<User>(undefined)
+ readonly pagination = input<ComponentPagination>(undefined)
- @Input() miniatureDisplayOptions: MiniatureDisplayOptions
+ readonly titlePage = input<string>(undefined)
- @Input() noResultMessage = $localize`No results.`
- @Input() enableSelection = true
+ readonly miniatureDisplayOptions = input<MiniatureDisplayOptions>(undefined)
- @Input() disabled = false
+ readonly noResultMessage = input($localize`No results.`)
+ readonly enableSelection = input(true)
- @Input() getVideosObservableFunction: (page: number, sort?: VideoSortField) => Observable<ResultList<Video>>
+ readonly disabled = input(false)
- @ContentChildren(PeerTubeTemplateDirective) templates: QueryList<PeerTubeTemplateDirective<'rowButtons' | 'globalButtons'>>
+ readonly getVideosObservableFunction = input<(page: number, sort?: VideoSortField) => Observable<ResultList<Video>>>(undefined)
- @Output() selectionChange = new EventEmitter<SelectionType>()
- @Output() videosModelChange = new EventEmitter<Video[]>()
+ readonly templates = contentChildren(PeerTubeTemplateDirective)
+
+ readonly selectionChange = output<SelectionType>()
+ readonly videosModelChange = output<Video[]>()
_selection: SelectionType = {}
@@ -55,11 +57,8 @@ export class VideosSelectionComponent implements AfterContentInit {
private lastQueryLength: number
- constructor (
- private notifier: Notifier
- ) { }
-
- @Input() get selection () {
+ @Input()
+ get selection () {
return this._selection
}
@@ -68,7 +67,8 @@ export class VideosSelectionComponent implements AfterContentInit {
this.selectionChange.emit(this._selection)
}
- @Input() get videosModel () {
+ @Input()
+ get videosModel () {
return this.videos
}
@@ -79,12 +79,12 @@ export class VideosSelectionComponent implements AfterContentInit {
ngAfterContentInit () {
{
- const t = this.templates.find(t => t.name === 'rowButtons')
+ const t = this.templates().find(t => t.name() === 'rowButtons')
if (t) this.rowButtonsTemplate = t.template
}
{
- const t = this.templates.find(t => t.name === 'globalButtons')
+ const t = this.templates().find(t => t.name() === 'globalButtons')
if (t) this.globalButtonsTemplate = t.template
}
@@ -92,7 +92,7 @@ export class VideosSelectionComponent implements AfterContentInit {
}
getVideosObservable (page: number) {
- return this.getVideosObservableFunction(page, this.sort)
+ return this.getVideosObservableFunction()(page, this.sort)
}
abortSelectionMode () {
@@ -108,12 +108,12 @@ export class VideosSelectionComponent implements AfterContentInit {
}
onNearOfBottom () {
- if (this.disabled) return
+ if (this.disabled()) return
// No more results
- if (this.lastQueryLength !== undefined && this.lastQueryLength < this.pagination.itemsPerPage) return
+ if (this.lastQueryLength !== undefined && this.lastQueryLength < this.pagination().itemsPerPage) return
- this.pagination.currentPage += 1
+ this.pagination().currentPage += 1
this.loadMoreVideos()
}
@@ -121,7 +121,7 @@ export class VideosSelectionComponent implements AfterContentInit {
loadMoreVideos (reset = false) {
if (reset) this.hasDoneFirstQuery = false
- this.getVideosObservable(this.pagination.currentPage)
+ this.getVideosObservable(this.pagination().currentPage)
.subscribe({
next: ({ data }) => {
this.hasDoneFirstQuery = true
@@ -144,7 +144,7 @@ export class VideosSelectionComponent implements AfterContentInit {
}
reloadVideos () {
- resetCurrentPage(this.pagination)
+ resetCurrentPage(this.pagination())
this.loadMoreVideos(true)
}
}
diff --git a/client/src/app/shared/shared-video-playlist/video-add-to-playlist.component.html b/client/src/app/shared/shared-video-playlist/video-add-to-playlist.component.html
index 9270d1365b..5fcbc66a1d 100644
--- a/client/src/app/shared/shared-video-playlist/video-add-to-playlist.component.html
+++ b/client/src/app/shared/shared-video-playlist/video-add-to-playlist.component.html
@@ -40,19 +40,19 @@
<my-peertube-checkbox
[inputName]="getOptionalInputName(playlist, element)"
[ngModel]="element.enabled"
- (click)="toggleOptionalPlaylist($event, playlist, element, startAt.timestamp, stopAt.timestamp)"
+ (click)="toggleOptionalPlaylist($event, playlist, element, startAt.timestamp(), stopAt.timestamp())"
></my-peertube-checkbox>
<my-timestamp-input
class="me-2"
- [maxTimestamp]="video.duration"
+ [maxTimestamp]="video().duration"
[(ngModel)]="element.startTimestamp"
(inputBlur)="onElementTimestampUpdate(playlist, element)"
#startAt
></my-timestamp-input>
<my-timestamp-input
- [maxTimestamp]="video.duration"
+ [maxTimestamp]="video().duration"
[(ngModel)]="element.stopTimestamp"
(inputBlur)="onElementTimestampUpdate(playlist, element)"
#stopAt
diff --git a/client/src/app/shared/shared-video-playlist/video-add-to-playlist.component.ts b/client/src/app/shared/shared-video-playlist/video-add-to-playlist.component.ts
index 6681d88a40..72695025c0 100644
--- a/client/src/app/shared/shared-video-playlist/video-add-to-playlist.component.ts
+++ b/client/src/app/shared/shared-video-playlist/video-add-to-playlist.component.ts
@@ -1,7 +1,17 @@
import debug from 'debug'
import { Subject, Subscription } from 'rxjs'
import { debounceTime, filter } from 'rxjs/operators'
-import { ChangeDetectionStrategy, ChangeDetectorRef, Component, Input, OnChanges, OnDestroy, OnInit, SimpleChanges } from '@angular/core'
+import {
+ ChangeDetectionStrategy,
+ ChangeDetectorRef,
+ Component,
+ OnChanges,
+ OnDestroy,
+ OnInit,
+ SimpleChanges,
+ inject,
+ input
+} from '@angular/core'
import { AuthService, DisableForReuseHook, Notifier } from '@app/core'
import { secondsToTime } from '@peertube/peertube-core-utils'
import {
@@ -56,8 +66,14 @@ type PlaylistSummary = {
]
})
export class VideoAddToPlaylistComponent extends FormReactive implements OnInit, OnChanges, OnDestroy, DisableForReuseHook {
- @Input() video: Video
- @Input() currentVideoTimestamp: number
+ protected formReactiveService = inject(FormReactiveService)
+ private authService = inject(AuthService)
+ private notifier = inject(Notifier)
+ private videoPlaylistService = inject(VideoPlaylistService)
+ private cd = inject(ChangeDetectorRef)
+
+ readonly video = input<Video>(undefined)
+ readonly currentVideoTimestamp = input<number>(undefined)
isNewPlaylistBlockOpened = false
@@ -73,16 +89,6 @@ export class VideoAddToPlaylistComponent extends FormReactive implements OnInit,
private pendingAddId: number
- constructor (
- protected formReactiveService: FormReactiveService,
- private authService: AuthService,
- private notifier: Notifier,
- private videoPlaylistService: VideoPlaylistService,
- private cd: ChangeDetectorRef
- ) {
- super()
- }
-
get user () {
return this.authService.getUser()
}
@@ -93,15 +99,15 @@ export class VideoAddToPlaylistComponent extends FormReactive implements OnInit,
})
this.videoPlaylistService.listenToMyAccountPlaylistsChange()
- .subscribe(result => {
- this.playlistsData = result.data
+ .subscribe(result => {
+ this.playlistsData = result.data
- this.videoPlaylistService.runVideoExistsInPlaylistCheck(this.video.id)
- })
+ this.videoPlaylistService.runVideoExistsInPlaylistCheck(this.video().id)
+ })
this.videoPlaylistSearchChanged
- .pipe(debounceTime(500))
- .subscribe(() => this.load())
+ .pipe(debounceTime(500))
+ .subscribe(() => this.load())
}
ngOnChanges (simpleChanges: SimpleChanges) {
@@ -139,11 +145,11 @@ export class VideoAddToPlaylistComponent extends FormReactive implements OnInit,
this.listenToVideoPlaylistChange()
this.videoPlaylistService.listMyPlaylistWithCache(this.user, this.videoPlaylistSearch)
- .subscribe(playlistsResult => {
- this.playlistsData = playlistsResult.data
+ .subscribe(playlistsResult => {
+ this.playlistsData = playlistsResult.data
- this.videoPlaylistService.runVideoExistsInPlaylistCheck(this.video.id)
- })
+ this.videoPlaylistService.runVideoExistsInPlaylistCheck(this.video().id)
+ })
}
openCreateBlock (event: Event) {
@@ -162,7 +168,7 @@ export class VideoAddToPlaylistComponent extends FormReactive implements OnInit,
enabled: true,
playlistElementId: undefined,
startTimestamp: 0,
- stopTimestamp: this.video.duration
+ stopTimestamp: this.video().duration
}
this.addVideoInPlaylist(playlist, element)
@@ -259,7 +265,7 @@ export class VideoAddToPlaylistComponent extends FormReactive implements OnInit,
elements.push({
enabled: false,
startTimestamp: 0,
- stopTimestamp: this.video.duration
+ stopTimestamp: this.video().duration
})
}
@@ -278,16 +284,16 @@ export class VideoAddToPlaylistComponent extends FormReactive implements OnInit,
stopTimestamp: element.stopTimestamp
}
- this.videoPlaylistService.updateVideoOfPlaylist(playlist.id, element.playlistElementId, body, this.video.id)
- .subscribe({
- next: () => {
- this.notifier.success($localize`Timestamps updated`)
- },
+ this.videoPlaylistService.updateVideoOfPlaylist(playlist.id, element.playlistElementId, body, this.video().id)
+ .subscribe({
+ next: () => {
+ this.notifier.success($localize`Timestamps updated`)
+ },
- error: err => this.notifier.error(err.message),
+ error: err => this.notifier.error(err.message),
- complete: () => this.cd.markForCheck()
- })
+ complete: () => this.cd.markForCheck()
+ })
}
private isOptionalRowDisplayed (playlist: PlaylistSummary) {
@@ -300,7 +306,7 @@ export class VideoAddToPlaylistComponent extends FormReactive implements OnInit,
if (
(element.startTimestamp && element.startTimestamp !== 0) ||
- (element.stopTimestamp && element.stopTimestamp !== this.video.duration)
+ (element.stopTimestamp && element.stopTimestamp !== this.video().duration)
) {
return true
}
@@ -310,24 +316,24 @@ export class VideoAddToPlaylistComponent extends FormReactive implements OnInit,
}
private removeVideoFromPlaylist (playlist: PlaylistSummary, elementId: number) {
- this.videoPlaylistService.removeVideoFromPlaylist(playlist.id, elementId, this.video.id)
- .subscribe({
- next: () => {
- this.notifier.success($localize`Video removed from ${playlist.displayName}`)
- },
+ this.videoPlaylistService.removeVideoFromPlaylist(playlist.id, elementId, this.video().id)
+ .subscribe({
+ next: () => {
+ this.notifier.success($localize`Video removed from ${playlist.displayName}`)
+ },
- error: err => this.notifier.error(err.message),
+ error: err => this.notifier.error(err.message),
- complete: () => this.cd.markForCheck()
- })
+ complete: () => this.cd.markForCheck()
+ })
}
private listenToVideoPlaylistChange () {
this.unsubscribePlaylistChanges()
- this.listenToPlaylistChangeSub = this.videoPlaylistService.listenToVideoPlaylistChange(this.video.id)
- .pipe(filter(() => this.disabled === false))
- .subscribe(existResult => this.rebuildPlaylists(existResult))
+ this.listenToPlaylistChangeSub = this.videoPlaylistService.listenToVideoPlaylistChange(this.video().id)
+ .pipe(filter(() => this.disabled === false))
+ .subscribe(existResult => this.rebuildPlaylists(existResult))
}
private unsubscribePlaylistChanges () {
@@ -338,7 +344,8 @@ export class VideoAddToPlaylistComponent extends FormReactive implements OnInit,
}
private rebuildPlaylists (existResult: CachedVideoExistInPlaylist[]) {
- debugLogger('Got existing results for %d.', this.video.id, existResult)
+ const video = this.video()
+ debugLogger('Got existing results for %d.', video.id, existResult)
const oldPlaylists = this.videoPlaylists
@@ -354,7 +361,7 @@ export class VideoAddToPlaylistComponent extends FormReactive implements OnInit,
enabled: true,
playlistElementId: e.playlistElementId,
startTimestamp: e.startTimestamp || 0,
- stopTimestamp: e.stopTimestamp || this.video.duration
+ stopTimestamp: e.stopTimestamp || this.video().duration
}))
}
@@ -366,16 +373,16 @@ export class VideoAddToPlaylistComponent extends FormReactive implements OnInit,
this.videoPlaylists.push(playlistSummary)
}
- debugLogger('Rebuilt playlist state for video %d.', this.video.id, this.videoPlaylists)
+ debugLogger('Rebuilt playlist state for video %d.', video.id, this.videoPlaylists)
this.cd.markForCheck()
}
private addVideoInPlaylist (playlist: PlaylistSummary, element: PlaylistElement) {
- const body: VideoPlaylistElementCreate = { videoId: this.video.id }
+ const body: VideoPlaylistElementCreate = { videoId: this.video().id }
if (element.startTimestamp) body.startTimestamp = element.startTimestamp
- if (element.stopTimestamp && element.stopTimestamp !== this.video.duration) body.stopTimestamp = element.stopTimestamp
+ if (element.stopTimestamp && element.stopTimestamp !== this.video().duration) body.stopTimestamp = element.stopTimestamp
this.pendingAddId = playlist.id
diff --git a/client/src/app/shared/shared-video-playlist/video-playlist-element-miniature.component.html b/client/src/app/shared/shared-video-playlist/video-playlist-element-miniature.component.html
index 517b76af6d..956729a093 100644
--- a/client/src/app/shared/shared-video-playlist/video-playlist-element-miniature.component.html
+++ b/client/src/app/shared/shared-video-playlist/video-playlist-element-miniature.component.html
@@ -1,58 +1,58 @@
-<div class="video" [ngClass]="{ playing: playing }">
+<div class="video" [ngClass]="{ playing: playing() }">
<a [routerLink]="buildRouterLink()" [queryParams]="buildRouterQuery()">
<div class="position">
- <my-global-icon *ngIf="playing" iconName="play"></my-global-icon>
- <ng-container *ngIf="!playing">{{ position }}</ng-container>
+ <my-global-icon *ngIf="playing()" iconName="play"></my-global-icon>
+ <ng-container *ngIf="!playing()">{{ position() }}</ng-container>
</div>
<my-video-thumbnail
- *ngIf="playlistElement.video"
- [video]="playlistElement.video" [nsfw]="isVideoBlur(playlistElement.video)"
+ *ngIf="playlistElement().video"
+ [video]="playlistElement().video" [nsfw]="isVideoBlur(playlistElement().video)"
[videoRouterLink]="buildRouterLink()" [queryParams]="buildRouterQuery()" [ariaLabel]="getVideoAriaLabel()"
></my-video-thumbnail>
- <div class="fake-thumbnail" *ngIf="!playlistElement.video"></div>
+ <div class="fake-thumbnail" *ngIf="!playlistElement().video"></div>
<div class="video-info">
- <ng-container *ngIf="playlistElement.video">
+ <ng-container *ngIf="playlistElement().video">
<div class="video-info-header">
<a
- tabindex="-1" class="video-info-name" [ariaLabel]="getVideoAriaLabel()" [attr.title]="playlistElement.video.name"
+ tabindex="-1" class="video-info-name" [ariaLabel]="getVideoAriaLabel()" [attr.title]="playlistElement().video.name"
[routerLink]="buildRouterLink()" [queryParams]="buildRouterQuery()"
- >{{ playlistElement.video.name }}</a>
+ >{{ playlistElement().video.name }}</a>
<span i18n *ngIf="isVideoPrivate()" class="pt-badge badge-yellow">Private</span>
<span i18n *ngIf="isVideoPasswordProtected()" class="pt-badge badge-yellow">Password protected</span>
</div>
<span class="date-and-views">
- <my-date-toggle [date]="playlistElement.video.publishedAt"></my-date-toggle>
+ <my-date-toggle [date]="playlistElement().video.publishedAt"></my-date-toggle>
<span class="views">
- • <my-video-views-counter [isLive]="playlistElement.video.isLive" [viewers]="playlistElement.video.viewers" [views]="playlistElement.video.views"></my-video-views-counter>
+ • <my-video-views-counter [isLive]="playlistElement().video.isLive" [viewers]="playlistElement().video.viewers" [views]="playlistElement().video.views"></my-video-views-counter>
</span>
</span>
- <a *ngIf="accountLink" tabindex="-1" class="video-info-owner" [routerLink]="[ '/c', playlistElement.video.byVideoChannel ]">
- <ng-container *ngIf="getVideoOwnerDisplayType(playlistElement) === 'account'">{{ playlistElement.video.byAccount }}</ng-container>
- <ng-container *ngIf="getVideoOwnerDisplayType(playlistElement) === 'videoChannel'">{{ playlistElement.video.byVideoChannel }}</ng-container>
+ <a *ngIf="accountLink()" tabindex="-1" class="video-info-owner" [routerLink]="[ '/c', playlistElement().video.byVideoChannel ]">
+ <ng-container *ngIf="getVideoOwnerDisplayType(playlistElement()) === 'account'">{{ playlistElement().video.byAccount }}</ng-container>
+ <ng-container *ngIf="getVideoOwnerDisplayType(playlistElement()) === 'videoChannel'">{{ playlistElement().video.byVideoChannel }}</ng-container>
</a>
- <span *ngIf="!accountLink" tabindex="-1" class="video-info-owner">{{ playlistElement.video.byAccount }}</span>
+ <span *ngIf="!accountLink()" tabindex="-1" class="video-info-owner">{{ playlistElement().video.byAccount }}</span>
- <span tabindex="-1" class="video-info-timestamp">{{ formatTimestamp(playlistElement) }}</span>
+ <span tabindex="-1" class="video-info-timestamp">{{ formatTimestamp(playlistElement()) }}</span>
</ng-container>
- <span *ngIf="!playlistElement.video" class="video-info-name">
- <ng-container i18n *ngIf="isUnavailable(playlistElement)">Unavailable</ng-container>
- <ng-container i18n *ngIf="isPrivate(playlistElement)">Private</ng-container>
- <ng-container i18n *ngIf="isDeleted(playlistElement)">Deleted</ng-container>
+ <span *ngIf="!playlistElement().video" class="video-info-name">
+ <ng-container i18n *ngIf="isUnavailable(playlistElement())">Unavailable</ng-container>
+ <ng-container i18n *ngIf="isPrivate(playlistElement())">Private</ng-container>
+ <ng-container i18n *ngIf="isDeleted(playlistElement())">Deleted</ng-container>
</span>
</div>
</a>
<div
- *ngIf="owned" class="more dropdown-root" ngbDropdown #moreDropdown="ngbDropdown" placement="left auto"
+ *ngIf="owned()" class="more dropdown-root" ngbDropdown #moreDropdown="ngbDropdown" placement="left auto"
(openChange)="onDropdownOpenChange()" autoClose="outside" container="body"
>
<button class="border-0 p-0 more-button" (click)="$event.preventDefault()" ngbDropdownToggle>
@@ -60,8 +60,8 @@
</button>
<div ngbDropdownMenu>
- <ng-container *ngIf="playlistElement.video">
- <button ngbDropdownItem (click)="toggleDisplayTimestampsOptions($event, playlistElement)">
+ <ng-container *ngIf="playlistElement().video">
+ <button ngbDropdownItem (click)="toggleDisplayTimestampsOptions($event, playlistElement())">
<my-global-icon iconName="edit" aria-hidden="true"></my-global-icon>
<ng-container i18n>Edit starts/stops at</ng-container>
</button>
@@ -75,7 +75,7 @@
<my-timestamp-input
[timestamp]="timestampOptions.startTimestamp"
- [maxTimestamp]="playlistElement.video.duration"
+ [maxTimestamp]="playlistElement().video.duration"
[disabled]="!timestampOptions.startTimestampEnabled"
[(ngModel)]="timestampOptions.startTimestamp"
></my-timestamp-input>
@@ -89,19 +89,19 @@
<my-timestamp-input
[timestamp]="timestampOptions.stopTimestamp"
- [maxTimestamp]="playlistElement.video.duration"
+ [maxTimestamp]="playlistElement().video.duration"
[disabled]="!timestampOptions.stopTimestampEnabled"
[(ngModel)]="timestampOptions.stopTimestamp"
></my-timestamp-input>
</div>
- <input class="peertube-button primary-button mt-2" type="submit" i18n-value value="Save" (click)="updateTimestamps(playlistElement)">
+ <input class="peertube-button primary-button mt-2" type="submit" i18n-value value="Save" (click)="updateTimestamps(playlistElement())">
</div>
</ng-container>
- <button ngbDropdownItem (click)="removeFromPlaylist(playlistElement)">
+ <button ngbDropdownItem (click)="removeFromPlaylist(playlistElement())">
<my-global-icon iconName="delete" aria-hidden="true"></my-global-icon>
- <ng-container i18n>Delete from {{ playlist?.displayName }}</ng-container>
+ <ng-container i18n>Delete from {{ playlist()?.displayName }}</ng-container>
</button>
</div>
</div>
diff --git a/client/src/app/shared/shared-video-playlist/video-playlist-element-miniature.component.ts b/client/src/app/shared/shared-video-playlist/video-playlist-element-miniature.component.ts
index bc4373a50a..6b293319bb 100644
--- a/client/src/app/shared/shared-video-playlist/video-playlist-element-miniature.component.ts
+++ b/client/src/app/shared/shared-video-playlist/video-playlist-element-miniature.component.ts
@@ -1,4 +1,4 @@
-import { ChangeDetectionStrategy, ChangeDetectorRef, Component, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core'
+import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit, inject, input, output, viewChild } from '@angular/core'
import { AuthService, Notifier, ServerService } from '@app/core'
import { NgbDropdown, NgbDropdownToggle, NgbDropdownMenu, NgbDropdownButtonItem, NgbDropdownItem } from '@ng-bootstrap/ng-bootstrap'
import { secondsToTime } from '@peertube/peertube-core-utils'
@@ -9,7 +9,7 @@ import { VideoPlaylistService } from './video-playlist.service'
import { TimestampInputComponent } from '../shared-forms/timestamp-input.component'
import { FormsModule } from '@angular/forms'
import { PeertubeCheckboxComponent } from '../shared-forms/peertube-checkbox.component'
-import { EditButtonComponent } from '../shared-main/buttons/edit-button.component'
+
import { VideoViewsCounterComponent } from '../shared-video/video-views-counter.component'
import { DateToggleComponent } from '../shared-main/date/date-toggle.component'
import { VideoThumbnailComponent } from '../shared-thumbnail/video-thumbnail.component'
@@ -32,7 +32,6 @@ import { VideoService } from '../shared-main/video/video.service'
VideoThumbnailComponent,
DateToggleComponent,
VideoViewsCounterComponent,
- EditButtonComponent,
NgbDropdown,
NgbDropdownToggle,
NgbDropdownMenu,
@@ -44,17 +43,25 @@ import { VideoService } from '../shared-main/video/video.service'
]
})
export class VideoPlaylistElementMiniatureComponent implements OnInit {
- @ViewChild('moreDropdown') moreDropdown: NgbDropdown
-
- @Input() playlist: VideoPlaylist
- @Input() playlistElement: VideoPlaylistElement
- @Input() owned = false
- @Input() playing = false
- @Input() rowLink = false
- @Input() accountLink = true
- @Input() position: number // Keep this property because we're in the OnPush change detection strategy
-
- @Output() elementRemoved = new EventEmitter<VideoPlaylistElement>()
+ private authService = inject(AuthService)
+ private serverService = inject(ServerService)
+ private notifier = inject(Notifier)
+ private videoPlaylistService = inject(VideoPlaylistService)
+ private videoService = inject(VideoService)
+ private cdr = inject(ChangeDetectorRef)
+
+ readonly moreDropdown = viewChild<NgbDropdown>('moreDropdown')
+
+ readonly playlist = input<VideoPlaylist>(undefined)
+ readonly playlistElement = input<VideoPlaylistElement>(undefined)
+ readonly owned = input(false)
+ readonly playing = input(false)
+ readonly rowLink = input(false)
+ readonly accountLink = input(true)
+ readonly position = input<number // Keep this property because we're in the OnPush change detection strategy
+ >(undefined) // Keep this property because we're in the OnPush change detection strategy
+
+ readonly elementRemoved = output<VideoPlaylistElement>()
displayTimestampOptions = false
@@ -67,21 +74,12 @@ export class VideoPlaylistElementMiniatureComponent implements OnInit {
private serverConfig: HTMLServerConfig
- constructor (
- private authService: AuthService,
- private serverService: ServerService,
- private notifier: Notifier,
- private videoPlaylistService: VideoPlaylistService,
- private videoService: VideoService,
- private cdr: ChangeDetectorRef
- ) {}
-
ngOnInit (): void {
this.serverConfig = this.serverService.getHTMLConfig()
}
getVideoAriaLabel () {
- return $localize`Watch video ${this.playlistElement.video.name}`
+ return $localize`Watch video ${this.playlistElement().video.name}`
}
getVideoOwnerDisplayType (element: VideoPlaylistElement) {
@@ -89,11 +87,11 @@ export class VideoPlaylistElementMiniatureComponent implements OnInit {
}
isVideoPrivate () {
- return this.playlistElement.video.privacy.id === VideoPrivacy.PRIVATE
+ return this.playlistElement().video.privacy.id === VideoPrivacy.PRIVATE
}
isVideoPasswordProtected () {
- return this.playlistElement.video.privacy.id === VideoPrivacy.PASSWORD_PROTECTED
+ return this.playlistElement().video.privacy.id === VideoPrivacy.PASSWORD_PROTECTED
}
isUnavailable (e: VideoPlaylistElement) {
@@ -109,18 +107,20 @@ export class VideoPlaylistElementMiniatureComponent implements OnInit {
}
buildRouterLink () {
- if (!this.playlist) return null
+ const playlist = this.playlist()
+ if (!playlist) return null
- return VideoPlaylist.buildWatchUrl(this.playlist)
+ return VideoPlaylist.buildWatchUrl(playlist)
}
buildRouterQuery () {
- if (!this.playlistElement?.video) return {}
+ const playlistElement = this.playlistElement()
+ if (!playlistElement?.video) return {}
return {
- playlistPosition: this.playlistElement.position,
- start: this.playlistElement.startTimestamp,
- stop: this.playlistElement.stopTimestamp,
+ playlistPosition: playlistElement.position,
+ start: playlistElement.startTimestamp,
+ stop: playlistElement.stopTimestamp,
resume: true
}
}
@@ -130,19 +130,20 @@ export class VideoPlaylistElementMiniatureComponent implements OnInit {
}
removeFromPlaylist (playlistElement: VideoPlaylistElement) {
- const videoId = this.playlistElement.video ? this.playlistElement.video.id : undefined
+ const playlistElementValue = this.playlistElement()
+ const videoId = playlistElementValue.video ? playlistElementValue.video.id : undefined
- this.videoPlaylistService.removeVideoFromPlaylist(this.playlist.id, playlistElement.id, videoId)
- .subscribe({
- next: () => {
- this.notifier.success($localize`Video removed from ${this.playlist.displayName}`)
- this.elementRemoved.emit(playlistElement)
- },
+ this.videoPlaylistService.removeVideoFromPlaylist(this.playlist().id, playlistElement.id, videoId)
+ .subscribe({
+ next: () => {
+ this.notifier.success($localize`Video removed from ${this.playlist().displayName}`)
+ this.elementRemoved.emit(playlistElement)
+ },
- error: err => this.notifier.error(err.message)
- })
+ error: err => this.notifier.error(err.message)
+ })
- this.moreDropdown.close()
+ this.moreDropdown().close()
}
updateTimestamps (playlistElement: VideoPlaylistElement) {
@@ -151,21 +152,21 @@ export class VideoPlaylistElementMiniatureComponent implements OnInit {
body.startTimestamp = this.timestampOptions.startTimestampEnabled ? this.timestampOptions.startTimestamp : null
body.stopTimestamp = this.timestampOptions.stopTimestampEnabled ? this.timestampOptions.stopTimestamp : null
- this.videoPlaylistService.updateVideoOfPlaylist(this.playlist.id, playlistElement.id, body, this.playlistElement.video.id)
- .subscribe({
- next: () => {
- this.notifier.success($localize`Timestamps updated`)
+ this.videoPlaylistService.updateVideoOfPlaylist(this.playlist().id, playlistElement.id, body, this.playlistElement().video.id)
+ .subscribe({
+ next: () => {
+ this.notifier.success($localize`Timestamps updated`)
- playlistElement.startTimestamp = body.startTimestamp
- playlistElement.stopTimestamp = body.stopTimestamp
+ playlistElement.startTimestamp = body.startTimestamp
+ playlistElement.stopTimestamp = body.stopTimestamp
- this.cdr.detectChanges()
- },
+ this.cdr.detectChanges()
+ },
- error: err => this.notifier.error(err.message)
- })
+ error: err => this.notifier.error(err.message)
+ })
- this.moreDropdown.close()
+ this.moreDropdown().close()
}
formatTimestamp (playlistElement: VideoPlaylistElement) {
diff --git a/client/src/app/shared/shared-video-playlist/video-playlist-miniature.component.html b/client/src/app/shared/shared-video-playlist/video-playlist-miniature.component.html
index 471044dcf4..6b0c4d2e7e 100644
--- a/client/src/app/shared/shared-video-playlist/video-playlist-miniature.component.html
+++ b/client/src/app/shared/shared-video-playlist/video-playlist-miniature.component.html
@@ -1,12 +1,12 @@
-<div class="miniature" [ngClass]="{ 'no-videos': playlist.videosLength === 0, 'to-manage': toManage, 'display-as-row': displayAsRow }">
+<div class="miniature" [ngClass]="{ 'no-videos': playlist().videosLength === 0, 'to-manage': toManage(), 'display-as-row': displayAsRow() }">
<my-link
[internalLink]="routerLink" [href]="playlistHref" [target]="playlistTarget" inheritParentStyle="true" inheritParentDimension="true"
- [title]="playlist.description" class="miniature-thumbnail" tabindex="-1"
+ [title]="playlist().description" class="miniature-thumbnail" tabindex="-1"
>
- <img alt="" [attr.aria-labelledby]="playlist.displayName" [attr.src]="playlist.thumbnailUrl" />
+ <img alt="" [attr.aria-labelledby]="playlist().displayName" [attr.src]="playlist().thumbnailUrl" />
<div class="miniature-playlist-info-overlay">
- <ng-container i18n>{playlist.videosLength, plural, =0 {No videos} =1 {1 video} other {{{ playlist.videosLength }} videos}}</ng-container>
+ <ng-container i18n>{playlist().videosLength, plural, =0 {No videos} =1 {1 video} other {{{ playlist().videosLength }} videos}}</ng-container>
</div>
<div class="play-overlay">
@@ -17,21 +17,21 @@
<div class="miniature-info">
<my-link
[internalLink]="routerLink" [href]="playlistHref" [target]="playlistTarget" inheritParentStyle="true" inheritParentDimension="true"
- [title]="playlist.description" class="miniature-name" className="ellipsis-multiline-2"
+ [title]="playlist().description" class="miniature-name" className="ellipsis-multiline-2"
>
- {{ playlist.displayName }}
+ {{ playlist().displayName }}
</my-link>
- <a i18n [routerLink]="[ '/c', playlist.videoChannelBy ]" class="by" *ngIf="displayChannel && playlist.videoChannelBy">
- {{ playlist.videoChannelBy }}
+ <a i18n [routerLink]="[ '/c', playlist().videoChannelBy ]" class="by" *ngIf="displayChannel() && playlist().videoChannelBy">
+ {{ playlist().videoChannelBy }}
</a>
<div class="privacy-date">
- <span class="privacy" *ngIf="displayPrivacy">{{ playlist.privacy.label }}</span>
+ <span class="privacy" *ngIf="displayPrivacy()">{{ playlist().privacy.label }}</span>
- <span i18n class="updated-at">Updated {{ playlist.updatedAt | myFromNow }}</span>
+ <span i18n class="updated-at">Updated {{ playlist().updatedAt | myFromNow }}</span>
</div>
- <div *ngIf="displayDescription" class="description" [innerHTML]="playlistDescription"></div>
+ <div *ngIf="displayDescription()" class="description" [innerHTML]="playlistDescription"></div>
</div>
</div>
diff --git a/client/src/app/shared/shared-video-playlist/video-playlist-miniature.component.ts b/client/src/app/shared/shared-video-playlist/video-playlist-miniature.component.ts
index 7c36f855d7..f1831dcfdf 100644
--- a/client/src/app/shared/shared-video-playlist/video-playlist-miniature.component.ts
+++ b/client/src/app/shared/shared-video-playlist/video-playlist-miniature.component.ts
@@ -1,5 +1,5 @@
import { LinkType } from 'src/types/link.type'
-import { Component, Input, OnInit } from '@angular/core'
+import { Component, OnInit, inject, input } from '@angular/core'
import { VideoPlaylist } from './video-playlist.model'
import { MarkdownService } from '@app/core'
import { FromNowPipe } from '../shared-main/date/from-now.pipe'
@@ -14,58 +14,58 @@ import { NgClass, NgIf } from '@angular/common'
imports: [ NgClass, LinkComponent, NgIf, RouterLink, FromNowPipe ]
})
export class VideoPlaylistMiniatureComponent implements OnInit {
- @Input() playlist: VideoPlaylist
+ private markdownService = inject(MarkdownService)
- @Input() toManage = false
+ readonly playlist = input<VideoPlaylist>(undefined)
- @Input() displayChannel = false
- @Input() displayDescription = false
- @Input() displayPrivacy = false
- @Input() displayAsRow = false
+ readonly toManage = input(false)
- @Input() linkType: LinkType = 'internal'
+ readonly displayChannel = input(false)
+ readonly displayDescription = input(false)
+ readonly displayPrivacy = input(false)
+ readonly displayAsRow = input(false)
+
+ readonly linkType = input<LinkType>('internal')
routerLink: any
playlistHref: string
playlistTarget: string
playlistDescription: string
- constructor (
- private markdownService: MarkdownService
- ) {}
-
async ngOnInit () {
this.buildPlaylistUrl()
- if (this.displayDescription) {
- this.playlistDescription = await this.markdownService.textMarkdownToHTML({ markdown: this.playlist.description })
+ if (this.displayDescription()) {
+ this.playlistDescription = await this.markdownService.textMarkdownToHTML({ markdown: this.playlist().description })
}
}
buildPlaylistUrl () {
- if (this.toManage) {
- this.routerLink = [ '/my-library/video-playlists', this.playlist.shortUUID ]
+ if (this.toManage()) {
+ this.routerLink = [ '/my-library/video-playlists', this.playlist().shortUUID ]
return
}
- if (this.playlist.videosLength === 0) {
+ const playlist = this.playlist()
+ if (playlist.videosLength === 0) {
this.routerLink = null
return
}
- if (this.linkType === 'internal' || !this.playlist.url) {
- this.routerLink = VideoPlaylist.buildWatchUrl(this.playlist)
+ const linkType = this.linkType()
+ if (linkType === 'internal' || !playlist.url) {
+ this.routerLink = VideoPlaylist.buildWatchUrl(playlist)
return
}
- if (this.linkType === 'external') {
+ if (linkType === 'external') {
this.routerLink = null
- this.playlistHref = this.playlist.url
+ this.playlistHref = playlist.url
this.playlistTarget = '_blank'
return
}
// Lazy load
- this.routerLink = [ '/search/lazy-load-playlist', { url: this.playlist.url } ]
+ this.routerLink = [ '/search/lazy-load-playlist', { url: playlist.url } ]
return
}
diff --git a/client/src/app/shared/shared-video-playlist/video-playlist.service.ts b/client/src/app/shared/shared-video-playlist/video-playlist.service.ts
index 18ac930e7b..9190d84ee6 100644
--- a/client/src/app/shared/shared-video-playlist/video-playlist.service.ts
+++ b/client/src/app/shared/shared-video-playlist/video-playlist.service.ts
@@ -2,7 +2,7 @@ import debug from 'debug'
import { merge, Observable, of, ReplaySubject, Subject } from 'rxjs'
import { catchError, filter, map, share, switchMap, tap } from 'rxjs/operators'
import { HttpClient, HttpContext, HttpParams } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { AuthService, AuthUser, ComponentPaginationLight, RestExtractor, RestService, ServerService } from '@app/core'
import { buildBulkObservable, objectToFormData } from '@app/helpers'
import { NGX_LOADING_BAR_IGNORED } from '@ngx-loading-bar/http-client'
@@ -34,6 +34,12 @@ export type CachedPlaylist = VideoPlaylist | { id: number, displayName: string }
@Injectable()
export class VideoPlaylistService {
+ private authHttp = inject(HttpClient)
+ private auth = inject(AuthService)
+ private serverService = inject(ServerService)
+ private restExtractor = inject(RestExtractor)
+ private restService = inject(RestService)
+
static BASE_VIDEO_PLAYLIST_URL = environment.apiUrl + '/api/v1/video-playlists/'
static MY_VIDEO_PLAYLIST_URL = environment.apiUrl + '/api/v1/users/me/video-playlists/'
@@ -42,20 +48,14 @@ export class VideoPlaylistService {
private videoExistsInPlaylistCacheSubject = new Subject<CachedVideosExistInPlaylists>()
private readonly videoExistsInPlaylistObservable: Observable<CachedVideosExistInPlaylists>
- private videoExistsObservableCache: { [ id: number ]: Observable<CachedVideoExistInPlaylist[]> } = {}
- private videoExistsCache: { [ id: number ]: CachedVideoExistInPlaylist[] } = {}
+ private videoExistsObservableCache: { [id: number]: Observable<CachedVideoExistInPlaylist[]> } = {}
+ private videoExistsCache: { [id: number]: CachedVideoExistInPlaylist[] } = {}
private myAccountPlaylistCache: ResultList<CachedPlaylist> = undefined
private myAccountPlaylistCacheRunning: Observable<ResultList<CachedPlaylist>>
private myAccountPlaylistCacheSubject = new Subject<ResultList<CachedPlaylist>>()
- constructor (
- private authHttp: HttpClient,
- private auth: AuthService,
- private serverService: ServerService,
- private restExtractor: RestExtractor,
- private restService: RestService
- ) {
+ constructor () {
this.videoExistsInPlaylistObservable = merge(
buildBulkObservable({
time: 200,
@@ -69,7 +69,6 @@ export class VideoPlaylistService {
},
notifierObservable: this.videoExistsInPlaylistNotifier
}).pipe(map(({ response }) => response)),
-
this.videoExistsInPlaylistCacheSubject
)
}
@@ -82,10 +81,10 @@ export class VideoPlaylistService {
params = this.restService.addRestGetParams(params, pagination)
return this.authHttp.get<ResultList<VideoPlaylist>>(url, { params })
- .pipe(
- switchMap(res => this.extractPlaylists(res)),
- catchError(err => this.restExtractor.handleError(err))
- )
+ .pipe(
+ switchMap(res => this.extractPlaylists(res)),
+ catchError(err => this.restExtractor.handleError(err))
+ )
}
listMyPlaylistWithCache (user: AuthUser, search?: string) {
@@ -95,15 +94,15 @@ export class VideoPlaylistService {
}
const obs = this.listAccountPlaylists(user.account, undefined, '-updatedAt', search)
- .pipe(
- tap(result => {
- if (!search) {
- this.myAccountPlaylistCacheRunning = undefined
- this.myAccountPlaylistCache = result
- }
- }),
- share()
- )
+ .pipe(
+ tap(result => {
+ if (!search) {
+ this.myAccountPlaylistCacheRunning = undefined
+ this.myAccountPlaylistCache = result
+ }
+ }),
+ share()
+ )
if (!search) this.myAccountPlaylistCacheRunning = obs
return obs
@@ -125,138 +124,138 @@ export class VideoPlaylistService {
if (search) params = this.restService.addObjectParams(params, { search })
return this.authHttp.get<ResultList<VideoPlaylist>>(url, { params })
- .pipe(
- switchMap(res => this.extractPlaylists(res)),
- catchError(err => this.restExtractor.handleError(err))
- )
+ .pipe(
+ switchMap(res => this.extractPlaylists(res)),
+ catchError(err => this.restExtractor.handleError(err))
+ )
}
getVideoPlaylist (id: string | number) {
const url = VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + id
return this.authHttp.get<VideoPlaylist>(url)
- .pipe(
- switchMap(res => this.extractPlaylist(res)),
- catchError(err => this.restExtractor.handleError(err))
- )
+ .pipe(
+ switchMap(res => this.extractPlaylist(res)),
+ catchError(err => this.restExtractor.handleError(err))
+ )
}
createVideoPlaylist (body: VideoPlaylistCreate) {
const data = objectToFormData(body)
return this.authHttp.post<{ videoPlaylist: { id: number } }>(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL, data)
- .pipe(
- tap(res => {
- if (!this.myAccountPlaylistCache) return
+ .pipe(
+ tap(res => {
+ if (!this.myAccountPlaylistCache) return
- this.myAccountPlaylistCache.total++
+ this.myAccountPlaylistCache.total++
- this.myAccountPlaylistCache.data.push({
- id: res.videoPlaylist.id,
- displayName: body.displayName
- })
+ this.myAccountPlaylistCache.data.push({
+ id: res.videoPlaylist.id,
+ displayName: body.displayName
+ })
- this.myAccountPlaylistCacheSubject.next(this.myAccountPlaylistCache)
- }),
- catchError(err => this.restExtractor.handleError(err))
- )
+ this.myAccountPlaylistCacheSubject.next(this.myAccountPlaylistCache)
+ }),
+ catchError(err => this.restExtractor.handleError(err))
+ )
}
updateVideoPlaylist (videoPlaylist: VideoPlaylist, body: VideoPlaylistUpdate) {
const data = objectToFormData(body)
return this.authHttp.put(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + videoPlaylist.id, data)
- .pipe(
- tap(() => {
- if (!this.myAccountPlaylistCache) return
+ .pipe(
+ tap(() => {
+ if (!this.myAccountPlaylistCache) return
- const playlist = this.myAccountPlaylistCache.data.find(p => p.id === videoPlaylist.id)
- playlist.displayName = body.displayName
+ const playlist = this.myAccountPlaylistCache.data.find(p => p.id === videoPlaylist.id)
+ playlist.displayName = body.displayName
- this.myAccountPlaylistCacheSubject.next(this.myAccountPlaylistCache)
- }),
- catchError(err => this.restExtractor.handleError(err))
- )
+ this.myAccountPlaylistCacheSubject.next(this.myAccountPlaylistCache)
+ }),
+ catchError(err => this.restExtractor.handleError(err))
+ )
}
removeVideoPlaylist (videoPlaylist: VideoPlaylist) {
return this.authHttp.delete(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + videoPlaylist.id)
- .pipe(
- tap(() => {
- if (!this.myAccountPlaylistCache) return
-
- this.myAccountPlaylistCache.total--
- this.myAccountPlaylistCache.data = this.myAccountPlaylistCache.data
- .filter(p => p.id !== videoPlaylist.id)
-
- this.myAccountPlaylistCacheSubject.next(this.myAccountPlaylistCache)
- }),
- catchError(err => this.restExtractor.handleError(err))
- )
+ .pipe(
+ tap(() => {
+ if (!this.myAccountPlaylistCache) return
+
+ this.myAccountPlaylistCache.total--
+ this.myAccountPlaylistCache.data = this.myAccountPlaylistCache.data
+ .filter(p => p.id !== videoPlaylist.id)
+
+ this.myAccountPlaylistCacheSubject.next(this.myAccountPlaylistCache)
+ }),
+ catchError(err => this.restExtractor.handleError(err))
+ )
}
addVideoInPlaylist (playlistId: number, body: VideoPlaylistElementCreate) {
const url = VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos'
return this.authHttp.post<{ videoPlaylistElement: { id: number } }>(url, body)
- .pipe(
- tap(res => {
- const existsResult = this.videoExistsCache[body.videoId]
- existsResult.push({
- playlistId,
- playlistElementId: res.videoPlaylistElement.id,
- startTimestamp: body.startTimestamp,
- stopTimestamp: body.stopTimestamp
- })
-
- this.runVideoExistsInPlaylistCheck(body.videoId)
-
- if (this.myAccountPlaylistCache) {
- const playlist = this.myAccountPlaylistCache.data.find(p => p.id === playlistId)
- if (!playlist) return
-
- const otherPlaylists = this.myAccountPlaylistCache.data.filter(p => p !== playlist)
- this.myAccountPlaylistCache.data = [ playlist, ...otherPlaylists ]
- }
- }),
- catchError(err => this.restExtractor.handleError(err))
- )
+ .pipe(
+ tap(res => {
+ const existsResult = this.videoExistsCache[body.videoId]
+ existsResult.push({
+ playlistId,
+ playlistElementId: res.videoPlaylistElement.id,
+ startTimestamp: body.startTimestamp,
+ stopTimestamp: body.stopTimestamp
+ })
+
+ this.runVideoExistsInPlaylistCheck(body.videoId)
+
+ if (this.myAccountPlaylistCache) {
+ const playlist = this.myAccountPlaylistCache.data.find(p => p.id === playlistId)
+ if (!playlist) return
+
+ const otherPlaylists = this.myAccountPlaylistCache.data.filter(p => p !== playlist)
+ this.myAccountPlaylistCache.data = [ playlist, ...otherPlaylists ]
+ }
+ }),
+ catchError(err => this.restExtractor.handleError(err))
+ )
}
updateVideoOfPlaylist (playlistId: number, playlistElementId: number, body: VideoPlaylistElementUpdate, videoId: number) {
return this.authHttp.put(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos/' + playlistElementId, body)
- .pipe(
- tap(() => {
- const existsResult = this.videoExistsCache[videoId]
+ .pipe(
+ tap(() => {
+ const existsResult = this.videoExistsCache[videoId]
- if (existsResult) {
- const elem = existsResult.find(e => e.playlistElementId === playlistElementId)
+ if (existsResult) {
+ const elem = existsResult.find(e => e.playlistElementId === playlistElementId)
- elem.startTimestamp = body.startTimestamp
- elem.stopTimestamp = body.stopTimestamp
- }
+ elem.startTimestamp = body.startTimestamp
+ elem.stopTimestamp = body.stopTimestamp
+ }
- this.runVideoExistsInPlaylistCheck(videoId)
- }),
- catchError(err => this.restExtractor.handleError(err))
- )
+ this.runVideoExistsInPlaylistCheck(videoId)
+ }),
+ catchError(err => this.restExtractor.handleError(err))
+ )
}
removeVideoFromPlaylist (playlistId: number, playlistElementId: number, videoId?: number) {
return this.authHttp.delete(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos/' + playlistElementId)
- .pipe(
- tap(() => {
- if (!videoId) return
-
- if (this.videoExistsCache[videoId]) {
- this.videoExistsCache[videoId] = this.videoExistsCache[videoId]
- .filter(e => e.playlistElementId !== playlistElementId)
- }
-
- this.runVideoExistsInPlaylistCheck(videoId)
- }),
- catchError(err => this.restExtractor.handleError(err))
- )
+ .pipe(
+ tap(() => {
+ if (!videoId) return
+
+ if (this.videoExistsCache[videoId]) {
+ this.videoExistsCache[videoId] = this.videoExistsCache[videoId]
+ .filter(e => e.playlistElementId !== playlistElementId)
+ }
+
+ this.runVideoExistsInPlaylistCheck(videoId)
+ }),
+ catchError(err => this.restExtractor.handleError(err))
+ )
}
reorderPlaylist (playlistId: number, oldPosition: number, newPosition: number) {
@@ -266,7 +265,7 @@ export class VideoPlaylistService {
}
return this.authHttp.post(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos/reorder', body)
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
getPlaylistVideos (options: {
@@ -280,11 +279,11 @@ export class VideoPlaylistService {
params = this.restService.addRestGetParams(params, pagination)
return this.authHttp
- .get<ResultList<ServerVideoPlaylistElement>>(path, { params })
- .pipe(
- switchMap(res => this.extractVideoPlaylistElements(res)),
- catchError(err => this.restExtractor.handleError(err))
- )
+ .get<ResultList<ServerVideoPlaylistElement>>(path, { params })
+ .pipe(
+ switchMap(res => this.extractVideoPlaylistElements(res)),
+ catchError(err => this.restExtractor.handleError(err))
+ )
}
listenToMyAccountPlaylistsChange () {
@@ -297,11 +296,11 @@ export class VideoPlaylistService {
}
const obs = this.videoExistsInPlaylistObservable
- .pipe(
- map(existsResult => existsResult[videoId]),
- filter(r => !!r),
- tap(result => this.videoExistsCache[videoId] = result)
- )
+ .pipe(
+ map(existsResult => existsResult[videoId]),
+ filter(r => !!r),
+ tap(result => this.videoExistsCache[videoId] = result)
+ )
this.videoExistsObservableCache[videoId] = obs
return obs
@@ -322,41 +321,41 @@ export class VideoPlaylistService {
extractPlaylists (result: ResultList<VideoPlaylistServerModel>) {
return this.serverService.getServerLocale()
- .pipe(
- map(translations => {
- const playlistsJSON = result.data
- const total = result.total
- const playlists: VideoPlaylist[] = []
-
- for (const playlistJSON of playlistsJSON) {
- playlists.push(new VideoPlaylist(playlistJSON, translations))
- }
-
- return { data: playlists, total }
- })
- )
+ .pipe(
+ map(translations => {
+ const playlistsJSON = result.data
+ const total = result.total
+ const playlists: VideoPlaylist[] = []
+
+ for (const playlistJSON of playlistsJSON) {
+ playlists.push(new VideoPlaylist(playlistJSON, translations))
+ }
+
+ return { data: playlists, total }
+ })
+ )
}
extractPlaylist (playlist: VideoPlaylistServerModel) {
return this.serverService.getServerLocale()
- .pipe(map(translations => new VideoPlaylist(playlist, translations)))
+ .pipe(map(translations => new VideoPlaylist(playlist, translations)))
}
extractVideoPlaylistElements (result: ResultList<ServerVideoPlaylistElement>) {
return this.serverService.getServerLocale()
- .pipe(
- map(translations => {
- const elementsJson = result.data
- const total = result.total
- const elements: VideoPlaylistElement[] = []
-
- for (const elementJson of elementsJson) {
- elements.push(new VideoPlaylistElement(elementJson, translations))
- }
-
- return { total, data: elements }
- })
- )
+ .pipe(
+ map(translations => {
+ const elementsJson = result.data
+ const total = result.total
+ const elements: VideoPlaylistElement[] = []
+
+ for (const elementJson of elementsJson) {
+ elements.push(new VideoPlaylistElement(elementJson, translations))
+ }
+
+ return { total, data: elements }
+ })
+ )
}
doVideosExistInPlaylist (videoIds: number[]): Observable<VideosExistInPlaylists> {
@@ -366,6 +365,6 @@ export class VideoPlaylistService {
params = this.restService.addObjectParams(params, { videoIds })
return this.authHttp.get<VideoExistInPlaylist>(url, { params, context: new HttpContext().set(NGX_LOADING_BAR_IGNORED, true) })
- .pipe(catchError(err => this.restExtractor.handleError(err)))
+ .pipe(catchError(err => this.restExtractor.handleError(err)))
}
}
diff --git a/client/src/app/shared/shared-video/video-views-counter.component.html b/client/src/app/shared/shared-video/video-views-counter.component.html
index e26ffa04d7..2facf2d495 100644
--- a/client/src/app/shared/shared-video/video-views-counter.component.html
+++ b/client/src/app/shared/shared-video/video-views-counter.component.html
@@ -1,11 +1,11 @@
<span [title]="getExactNumberOfViews()">
- @if (isLive) {
+ @if (isLive()) {
<ng-container i18n>
- {viewers, plural, =1 {1 viewer} other {{{ viewers | myNumberFormatter }} viewers}}
+ {viewers(), plural, =1 {1 viewer} other {{{ viewers() | myNumberFormatter }} viewers}}
</ng-container>
} @else {
<ng-container i18n>
- {views, plural, =1 {1 view} other {{{ views | myNumberFormatter }} views}}
+ {views(), plural, =1 {1 view} other {{{ views() | myNumberFormatter }} views}}
</ng-container>
}
</span>
diff --git a/client/src/app/shared/shared-video/video-views-counter.component.ts b/client/src/app/shared/shared-video/video-views-counter.component.ts
index 5afaef1994..d25d1f91e1 100644
--- a/client/src/app/shared/shared-video/video-views-counter.component.ts
+++ b/client/src/app/shared/shared-video/video-views-counter.component.ts
@@ -1,4 +1,4 @@
-import { booleanAttribute, ChangeDetectionStrategy, Component, Input } from '@angular/core'
+import { booleanAttribute, ChangeDetectionStrategy, Component, input } from '@angular/core'
import { formatICU } from '@app/helpers'
import { NumberFormatterPipe } from '../shared-main/common/number-formatter.pipe'
@@ -10,15 +10,15 @@ import { NumberFormatterPipe } from '../shared-main/common/number-formatter.pipe
imports: [ NumberFormatterPipe ]
})
export class VideoViewsCounterComponent {
- @Input({ required: true, transform: booleanAttribute }) isLive: boolean
- @Input({ required: true }) viewers: number
- @Input({ required: true }) views: number
+ readonly isLive = input.required<boolean, unknown>({ transform: booleanAttribute })
+ readonly viewers = input.required<number>()
+ readonly views = input.required<number>()
getExactNumberOfViews () {
- if (this.isLive) {
- return formatICU($localize`{viewers, plural, =0 {No viewers} =1 {1 viewer} other {{viewers} viewers}}`, { viewers: this.viewers })
+ if (this.isLive()) {
+ return formatICU($localize`{viewers, plural, =0 {No viewers} =1 {1 viewer} other {{viewers} viewers}}`, { viewers: this.viewers() })
}
- return formatICU($localize`{views, plural, =0 {No view} =1 {1 view} other {{views} views}}`, { views: this.views })
+ return formatICU($localize`{views, plural, =0 {No view} =1 {1 view} other {{views} views}}`, { views: this.views() })
}
}
diff --git a/client/src/app/shared/standalone-actor/actor-host.component.html b/client/src/app/shared/standalone-actor/actor-host.component.html
index 45067b9d46..54b9597f6f 100644
--- a/client/src/app/shared/standalone-actor/actor-host.component.html
+++ b/client/src/app/shared/standalone-actor/actor-host.component.html
@@ -7,7 +7,7 @@
<path d="M0 19V0L7.45757 8.85586C7.77102 9.22809 7.77102 9.77191 7.45757 10.1441L0 19Z"/>
</svg>
- {{ host }}
+ {{ host() }}
<svg class="right" width="9" height="19" viewBox="0 0 9 19" xmlns="http://www.w3.org/2000/svg">
<path d="m 8.0900763,0 h -7.08835 C 0.19446632,0 -0.28009268,0.907181 0.18029632,1.5703 L 5.4485063,9.15841 c 0.24316,0.35023 0.23751,0.81611 -0.01406,1.16039 L 0.25209632,17.41 c -0.482855,0.6607 -0.01097,1.59 0.80737998,1.59 h 7.0306 z"/>
@@ -18,11 +18,11 @@
<strong class="question mb-3" i18n>What is it?</strong>
<div class="answer mb-3">
- This video comes from <a [href]="'https://' + host" target="_blank" rel="noopener noreferrer">{{ host }} <my-global-icon iconName="external-link"></my-global-icon></a> platform, to which we have subscribed.
+ This video comes from <a [href]="'https://' + host()" target="_blank" rel="noopener noreferrer">{{ host() }} <my-global-icon iconName="external-link"></my-global-icon></a> platform, to which we have subscribed.
</div>
<a i18n class="mt-3 mb-3 d-block peertube-button-link secondary-button" routerLink="/about/follows">Show all our subscriptions</a>
- <my-button i18n class="d-block" theme="primary" ptRouterLink="/search" [ptQueryParams]="{ 'host': host }">More {{ host }} content</my-button>
+ <my-button i18n class="d-block" theme="primary" ptRouterLink="/search" [ptQueryParams]="{ 'host': host() }">More {{ host() }} content</my-button>
</div>
</div>
diff --git a/client/src/app/shared/standalone-actor/actor-host.component.ts b/client/src/app/shared/standalone-actor/actor-host.component.ts
index 1a1fd51409..7afab70f56 100644
--- a/client/src/app/shared/standalone-actor/actor-host.component.ts
+++ b/client/src/app/shared/standalone-actor/actor-host.component.ts
@@ -1,5 +1,5 @@
import { CommonModule } from '@angular/common'
-import { Component, Input, OnChanges } from '@angular/core'
+import { Component, OnChanges, input } from '@angular/core'
import { RouterLink } from '@angular/router'
import { NgbDropdownModule } from '@ng-bootstrap/ng-bootstrap'
import { GlobalIconComponent } from '../shared-icons/global-icon.component'
@@ -12,11 +12,11 @@ import { ButtonComponent } from '../shared-main/buttons/button.component'
imports: [ CommonModule, NgbDropdownModule, GlobalIconComponent, ButtonComponent, RouterLink ]
})
export class ActorHostComponent implements OnChanges {
- @Input({ required: true }) host: string
+ readonly host = input.required<string>()
title: string
ngOnChanges () {
- this.title = $localize`Get more information on ${this.host}`
+ this.title = $localize`Get more information on ${this.host()}`
}
}
diff --git a/client/src/app/shared/standalone-channels/video-channel-create.component.ts b/client/src/app/shared/standalone-channels/video-channel-create.component.ts
index 25e7268e1d..d5f234f799 100644
--- a/client/src/app/shared/standalone-channels/video-channel-create.component.ts
+++ b/client/src/app/shared/standalone-channels/video-channel-create.component.ts
@@ -1,5 +1,5 @@
import { NgClass, NgIf } from '@angular/common'
-import { AfterViewInit, Component, OnInit } from '@angular/core'
+import { AfterViewInit, Component, OnInit, inject } from '@angular/core'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { Router } from '@angular/router'
import { AuthService, HooksService, Notifier } from '@app/core'
@@ -40,23 +40,19 @@ import { VideoChannelEdit } from './video-channel-edit'
]
})
export class VideoChannelCreateComponent extends VideoChannelEdit implements OnInit, AfterViewInit {
+ protected formReactiveService = inject(FormReactiveService)
+ private authService = inject(AuthService)
+ private notifier = inject(Notifier)
+ private router = inject(Router)
+ private videoChannelService = inject(VideoChannelService)
+ private hooks = inject(HooksService)
+
error: string
videoChannel = new VideoChannel({})
private avatar: FormData
private banner: FormData
- constructor (
- protected formReactiveService: FormReactiveService,
- private authService: AuthService,
- private notifier: Notifier,
- private router: Router,
- private videoChannelService: VideoChannelService,
- private hooks: HooksService
- ) {
- super()
- }
-
ngOnInit () {
this.buildForm({
'name': VIDEO_CHANNEL_NAME_VALIDATOR,
diff --git a/client/src/app/shared/standalone-channels/video-channel-update.component.ts b/client/src/app/shared/standalone-channels/video-channel-update.component.ts
index 24d9a55e22..a903d12fa7 100644
--- a/client/src/app/shared/standalone-channels/video-channel-update.component.ts
+++ b/client/src/app/shared/standalone-channels/video-channel-update.component.ts
@@ -1,6 +1,6 @@
import { NgClass, NgIf } from '@angular/common'
import { HttpErrorResponse } from '@angular/common/http'
-import { AfterViewInit, Component, OnDestroy, OnInit } from '@angular/core'
+import { AfterViewInit, Component, OnDestroy, OnInit, inject } from '@angular/core'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { ActivatedRoute } from '@angular/router'
import { AuthService, HooksService, Notifier, RedirectService } from '@app/core'
@@ -41,23 +41,19 @@ import { VideoChannelEdit } from './video-channel-edit'
]
})
export class VideoChannelUpdateComponent extends VideoChannelEdit implements OnInit, AfterViewInit, OnDestroy {
+ protected formReactiveService = inject(FormReactiveService)
+ private authService = inject(AuthService)
+ private notifier = inject(Notifier)
+ private route = inject(ActivatedRoute)
+ private videoChannelService = inject(VideoChannelService)
+ private redirectService = inject(RedirectService)
+ private hooks = inject(HooksService)
+
error: string
private paramsSub: Subscription
private oldSupportField: string
- constructor (
- protected formReactiveService: FormReactiveService,
- private authService: AuthService,
- private notifier: Notifier,
- private route: ActivatedRoute,
- private videoChannelService: VideoChannelService,
- private redirectService: RedirectService,
- private hooks: HooksService
- ) {
- super()
- }
-
ngOnInit () {
this.buildForm({
'display-name': VIDEO_CHANNEL_DISPLAY_NAME_VALIDATOR,
@@ -129,68 +125,70 @@ export class VideoChannelUpdateComponent extends VideoChannelEdit implements OnI
onAvatarChange (formData: FormData) {
this.videoChannelService.changeVideoChannelImage(this.videoChannel.name, formData, 'avatar')
- .subscribe({
- next: data => {
- this.notifier.success($localize`Avatar changed.`)
+ .subscribe({
+ next: data => {
+ this.notifier.success($localize`Avatar changed.`)
- this.videoChannel.updateAvatar(data.avatars)
+ this.videoChannel.updateAvatar(data.avatars)
- // So my-actor-avatar component detects changes
- this.videoChannel = shallowCopy(this.videoChannel)
- },
+ // So my-actor-avatar component detects changes
+ this.videoChannel = shallowCopy(this.videoChannel)
+ },
- error: (err: HttpErrorResponse) => genericUploadErrorHandler({
+ error: (err: HttpErrorResponse) =>
+ genericUploadErrorHandler({
err,
name: $localize`avatar`,
notifier: this.notifier
})
- })
+ })
}
onAvatarDelete () {
this.videoChannelService.deleteVideoChannelImage(this.videoChannel.name, 'avatar')
- .subscribe({
- next: () => {
- this.notifier.success($localize`Avatar deleted.`)
+ .subscribe({
+ next: () => {
+ this.notifier.success($localize`Avatar deleted.`)
- this.videoChannel.resetAvatar()
+ this.videoChannel.resetAvatar()
- // So my-actor-avatar component detects changes
- this.videoChannel = shallowCopy(this.videoChannel)
- },
+ // So my-actor-avatar component detects changes
+ this.videoChannel = shallowCopy(this.videoChannel)
+ },
- error: err => this.notifier.error(err.message)
- })
+ error: err => this.notifier.error(err.message)
+ })
}
onBannerChange (formData: FormData) {
this.videoChannelService.changeVideoChannelImage(this.videoChannel.name, formData, 'banner')
- .subscribe({
- next: data => {
- this.notifier.success($localize`Banner changed.`)
+ .subscribe({
+ next: data => {
+ this.notifier.success($localize`Banner changed.`)
- this.videoChannel.updateBanner(data.banners)
- },
+ this.videoChannel.updateBanner(data.banners)
+ },
- error: (err: HttpErrorResponse) => genericUploadErrorHandler({
+ error: (err: HttpErrorResponse) =>
+ genericUploadErrorHandler({
err,
name: $localize`banner`,
notifier: this.notifier
})
- })
+ })
}
onBannerDelete () {
this.videoChannelService.deleteVideoChannelImage(this.videoChannel.name, 'banner')
- .subscribe({
- next: () => {
- this.notifier.success($localize`Banner deleted.`)
+ .subscribe({
+ next: () => {
+ this.notifier.success($localize`Banner deleted.`)
- this.videoChannel.resetBanner()
- },
+ this.videoChannel.resetBanner()
+ },
- error: err => this.notifier.error(err.message)
- })
+ error: err => this.notifier.error(err.message)
+ })
}
isCreation () {
diff --git a/client/src/app/shared/standalone-notifications/user-notifications.component.ts b/client/src/app/shared/standalone-notifications/user-notifications.component.ts
index 2c0019621d..2c4691236e 100644
--- a/client/src/app/shared/standalone-notifications/user-notifications.component.ts
+++ b/client/src/app/shared/standalone-notifications/user-notifications.component.ts
@@ -1,5 +1,5 @@
import { Subject } from 'rxjs'
-import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'
+import { Component, OnInit, inject, input, output } from '@angular/core'
import { ComponentPagination, hasMoreItems, Notifier } from '@app/core'
import { AbuseState, VideoState } from '@peertube/peertube-models'
import { CommonModule } from '@angular/common'
@@ -17,13 +17,16 @@ import { UserNotification } from '../shared-main/users/user-notification.model'
imports: [ CommonModule, GlobalIconComponent, RouterLink, FromNowPipe, InfiniteScrollerDirective ]
})
export class UserNotificationsComponent implements OnInit {
- @Input() ignoreLoadingBar = false
- @Input() infiniteScroll = true
- @Input() itemsPerPage = 20
- @Input() markAllAsReadSubject: Subject<boolean>
- @Input() userNotificationReload: Subject<boolean>
+ private userNotificationService = inject(UserNotificationService)
+ private notifier = inject(Notifier)
- @Output() notificationsLoaded = new EventEmitter()
+ readonly ignoreLoadingBar = input(false)
+ readonly infiniteScroll = input(true)
+ readonly itemsPerPage = input(20)
+ readonly markAllAsReadSubject = input<Subject<boolean>>(undefined)
+ readonly userNotificationReload = input<Subject<boolean>>(undefined)
+
+ readonly notificationsLoaded = output()
notifications: UserNotification[] = []
sortField = 'createdAt'
@@ -32,26 +35,23 @@ export class UserNotificationsComponent implements OnInit {
onDataSubject = new Subject<any[]>()
- constructor (
- private userNotificationService: UserNotificationService,
- private notifier: Notifier
- ) { }
-
ngOnInit () {
this.componentPagination = {
currentPage: 1,
- itemsPerPage: this.itemsPerPage, // Reset items per page, because of the @Input() variable
+ itemsPerPage: this.itemsPerPage(), // Reset items per page, because of the @Input() variable
totalItems: null
}
this.loadNotifications()
- if (this.markAllAsReadSubject) {
- this.markAllAsReadSubject.subscribe(() => this.markAllAsRead())
+ const markAllAsReadSubject = this.markAllAsReadSubject()
+ if (markAllAsReadSubject) {
+ markAllAsReadSubject.subscribe(() => this.markAllAsRead())
}
- if (this.userNotificationReload) {
- this.userNotificationReload.subscribe(() => this.loadNotifications(true))
+ const userNotificationReload = this.userNotificationReload()
+ if (userNotificationReload) {
+ userNotificationReload.subscribe(() => this.loadNotifications(true))
}
}
@@ -60,7 +60,7 @@ export class UserNotificationsComponent implements OnInit {
const options = {
pagination: this.componentPagination,
- ignoreLoadingBar: this.ignoreLoadingBar,
+ ignoreLoadingBar: this.ignoreLoadingBar(),
sort: {
field: this.sortField,
// if we order by creation date, we want DESC. all other fields are ASC (like unread).
@@ -69,22 +69,22 @@ export class UserNotificationsComponent implements OnInit {
}
this.userNotificationService.listMyNotifications(options)
- .subscribe({
- next: result => {
- this.notifications = reset ? result.data : this.notifications.concat(result.data)
- this.componentPagination.totalItems = result.total
+ .subscribe({
+ next: result => {
+ this.notifications = reset ? result.data : this.notifications.concat(result.data)
+ this.componentPagination.totalItems = result.total
- this.notificationsLoaded.emit()
+ this.notificationsLoaded.emit()
- this.onDataSubject.next(result.data)
- },
+ this.onDataSubject.next(result.data)
+ },
- error: err => this.notifier.error(err.message)
- })
+ error: err => this.notifier.error(err.message)
+ })
}
onNearOfBottom () {
- if (this.infiniteScroll === false) return
+ if (this.infiniteScroll() === false) return
this.componentPagination.currentPage++
@@ -97,32 +97,32 @@ export class UserNotificationsComponent implements OnInit {
if (notification.read) return
this.userNotificationService.markAsRead(notification)
- .subscribe({
- next: () => {
- notification.read = true
- },
+ .subscribe({
+ next: () => {
+ notification.read = true
+ },
- error: err => this.notifier.error(err.message)
- })
+ error: err => this.notifier.error(err.message)
+ })
}
markAllAsRead () {
this.userNotificationService.markAllAsRead()
- .subscribe({
- next: () => {
- for (const notification of this.notifications) {
- notification.read = true
- }
- },
-
- error: err => this.notifier.error(err.message)
- })
+ .subscribe({
+ next: () => {
+ for (const notification of this.notifications) {
+ notification.read = true
+ }
+ },
+
+ error: err => this.notifier.error(err.message)
+ })
}
changeSortColumn (column: string) {
this.componentPagination = {
currentPage: 1,
- itemsPerPage: this.itemsPerPage,
+ itemsPerPage: this.itemsPerPage(),
totalItems: null
}
this.sortField = column
diff --git a/client/src/app/shared/standalone-upload/upload-progress.component.html b/client/src/app/shared/standalone-upload/upload-progress.component.html
index 4a54fdfdf0..007cbc9ad9 100644
--- a/client/src/app/shared/standalone-upload/upload-progress.component.html
+++ b/client/src/app/shared/standalone-upload/upload-progress.component.html
@@ -1,20 +1,20 @@
<!-- Upload progress/cancel/error/success header -->
-<div *ngIf="isUploading && !error" class="upload-progress-cancel">
+<div *ngIf="isUploading() && !error()" class="upload-progress-cancel">
<my-progress-bar
i18n-label label="Total uploaded" theme="green"
- [value]="uploadPercents" [valueFormatted]="getUploadingLabel()"
+ [value]="uploadPercents()" [valueFormatted]="getUploadingLabel()"
>
</my-progress-bar>
<input
- *ngIf="uploaded === false"
+ *ngIf="uploaded() === false"
type="button" class="peertube-button secondary-button ms-1" i18n-value="Cancel ongoing upload" value="Cancel" (click)="cancelUpload.emit()"
/>
</div>
-<div *ngIf="error && enableRetryAfterError" class="upload-progress-retry">
+<div *ngIf="error() && enableRetryAfterError()" class="upload-progress-retry">
<my-progress-bar
- [label]="error" value="100" [valueFormatted]="error"
+ [label]="error()" value="100" [valueFormatted]="error()"
theme="red"
>
</my-progress-bar>
@@ -23,7 +23,7 @@
<input type="button" class="peertube-button secondary-button ms-1" i18n-value="Cancel ongoing upload" value="Cancel" (click)="cancelUpload.emit()" />
</div>
-<my-alert *ngIf="error && !enableRetryAfterError" type="danger">
+<my-alert *ngIf="error() && !enableRetryAfterError()" type="danger">
<div i18n>Sorry, but something went wrong</div>
- {{ error }}
+ {{ error() }}
</my-alert>
diff --git a/client/src/app/shared/standalone-upload/upload-progress.component.ts b/client/src/app/shared/standalone-upload/upload-progress.component.ts
index 7122162d54..40c4ddbf2b 100644
--- a/client/src/app/shared/standalone-upload/upload-progress.component.ts
+++ b/client/src/app/shared/standalone-upload/upload-progress.component.ts
@@ -1,5 +1,5 @@
import { CommonModule } from '@angular/common'
-import { Component, EventEmitter, Input, Output } from '@angular/core'
+import { Component, input, output } from '@angular/core'
import { AlertComponent } from '../shared-main/common/alert.component'
import { ProgressBarComponent } from '../shared-main/common/progress-bar.component'
@@ -10,20 +10,21 @@ import { ProgressBarComponent } from '../shared-main/common/progress-bar.compone
imports: [ CommonModule, ProgressBarComponent, AlertComponent ]
})
export class UploadProgressComponent {
- @Input() isUploading: boolean
- @Input() uploadPercents: number
- @Input() error: string
- @Input() uploaded: boolean
- @Input() enableRetryAfterError: boolean
+ readonly isUploading = input<boolean>(undefined)
+ readonly uploadPercents = input<number>(undefined)
+ readonly error = input<string>(undefined)
+ readonly uploaded = input<boolean>(undefined)
+ readonly enableRetryAfterError = input<boolean>(undefined)
- @Output() cancelUpload = new EventEmitter()
- @Output() retry = new EventEmitter()
+ readonly cancelUpload = output()
+ readonly retry = output()
getUploadingLabel () {
- if (this.uploadPercents === 100 && this.uploaded === false) {
+ const uploadPercents = this.uploadPercents()
+ if (uploadPercents === 100 && this.uploaded() === false) {
return $localize`Processing…`
}
- return $localize`${this.uploadPercents}%`
+ return $localize`${uploadPercents}%`
}
}
diff --git a/client/src/app/shared/standalone-watched-words/watched-words-list-admin-owner.component.ts b/client/src/app/shared/standalone-watched-words/watched-words-list-admin-owner.component.ts
index 8184e76cff..bf85140899 100644
--- a/client/src/app/shared/standalone-watched-words/watched-words-list-admin-owner.component.ts
+++ b/client/src/app/shared/standalone-watched-words/watched-words-list-admin-owner.component.ts
@@ -1,5 +1,5 @@
import { NgClass, NgIf } from '@angular/common'
-import { Component, Input, OnInit, ViewChild } from '@angular/core'
+import { Component, OnInit, inject, input, viewChild } from '@angular/core'
import { ActivatedRoute, Router } from '@angular/router'
import { AuthService, ConfirmService, Notifier, RestPagination, RestTable } from '@app/core'
import { NgbTooltip } from '@ng-bootstrap/ng-bootstrap'
@@ -35,9 +35,16 @@ import { WatchedWordsListService } from './watched-words-list.service'
]
})
export class WatchedWordsListAdminOwnerComponent extends RestTable<WatchedWordsList> implements OnInit {
- @Input({ required: true }) mode: 'user' | 'admin'
+ protected router = inject(Router)
+ protected route = inject(ActivatedRoute)
+ private auth = inject(AuthService)
+ private notifier = inject(Notifier)
+ private confirmService = inject(ConfirmService)
+ private watchedWordsListService = inject(WatchedWordsListService)
- @ViewChild('saveModal', { static: true }) saveModal: WatchedWordsListSaveModalComponent
+ readonly mode = input.required<'user' | 'admin'>()
+
+ readonly saveModal = viewChild<WatchedWordsListSaveModalComponent>('saveModal')
lists: WatchedWordsList[]
totalRecords = 0
@@ -51,22 +58,15 @@ export class WatchedWordsListAdminOwnerComponent extends RestTable<WatchedWordsL
}
get accountNameParam () {
- if (this.mode === 'admin') return undefined
+ if (this.mode() === 'admin') return undefined
return this.authUser.account.name
}
- constructor (
- protected router: Router,
- protected route: ActivatedRoute,
- private auth: AuthService,
- private notifier: Notifier,
- private confirmService: ConfirmService,
- private watchedWordsListService: WatchedWordsListService
- ) {
+ constructor () {
super()
- const isDisplayed = () => this.mode === 'user' || this.authUser.hasRight(UserRight.MANAGE_INSTANCE_WATCHED_WORDS)
+ const isDisplayed = () => this.mode() === 'user' || this.authUser.hasRight(UserRight.MANAGE_INSTANCE_WATCHED_WORDS)
this.actions = [
[
@@ -101,7 +101,7 @@ export class WatchedWordsListAdminOwnerComponent extends RestTable<WatchedWordsL
}
openCreateOrUpdateList (list?: WatchedWordsList) {
- this.saveModal.show(list)
+ this.saveModal().show(list)
}
protected reloadDataInternal () {
@@ -134,5 +134,4 @@ export class WatchedWordsListAdminOwnerComponent extends RestTable<WatchedWordsL
error: err => this.notifier.error(err.message)
})
}
-
}
diff --git a/client/src/app/shared/standalone-watched-words/watched-words-list-save-modal.component.ts b/client/src/app/shared/standalone-watched-words/watched-words-list-save-modal.component.ts
index 2965573ebd..b3b9eb06b8 100644
--- a/client/src/app/shared/standalone-watched-words/watched-words-list-save-modal.component.ts
+++ b/client/src/app/shared/standalone-watched-words/watched-words-list-save-modal.component.ts
@@ -1,5 +1,5 @@
import { NgClass, NgIf } from '@angular/common'
-import { Component, ElementRef, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core'
+import { Component, ElementRef, OnInit, inject, input, output, viewChild } from '@angular/core'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { Notifier } from '@app/core'
import { FormReactive } from '@app/shared/shared-forms/form-reactive'
@@ -17,26 +17,21 @@ import { WatchedWordsListService } from './watched-words-list.service'
templateUrl: './watched-words-list-save-modal.component.html',
imports: [ FormsModule, ReactiveFormsModule, GlobalIconComponent, NgIf, NgClass ]
})
-
export class WatchedWordsListSaveModalComponent extends FormReactive implements OnInit {
- @Input({ required: true }) accountName: string
+ protected formReactiveService = inject(FormReactiveService)
+ private modalService = inject(NgbModal)
+ private notifier = inject(Notifier)
+ private watchedWordsService = inject(WatchedWordsListService)
+
+ readonly accountName = input.required<string>()
- @Output() listAddedOrUpdated = new EventEmitter<void>()
+ readonly listAddedOrUpdated = output()
- @ViewChild('modal', { static: true }) modal: ElementRef
+ readonly modal = viewChild<ElementRef>('modal')
private openedModal: NgbModalRef
private listToUpdate: WatchedWordsList
- constructor (
- protected formReactiveService: FormReactiveService,
- private modalService: NgbModal,
- private notifier: Notifier,
- private watchedWordsService: WatchedWordsListService
- ) {
- super()
- }
-
ngOnInit () {
this.buildForm({
listName: WATCHED_WORDS_LIST_NAME_VALIDATOR,
@@ -47,7 +42,7 @@ export class WatchedWordsListSaveModalComponent extends FormReactive implements
show (list?: WatchedWordsList) {
this.listToUpdate = list
- this.openedModal = this.modalService.open(this.modal, { centered: true, keyboard: false })
+ this.openedModal = this.modalService.open(this.modal(), { centered: true, keyboard: false })
if (list) {
this.form.patchValue({
@@ -66,7 +61,7 @@ export class WatchedWordsListSaveModalComponent extends FormReactive implements
addOrUpdate () {
const commonParams = {
- accountName: this.accountName,
+ accountName: this.accountName(),
listName: this.form.value['listName'],
words: splitAndGetNotEmpty(this.form.value['words'])
}
diff --git a/client/src/app/shared/standalone-watched-words/watched-words-list.service.ts b/client/src/app/shared/standalone-watched-words/watched-words-list.service.ts
index baf263e46b..a10d66cdcf 100644
--- a/client/src/app/shared/standalone-watched-words/watched-words-list.service.ts
+++ b/client/src/app/shared/standalone-watched-words/watched-words-list.service.ts
@@ -1,5 +1,5 @@
import { HttpClient, HttpParams } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+import { Injectable, inject } from '@angular/core'
import { RestExtractor, RestPagination, RestService } from '@app/core'
import { ResultList, WatchedWordsList } from '@peertube/peertube-models'
import { SortMeta } from 'primeng/api'
@@ -9,13 +9,11 @@ import { environment } from '../../../environments/environment'
@Injectable()
export class WatchedWordsListService {
- private static BASE_WATCHED_WORDS_URL = environment.apiUrl + '/api/v1/watched-words/'
+ private authHttp = inject(HttpClient)
+ private restExtractor = inject(RestExtractor)
+ private restService = inject(RestService)
- constructor (
- private authHttp: HttpClient,
- private restExtractor: RestExtractor,
- private restService: RestService
- ) {}
+ private static BASE_WATCHED_WORDS_URL = environment.apiUrl + '/api/v1/watched-words/'
list (options: {
accountName?: string