Adrià Vilanova Martínez | 18d03c4 | 2024-04-21 16:43:01 +0200 | [diff] [blame] | 1 | import Feature from '../common/architecture/features/Feature'; |
| 2 | import { |
| 3 | ScriptEnvironment, |
| 4 | ScriptPage, |
| 5 | ScriptRunPhase, |
| 6 | } from '../common/architecture/scripts/Script'; |
Adrià Vilanova Martínez | 58cc67c | 2024-04-21 16:43:01 +0200 | [diff] [blame^] | 7 | import AutoRefreshFeature from './autoRefresh/autoRefresh.feature'; |
Adrià Vilanova Martínez | 18d03c4 | 2024-04-21 16:43:01 +0200 | [diff] [blame] | 8 | import InfiniteScrollFeature from './infiniteScroll/infiniteScroll.feature'; |
| 9 | |
| 10 | export type ConcreteFeatureClass = { new (): Feature }; |
| 11 | |
| 12 | export interface Context { |
| 13 | page: ScriptPage; |
| 14 | environment: ScriptEnvironment; |
| 15 | runPhase: ScriptRunPhase; |
| 16 | } |
| 17 | |
| 18 | export default class Features { |
Adrià Vilanova Martínez | 58cc67c | 2024-04-21 16:43:01 +0200 | [diff] [blame^] | 19 | private features: ConcreteFeatureClass[] = [ |
| 20 | AutoRefreshFeature, |
| 21 | InfiniteScrollFeature, |
| 22 | ]; |
Adrià Vilanova Martínez | 18d03c4 | 2024-04-21 16:43:01 +0200 | [diff] [blame] | 23 | private initializedFeatures: Feature[]; |
| 24 | |
| 25 | runScripts(context: Context) { |
| 26 | const scripts = this.getScripts(context).sort((a, b) => |
| 27 | a.priority < b.priority ? -1 : 1, |
| 28 | ); |
| 29 | for (const script of scripts) { |
| 30 | script.execute(); |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | getScripts(context: Context) { |
| 35 | const features = this.getFeatures(); |
| 36 | const allScripts = features.map((feature) => feature.getScripts()).flat(1); |
| 37 | return allScripts.filter( |
| 38 | (script) => |
| 39 | script.page === context.page && |
| 40 | script.environment === context.environment && |
| 41 | script.runPhase === context.runPhase, |
| 42 | ); |
| 43 | } |
| 44 | |
| 45 | private getFeatures() { |
| 46 | if (this.initializedFeatures === undefined) { |
| 47 | this.initializedFeatures = this.features.map((feature) => new feature()); |
| 48 | } |
| 49 | return this.initializedFeatures; |
| 50 | } |
| 51 | } |