|
1 | | -import {useProjectContext} from '$lib/project-context.svelte'; |
| 1 | +import type {IPublication} from '$lib/dotnet-types'; |
| 2 | +import {useWritingSystemService, type WritingSystemService} from './writing-system-service.svelte'; |
| 3 | +import {type ProjectContext, useProjectContext} from '$lib/project-context.svelte'; |
| 4 | +import {type ResourceReturn} from 'runed'; |
2 | 5 |
|
3 | | -const publicationsSymbol = Symbol.for('fw-lite-publications'); |
4 | | -export function usePublications() { |
| 6 | +type LabeledPublication = IPublication & { label: string }; |
| 7 | + |
| 8 | +const symbol = Symbol.for('fw-lite-publications'); |
| 9 | +export function usePublications(): PublicationService { |
5 | 10 | const projectContext = useProjectContext(); |
6 | | - return projectContext.getOrAddAsync(publicationsSymbol, [], async (api) => { |
7 | | - const publications = await api.getPublications(); |
8 | | - return publications.sort((a, b) => { |
9 | | - const aName = Object.values(a.name)[0] || ''; |
10 | | - const bName = Object.values(b.name)[0] || ''; |
11 | | - return aName.localeCompare(bName); |
12 | | - }); |
| 11 | + const writingSystemService = useWritingSystemService(); |
| 12 | + return projectContext.getOrAdd(symbol, () => { |
| 13 | + return new PublicationService(projectContext, writingSystemService); |
| 14 | + }); |
| 15 | +} |
| 16 | + |
| 17 | +export class PublicationService { |
| 18 | + constructor(projectContext: ProjectContext, private writingSystemService: WritingSystemService) { |
| 19 | + this.#publicationsResource = projectContext.apiResource([], api => api.getPublications()); |
| 20 | + } |
| 21 | + |
| 22 | + #publicationsResource: ResourceReturn<IPublication[], unknown, true>; |
| 23 | + |
| 24 | + current: LabeledPublication[] = $derived.by(() => { |
| 25 | + return this.#publicationsResource.current.map(pub => ({ |
| 26 | + ...pub, |
| 27 | + label: this.getLabel(pub), |
| 28 | + })).sort((a, b) => a.label.localeCompare(b.label)); |
13 | 29 | }); |
| 30 | + |
| 31 | + async refetch() { |
| 32 | + await this.#publicationsResource.refetch(); |
| 33 | + return this.current; |
| 34 | + } |
| 35 | + |
| 36 | + getLabel(pub: IPublication): string { |
| 37 | + return this.writingSystemService.pickBestAlternative(pub.name, 'analysis'); |
| 38 | + } |
14 | 39 | } |
0 commit comments