add logic

This commit is contained in:
2026-10-07 17:32:25 +03:00
parent cdcdd22526
commit f86777e2cd
69 changed files with 1519 additions and 637 deletions
+5
View File
@@ -3,5 +3,10 @@
"target": "https://gorodar.ru", "target": "https://gorodar.ru",
"secure": true, "secure": true,
"changeOrigin": true "changeOrigin": true
},
"/api": {
"target": "https://gorodar.ru",
"secure": true,
"changeOrigin": true
} }
} }
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.6 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 MiB

Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 19 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 16 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 13 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 172 KiB

+4
View File
@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 112 112" fill="none">
<circle cx="56" cy="56" r="52" fill="#F0876A"/>
<path d="M40 40 L72 72 M72 40 L40 72" stroke="#1A1508" stroke-width="7" stroke-linecap="round"/>
</svg>

After

Width:  |  Height:  |  Size: 231 B

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="390" height="320" viewBox="0 0 390 320"><defs><linearGradient id="nn1" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#161B38"></stop><stop offset="0.55" stop-color="#4A3A63"></stop><stop offset="1" stop-color="#C9764C"></stop></linearGradient></defs><rect width="390" height="320" fill="url(#nn1)"></rect><circle cx="46.8" cy="20.5" r="1.1" fill="#FFFFFF" opacity="0.65"></circle><circle cx="117.0" cy="35.8" r="1.1" fill="#FFFFFF" opacity="0.65"></circle><circle cx="280.8" cy="17.9" r="1.1" fill="#FFFFFF" opacity="0.65"></circle><circle cx="335.4" cy="43.5" r="1.1" fill="#FFFFFF" opacity="0.65"></circle><circle cx="78.0" cy="66.6" r="1.1" fill="#FFFFFF" opacity="0.65"></circle><circle cx="358.8" cy="76.8" r="1.1" fill="#FFFFFF" opacity="0.65"></circle><circle cx="31.2" cy="92.2" r="1.1" fill="#FFFFFF" opacity="0.65"></circle><circle cx="304.2" cy="102.4" r="1.1" fill="#FFFFFF" opacity="0.65"></circle><rect x="113.8" y="203.4" width="162.4" height="98.6" fill="#0C0B0A"></rect><rect x="73.2" y="244.0" width="40.6" height="58.0" fill="#0C0B0A"></rect><rect x="276.2" y="244.0" width="40.6" height="58.0" fill="#0C0B0A"></rect><rect x="166.0" y="168.6" width="58.0" height="34.8" fill="#0C0B0A"></rect><path d="M160.2 168.6 C144.9 143.0 183.9 126.4 195.0 93.2 C206.1 126.4 245.1 143.0 229.8 168.6 Z" fill="#0C0B0A"></path><path d="M195.0 64.2 V93.2 M186.3 73.8 H203.7" stroke="#0C0B0A" stroke-width="2.9" fill="none"></path><path d="M76.1 244.0 C68.4 231.2 87.9 222.9 93.5 206.3 C99.1 222.9 118.6 231.2 110.9 244.0 Z" fill="#0C0B0A"></path><path d="M93.5 186.0 V206.3 M87.4 192.7 H99.6" stroke="#0C0B0A" stroke-width="2.0" fill="none"></path><path d="M279.1 244.0 C271.4 231.2 290.9 222.9 296.5 206.3 C302.1 222.9 321.6 231.2 313.9 244.0 Z" fill="#0C0B0A"></path><path d="M296.5 186.0 V206.3 M290.4 192.7 H302.6" stroke="#0C0B0A" stroke-width="2.0" fill="none"></path><ellipse cx="0.0" cy="318.0" rx="29.3" ry="14.4" fill="#0C0B0A"></ellipse><ellipse cx="48.8" cy="318.0" rx="29.3" ry="20.5" fill="#0C0B0A"></ellipse><ellipse cx="97.5" cy="318.0" rx="29.3" ry="26.4" fill="#0C0B0A"></ellipse><ellipse cx="146.2" cy="318.0" rx="29.3" ry="14.4" fill="#0C0B0A"></ellipse><ellipse cx="195.0" cy="318.0" rx="29.3" ry="20.5" fill="#0C0B0A"></ellipse><ellipse cx="243.8" cy="318.0" rx="29.3" ry="26.4" fill="#0C0B0A"></ellipse><ellipse cx="292.5" cy="318.0" rx="29.3" ry="14.4" fill="#0C0B0A"></ellipse><ellipse cx="341.2" cy="318.0" rx="29.3" ry="20.5" fill="#0C0B0A"></ellipse><ellipse cx="390.0" cy="318.0" rx="29.3" ry="26.4" fill="#0C0B0A"></ellipse><rect x="0" y="310.0" width="390" height="10" fill="#0C0B0A"></rect></svg>

Before

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+5 -4
View File
@@ -1,5 +1,5 @@
import { ApplicationConfig, isDevMode, provideBrowserGlobalErrorListeners, provideZoneChangeDetection } from '@angular/core'; import { ApplicationConfig, isDevMode, provideBrowserGlobalErrorListeners, provideZoneChangeDetection } from '@angular/core';
import { provideHttpClient } from '@angular/common/http'; import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { provideAnimationsAsync } from '@angular/platform-browser/animations/async'; import { provideAnimationsAsync } from '@angular/platform-browser/animations/async';
import { provideRouter, withComponentInputBinding } from '@angular/router'; import { provideRouter, withComponentInputBinding } from '@angular/router';
import { provideServiceWorker } from '@angular/service-worker'; import { provideServiceWorker } from '@angular/service-worker';
@@ -7,19 +7,20 @@ import { provideEffects } from '@ngrx/effects';
import { provideState, provideStore } from '@ngrx/store'; import { provideState, provideStore } from '@ngrx/store';
import { provideStoreDevtools } from '@ngrx/store-devtools'; import { provideStoreDevtools } from '@ngrx/store-devtools';
import { authInterceptor } from './auth/auth.interceptor';
import { routes } from './app.routes'; import { routes } from './app.routes';
import { AuthEffects, GorodarEffects, gorodarFeature } from './state'; import { AreasEffects, AuthEffects, GorodarEffects, gorodarFeature } from './state';
export const appConfig: ApplicationConfig = { export const appConfig: ApplicationConfig = {
providers: [ providers: [
provideBrowserGlobalErrorListeners(), provideBrowserGlobalErrorListeners(),
provideZoneChangeDetection({ eventCoalescing: true }), provideZoneChangeDetection({ eventCoalescing: true }),
provideHttpClient(), provideHttpClient(withInterceptors([authInterceptor])),
provideRouter(routes, withComponentInputBinding()), provideRouter(routes, withComponentInputBinding()),
provideAnimationsAsync(), provideAnimationsAsync(),
provideStore(), provideStore(),
provideState(gorodarFeature), provideState(gorodarFeature),
provideEffects(GorodarEffects, AuthEffects), provideEffects(GorodarEffects, AuthEffects, AreasEffects),
provideStoreDevtools({ maxAge: 25, logOnly: !isDevMode() }), provideStoreDevtools({ maxAge: 25, logOnly: !isDevMode() }),
provideServiceWorker('ngsw-worker.js', { provideServiceWorker('ngsw-worker.js', {
enabled: !isDevMode(), enabled: !isDevMode(),
+4 -5
View File
@@ -11,10 +11,9 @@ export const routes: Routes = [
{ path: '', component: CitiesPage }, { path: '', component: CitiesPage },
{ path: 'map', component: MapPage }, { path: 'map', component: MapPage },
{ path: 'collections', component: CollectionsPage }, { path: 'collections', component: CollectionsPage },
{ path: 'city', component: CityPage }, { path: 'collection', pathMatch: 'full', redirectTo: '' },
{ path: 'collection', pathMatch: 'full', redirectTo: '/city' }, { path: 'city/:areaId/:id/icon', component: IconPreviewPage },
{ path: 'city/:id/icon', component: IconPreviewPage }, { path: 'city/:areaId/:id', component: MapItemPage },
{ path: 'city/:id', component: MapItemPage }, { path: 'city/:areaId', component: CityPage },
{ path: 'objects/:id', redirectTo: 'city/:id' },
{ path: '**', redirectTo: '' }, { path: '**', redirectTo: '' },
]; ];
+10 -1
View File
@@ -2,9 +2,11 @@ import { Component, computed, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop'; import { toSignal } from '@angular/core/rxjs-interop';
import { NavigationEnd, Router, RouterOutlet } from '@angular/router'; import { NavigationEnd, Router, RouterOutlet } from '@angular/router';
import { filter, map, startWith } from 'rxjs'; import { filter, map, startWith } from 'rxjs';
import { Store } from '@ngrx/store';
import { AuthSheet } from './auth/ui/auth-sheet/auth-sheet'; import { AuthSheet } from './auth/ui/auth-sheet/auth-sheet';
import { BottomNav } from './layout/bottom-nav/bottom-nav'; import { BottomNav } from './layout/bottom-nav/bottom-nav';
import { GorodarActions } from './state';
@Component({ @Component({
selector: 'app-root', selector: 'app-root',
@@ -14,6 +16,11 @@ import { BottomNav } from './layout/bottom-nav/bottom-nav';
}) })
export class App { export class App {
private readonly router = inject(Router); private readonly router = inject(Router);
private readonly store = inject(Store);
constructor() {
this.store.dispatch(GorodarActions.areasRequested());
}
private readonly url = toSignal( private readonly url = toSignal(
this.router.events.pipe( this.router.events.pipe(
@@ -24,5 +31,7 @@ export class App {
{ initialValue: this.router.url }, { initialValue: this.router.url },
); );
protected readonly hideNav = computed(() => this.url().startsWith('/city/')); protected readonly hideNav = computed(() =>
/^\/city\/[^/]+\/[^/]+/.test(this.url().split('?')[0]),
);
} }
+100
View File
@@ -0,0 +1,100 @@
export interface Attraction {
id: string;
name: string;
about: string;
iconUrl: string;
backgroundUrl: string;
audioUrl: string;
modelUrl: string;
latitude: number;
longitude: number;
visited: boolean;
}
export interface AttractionDetails extends Attraction {
address: string;
facts: string[];
photoUrl: string;
}
export interface AreaProgress {
visited: number;
total: number;
}
export type VisitStatus = 'VISITED' | 'ALREADY_VISITED' | 'NOT_MATCHED' | 'UNCERTAIN';
export interface VisitResult {
status: VisitStatus;
confidence: number;
progress: AreaProgress;
}
export interface Area {
id: string;
parentId: string | null;
name: string;
attractions: Attraction[];
progress: AreaProgress;
}
export interface AreaDetails extends Area {
children: Area[];
}
export interface AreasPage {
content: Area[];
page: {
size: number;
number: number;
totalElements: number;
totalPages: number;
};
}
export type AreasStatus = 'idle' | 'loading' | 'ready' | 'error';
export function areaAttractions(area: Area | AreaDetails): Attraction[] {
const own = area.attractions ?? [];
const children = 'children' in area ? area.children : [];
return [...own, ...children.flatMap((child) => child.attractions ?? [])];
}
export function findAttraction(area: Area | AreaDetails, id: string): Attraction | null {
return areaAttractions(area).find((item) => item.id === id) ?? null;
}
export function isObtained(attraction: Attraction, collectedIds: ReadonlySet<string>): boolean {
return attraction.visited || collectedIds.has(attraction.id);
}
export function areaOpenedCount(area: Area | AreaDetails, collectedIds: ReadonlySet<string>): number {
const attractions = areaAttractions(area);
if (attractions.length > 0) {
return attractions.filter((item) => isObtained(item, collectedIds)).length;
}
return area.progress?.visited ?? 0;
}
export function areaTotalCount(area: Area | AreaDetails): number {
const attractions = areaAttractions(area);
if (attractions.length > 0) {
return attractions.length;
}
return area.progress?.total ?? 0;
}
export function areaProgress(area: Area | AreaDetails, collectedIds: ReadonlySet<string>): number {
const total = areaTotalCount(area);
if (!total) {
return 0;
}
return Math.round((areaOpenedCount(area, collectedIds) / total) * 100);
}
+33
View File
@@ -0,0 +1,33 @@
import { HttpClient } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable, map } from 'rxjs';
import { endpoints } from '../../environments/api';
import type { Area, AreaDetails, AreasPage, AttractionDetails, VisitResult } from './area.models';
@Injectable({ providedIn: 'root' })
export class AreasApiService {
private readonly http = inject(HttpClient);
getAreas(): Observable<Area[]> {
return this.http
.get<AreasPage>(endpoints.areas, {
params: { page: '0', size: '100' },
})
.pipe(map((page) => page.content));
}
getArea(id: string): Observable<AreaDetails> {
return this.http.get<AreaDetails>(endpoints.area(id));
}
getAttraction(id: string): Observable<AttractionDetails> {
return this.http.get<AttractionDetails>(endpoints.attraction(id));
}
visit(id: string, photo: Blob): Observable<VisitResult> {
const body = new FormData();
body.append('photo', photo, 'photo.jpg');
return this.http.post<VisitResult>(endpoints.visit(id), body);
}
}
+36
View File
@@ -0,0 +1,36 @@
const PHOTO_SIZE = 512;
const JPEG_QUALITY = 0.8;
export function resizePhoto(dataUrl: string): Promise<Blob> {
return new Promise((resolve, reject) => {
const image = new Image();
image.onload = () => {
const canvas = document.createElement('canvas');
canvas.width = PHOTO_SIZE;
canvas.height = PHOTO_SIZE;
const context = canvas.getContext('2d');
if (!context || image.width === 0 || image.height === 0) {
reject(new Error('Photo compression failed'));
return;
}
const scale = Math.max(PHOTO_SIZE / image.width, PHOTO_SIZE / image.height);
const width = image.width * scale;
const height = image.height * scale;
context.imageSmoothingQuality = 'high';
context.drawImage(image, (PHOTO_SIZE - width) / 2, (PHOTO_SIZE - height) / 2, width, height);
canvas.toBlob(
(blob) => (blob ? resolve(blob) : reject(new Error('Photo compression failed'))),
'image/jpeg',
JPEG_QUALITY,
);
};
image.onerror = () => reject(new Error('Photo is unreadable'));
image.src = dataUrl;
});
}
+4 -4
View File
@@ -3,7 +3,7 @@ import type { AuthSession } from './auth.models';
const SESSION_KEY = 'gorodar.session'; const SESSION_KEY = 'gorodar.session';
export function readAuthSession(): AuthSession | null { export function readAuthSession(): AuthSession | null {
const raw = sessionStorage.getItem(SESSION_KEY); const raw = localStorage.getItem(SESSION_KEY);
if (!raw) { if (!raw) {
return null; return null;
@@ -13,7 +13,7 @@ export function readAuthSession(): AuthSession | null {
const expired = !!session && typeof session.expiresAt === 'number' && session.expiresAt <= Date.now(); const expired = !!session && typeof session.expiresAt === 'number' && session.expiresAt <= Date.now();
if (!session || !isEmail(session.email) || !session.accessToken || expired) { if (!session || !isEmail(session.email) || !session.accessToken || expired) {
sessionStorage.removeItem(SESSION_KEY); localStorage.removeItem(SESSION_KEY);
return null; return null;
} }
@@ -21,11 +21,11 @@ export function readAuthSession(): AuthSession | null {
} }
export function writeAuthSession(session: AuthSession): void { export function writeAuthSession(session: AuthSession): void {
sessionStorage.setItem(SESSION_KEY, JSON.stringify(session)); localStorage.setItem(SESSION_KEY, JSON.stringify(session));
} }
export function clearAuthSession(): void { export function clearAuthSession(): void {
sessionStorage.removeItem(SESSION_KEY); localStorage.removeItem(SESSION_KEY);
} }
function parseSession(raw: string): AuthSession | null { function parseSession(raw: string): AuthSession | null {
+32
View File
@@ -0,0 +1,32 @@
import { HttpInterceptorFn } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Store } from '@ngrx/store';
import { selectAuth } from '../state/gorodar.selectors';
@Injectable({ providedIn: 'root' })
class AccessTokenReader {
private readonly auth = inject(Store).selectSignal(selectAuth);
token(): string | null {
return this.auth().accessToken;
}
}
export const authInterceptor: HttpInterceptorFn = (req, next) => {
if (req.url.includes('/oauth2/')) {
return next(req);
}
const token = inject(AccessTokenReader).token();
if (!token) {
return next(req);
}
return next(
req.clone({
setHeaders: { Authorization: `Bearer ${token}` },
}),
);
};
+18 -9
View File
@@ -1,12 +1,21 @@
@if (stage() === 'check' && photo(); as image) { @if (claim().stage === 'check' && claim().photo; as image) {
<app-photo-check [photo]="image" [title]="landmark().title" [step]="step()" /> <app-photo-check [photo]="image" [title]="landmark().name" [step]="claim().step" />
} @else if (stage() === 'success') { } @else if (claim().stage === 'failed') {
<app-photo-fail
[uncertain]="claim().failure === 'uncertain'"
[confidence]="claim().confidence"
(retake)="retake()"
(back)="leave()"
/>
} @else if (claim().stage === 'success') {
<app-collect-success <app-collect-success
[title]="landmark().title" [title]="landmark().name"
[image]="landmark().achievement" [image]="landmark().iconUrl"
[model]="landmark().model" [model]="landmark().modelUrl || undefined"
[cityName]="city.name" [alreadyVisited]="claim().alreadyVisited"
[opened]="openedCount()" [cityName]="cityName()"
[total]="totalCount" [opened]="opened()"
[total]="total()"
[areaId]="areaId()"
/> />
} }
+18 -17
View File
@@ -1,33 +1,34 @@
import { ChangeDetectionStrategy, Component, inject, input } from '@angular/core'; import { ChangeDetectionStrategy, Component, inject, input } from '@angular/core';
import { Store } from '@ngrx/store'; import { Store } from '@ngrx/store';
import type { Landmark } from '../../data/nizhny-novgorod'; import type { Attraction } from '../../areas/area.models';
import { CityCatalogService } from '../../root/services/city-catalog.service'; import { GorodarActions, selectClaim } from '../../state';
import {
selectClaimPhoto,
selectClaimStage,
selectClaimStep,
selectOpenedCount,
} from '../../state';
import { CollectSuccess } from '../collect-success/collect-success'; import { CollectSuccess } from '../collect-success/collect-success';
import { PhotoCheck } from '../photo-check/photo-check'; import { PhotoCheck } from '../photo-check/photo-check';
import { PhotoFail } from '../photo-fail/photo-fail';
@Component({ @Component({
selector: 'app-claim-flow', selector: 'app-claim-flow',
imports: [PhotoCheck, CollectSuccess], imports: [PhotoCheck, PhotoFail, CollectSuccess],
templateUrl: './claim-flow.html', templateUrl: './claim-flow.html',
changeDetection: ChangeDetectionStrategy.OnPush, changeDetection: ChangeDetectionStrategy.OnPush,
}) })
export class ClaimFlow { export class ClaimFlow {
private readonly store = inject(Store); private readonly store = inject(Store);
private readonly catalog = inject(CityCatalogService);
readonly landmark = input.required<Landmark>(); readonly landmark = input.required<Attraction>();
readonly cityName = input('');
readonly opened = input(0);
readonly total = input(1);
readonly areaId = input('');
protected readonly city = this.catalog.city; protected readonly claim = this.store.selectSignal(selectClaim);
protected readonly totalCount = this.city.objects.length;
protected readonly photo = this.store.selectSignal(selectClaimPhoto); protected retake(): void {
protected readonly stage = this.store.selectSignal(selectClaimStage); this.store.dispatch(GorodarActions.takePhoto({ landmarkId: this.landmark().id }));
protected readonly step = this.store.selectSignal(selectClaimStep); }
protected readonly openedCount = this.store.selectSignal(selectOpenedCount);
protected leave(): void {
this.store.dispatch(GorodarActions.claimReset());
}
} }
@@ -85,9 +85,15 @@
<h1 class="success__title">{{ title() }}</h1> <h1 class="success__title">{{ title() }}</h1>
} @else { } @else {
<div class="success__copy"> <div class="success__copy">
<p class="success__eyebrow">Новое в коллекции</p> <p class="success__eyebrow">{{ alreadyVisited() ? 'Уже в коллекции' : 'Новое в коллекции' }}</p>
<h1>{{ title() }}</h1> <h1>{{ title() }}</h1>
<p>Добавлено в коллекцию «{{ cityName() }}»</p> <p>
{{
alreadyVisited()
? 'Этот объект уже был в коллекции «' + cityName() + '»'
: 'Добавлено в коллекцию «' + cityName() + '»'
}}
</p>
</div> </div>
<div class="success__card anim-rise"> <div class="success__card anim-rise">
@@ -104,7 +110,7 @@
<div class="success__actions"> <div class="success__actions">
<a matButton="filled" routerLink="/collections" (click)="leave()">Открыть коллекцию</a> <a matButton="filled" routerLink="/collections" (click)="leave()">Открыть коллекцию</a>
<a class="success__ghost" routerLink="/city" (click)="leave()">Назад</a> <a class="success__ghost" [routerLink]="areaId() ? ['/city', areaId()] : ['/']" (click)="leave()">Назад</a>
</div> </div>
} }
</section> </section>
@@ -42,6 +42,8 @@ export class CollectSuccess {
readonly cityName = input(''); readonly cityName = input('');
readonly opened = input(0); readonly opened = input(0);
readonly total = input(1); readonly total = input(1);
readonly areaId = input('');
readonly alreadyVisited = input(false);
protected readonly view = signal<'model' | 'image'>('model'); protected readonly view = signal<'model' | 'image'>('model');
protected readonly modelLoaded = signal(false); protected readonly modelLoaded = signal(false);
@@ -129,7 +131,8 @@ export class CollectSuccess {
return; return;
} }
void this.router.navigateByUrl('/city'); const areaId = this.areaId();
void this.router.navigate(areaId ? ['/city', areaId] : ['/']);
} }
} }
+18 -40
View File
@@ -5,47 +5,25 @@
</div> </div>
<h1>Проверяем фото</h1> <h1>Проверяем фото</h1>
<p>Обычно это занимает несколько секунд</p> <p>Сверяем снимок с эталоном</p>
<ol class="steps"> <ol class="steps">
<li [class.steps__item--done]="step() >= 1"> @for (item of items(); track item.title) {
<span class="steps__mark steps__mark--done"> <li [class.steps__item--done]="item.state === 'done'" [class.steps__item--active]="item.state === 'active'">
<app-icon name="check" [size]="18" /> @if (item.state === 'done') {
</span> <span class="steps__mark steps__mark--done">
<div> <app-icon name="check" [size]="18" />
<b>Фото отправлено</b> </span>
<span>Снимок получен сервисом</span> } @else if (item.state === 'active') {
</div> <span class="steps__mark steps__mark--spin anim-spinner"></span>
</li> } @else {
<span class="steps__mark"></span>
<li [class.steps__item--done]="step() >= 2" [class.steps__item--active]="step() === 1"> }
@if (step() >= 2) { <div>
<span class="steps__mark steps__mark--done"> <b>{{ item.title }}</b>
<app-icon name="check" [size]="18" /> <span>{{ item.text }}</span>
</span> </div>
} @else { </li>
<span class="steps__mark steps__mark--spin anim-spinner"></span> }
}
<div>
<b>Сравниваем с эталонами</b>
<span>Ищем совпадение с {{ title() }}</span>
</div>
</li>
<li [class.steps__item--done]="step() >= 3" [class.steps__item--active]="step() === 2">
@if (step() >= 3) {
<span class="steps__mark steps__mark--done">
<app-icon name="check" [size]="18" />
</span>
} @else if (step() === 2) {
<span class="steps__mark steps__mark--spin anim-spinner"></span>
} @else {
<span class="steps__mark"></span>
}
<div>
<b>Добавляем в коллекцию</b>
<span>Объект появится в вашей коллекции</span>
</div>
</li>
</ol> </ol>
</section> </section>
@@ -99,6 +99,13 @@
border: 0; border: 0;
background: var(--color-accent); background: var(--color-accent);
color: var(--color-on-accent); color: var(--color-on-accent);
animation: step-pop 0.35s ease;
}
@keyframes step-pop {
from {
transform: scale(0.4);
}
} }
.steps b, .steps b,
@@ -121,3 +128,9 @@
.steps__item--active b { .steps__item--active b {
color: var(--color-text); color: var(--color-text);
} }
@media (prefers-reduced-motion: reduce) {
.steps__mark--done {
animation: none;
}
}
+34 -2
View File
@@ -1,7 +1,9 @@
import { ChangeDetectionStrategy, Component, input } from '@angular/core'; import { ChangeDetectionStrategy, Component, computed, input } from '@angular/core';
import { Icon } from '../../shared/icon/icon'; import { Icon } from '../../shared/icon/icon';
type StepState = 'done' | 'active' | 'wait';
@Component({ @Component({
selector: 'app-photo-check', selector: 'app-photo-check',
imports: [Icon], imports: [Icon],
@@ -12,5 +14,35 @@ import { Icon } from '../../shared/icon/icon';
export class PhotoCheck { export class PhotoCheck {
readonly photo = input.required<string>(); readonly photo = input.required<string>();
readonly title = input.required<string>(); readonly title = input.required<string>();
readonly step = input(1); readonly step = input(0);
protected readonly items = computed(() => {
const step = this.step();
return [
{
title: 'Фото отправлено',
text: step >= 1 ? 'Снимок получен сервисом' : 'Готовим снимок',
state: stepState(step, 0),
},
{
title: 'Сравниваем с эталонами',
text: `Ищем совпадение с ${this.title()}`,
state: stepState(step, 1),
},
{
title: 'Добавляем в коллекцию',
text: 'Объект появится в вашей коллекции',
state: stepState(step, 2),
},
];
});
}
function stepState(step: number, index: number): StepState {
if (step > index) {
return 'done';
}
return step === index ? 'active' : 'wait';
} }
+49
View File
@@ -0,0 +1,49 @@
<section class="fail">
<header class="fail__top">
<button class="fail__back" type="button" aria-label="К карточке объекта" (click)="back.emit()">
<app-icon name="chevron-left" [size]="22" />
</button>
</header>
<div class="fail__body">
<div class="fail__cross">
<img src="/assets/icons/cross.svg" alt="" width="80" height="80" />
</div>
<h1>{{ uncertain() ? 'Снимок неоднозначный' : 'Не получилось подтвердить' }}</h1>
@if (confidence() !== null) {
<div class="match">
<div class="match__head">
<span>Совпадение с эталонами</span>
<b class="match__value" [class.match__value--met]="shownPercent() >= requiredPercent">{{ shownPercent() }}%</b>
</div>
<div class="match__track">
<div class="match__fill" [style.width.%]="shownPercent()"></div>
<span class="match__mark" [style.left.%]="requiredPercent"></span>
<span class="match__need" [style.left.%]="requiredPercent">нужно от {{ requiredPercent }}%</span>
</div>
</div>
}
<ul class="fail__tips">
@for (tip of tips; track tip) {
<li>
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" aria-hidden="true">
<path d="M3 12 a9 9 0 1 0 18 0 a9 9 0 1 0 -18 0" stroke="currentColor" stroke-width="1.8" />
<path d="M12 11 V17 M12 7.5 V7.6" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" />
</svg>
<span>{{ tip }}</span>
</li>
}
</ul>
</div>
<footer class="fail__actions">
<button class="fail__retry" type="button" (click)="retake.emit()">
<app-icon name="camera" [size]="24" />
Сделать новое фото
</button>
<button class="fail__leave" type="button" (click)="back.emit()">Вернуться к карточке</button>
</footer>
</section>
+187
View File
@@ -0,0 +1,187 @@
:host {
display: block;
min-height: 100%;
background: var(--color-bg);
}
.fail {
display: flex;
flex-direction: column;
min-height: 100dvh;
box-sizing: border-box;
padding: 16px 16px calc(28px + env(safe-area-inset-bottom));
}
.fail__top {
padding: 0 0 8px;
}
.fail__back {
display: flex;
align-items: center;
justify-content: center;
width: 44px;
height: 44px;
padding: 0;
border: 1px solid var(--color-border);
border-radius: 14px;
background: rgb(28 26 23 / 86%);
color: var(--color-text);
}
.fail__body {
display: flex;
flex: 1;
flex-direction: column;
align-items: center;
padding: 8px 8px 24px;
}
.fail__cross {
display: flex;
flex: 1;
align-items: center;
justify-content: center;
min-height: 80px;
}
.fail h1 {
margin: 28px 0 0;
font-family: var(--font-display);
font-size: 28px;
font-weight: 700;
line-height: 1.2;
text-align: center;
}
.match {
align-self: stretch;
margin-top: 22px;
padding: 16px 16px 14px;
border: 1px solid rgb(255 255 255 / 8%);
border-radius: 16px;
background: #161513;
animation: match-in 0.45s ease both;
}
.match__head {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
font-size: 16px;
font-weight: 600;
}
.match__value {
color: #f0876a;
font-variant-numeric: tabular-nums;
}
.match__value--met {
color: var(--color-accent-soft);
}
.match__track {
position: relative;
height: 8px;
margin: 14px 0 26px;
border-radius: 99px;
background: #3a342e;
}
.match__fill {
height: 100%;
border-radius: inherit;
background: #efb0a0;
}
@keyframes match-in {
from {
opacity: 0;
transform: translateY(10px);
}
}
.match__mark {
position: absolute;
top: 50%;
z-index: 1;
width: 2px;
height: 18px;
background: #fff;
transform: translate(-50%, -50%);
}
.match__need {
position: absolute;
top: calc(100% + 6px);
color: #9c958a;
font-size: 12px;
line-height: 1.2;
white-space: nowrap;
transform: translateX(-50%);
}
@media (prefers-reduced-motion: reduce) {
.match {
animation: none;
}
}
.fail__tips {
display: flex;
flex-direction: column;
align-self: stretch;
gap: 10px;
margin: 28px 0 0;
padding: 0;
list-style: none;
color: #ddd6c8;
font-size: 14px;
}
.fail__tips li {
display: flex;
gap: 10px;
align-items: flex-start;
}
.fail__tips svg {
flex: none;
margin-top: 2px;
color: var(--color-accent);
}
.fail__actions {
display: flex;
flex-direction: column;
gap: 10px;
}
.fail__retry,
.fail__leave {
display: flex;
align-items: center;
justify-content: center;
gap: 10px;
width: 100%;
border: 0;
border-radius: 16px;
}
.fail__retry {
min-height: 56px;
background: var(--color-accent);
color: #1a1508;
font-size: 17px;
font-weight: 600;
}
.fail__leave {
min-height: 48px;
background: transparent;
color: var(--color-muted);
font-size: 15px;
font-weight: 500;
}
+64
View File
@@ -0,0 +1,64 @@
import { afterNextRender, ChangeDetectionStrategy, Component, computed, input, output, signal } from '@angular/core';
import { Icon } from '../../shared/icon/icon';
const COUNTER_MS = 1200;
@Component({
selector: 'app-photo-fail',
imports: [Icon],
templateUrl: './photo-fail.html',
styleUrl: './photo-fail.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class PhotoFail {
readonly uncertain = input(false);
readonly confidence = input.required<number | null>();
readonly retake = output<void>();
readonly back = output<void>();
protected readonly requiredPercent = 55;
protected readonly percent = computed(() => confidencePercent(this.confidence()));
protected readonly shownPercent = signal(0);
protected readonly tips = [
'Встаньте так, чтобы собор попал в кадр целиком.',
'Снимайте при хорошем свете, без пальцев в кадре.',
'Ориентируйтесь на примеры фото в карточке объекта.',
];
constructor() {
afterNextRender(() => this.playCounter());
}
private playCounter(): void {
const target = this.percent();
const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
if (target === 0 || reduceMotion) {
this.shownPercent.set(target);
return;
}
const started = performance.now();
const tick = (now: number) => {
const progress = Math.min(1, (now - started) / COUNTER_MS);
this.shownPercent.set(Math.round(target * progress));
if (progress < 1) {
requestAnimationFrame(tick);
}
};
requestAnimationFrame(tick);
}
}
function confidencePercent(confidence: number | null): number {
if (confidence === null) {
return 0;
}
const value = confidence <= 1 ? confidence * 100 : confidence;
return Math.max(0, Math.min(100, Math.round(value)));
}
-142
View File
@@ -1,142 +0,0 @@
export interface Landmark {
id: string;
title: string;
description: string;
address: string;
addressHint: string;
coordinates: [number, number];
collected: boolean;
geoCheckEnabled: boolean;
geoRadiusMeters: number;
facts: string[];
photoHint: string;
background: string;
audio: string;
achievement: string;
model?: string;
}
export interface City {
id: string;
name: string;
center: [number, number];
objects: Landmark[];
}
export const NIZHNY_NOVGOROD: City = {
id: 'nizhny-novgorod',
name: 'Нижний Новгород',
center: [43.99934, 56.329399],
objects: [
{
id: 'chkalov-stairs',
title: 'Чкаловская лестница',
description:
'Главная лестница-серпантин города: она спускается пологими зигзагами от площади Минина и Пожарского к Волге, а на верхней площадке стоит памятник лётчику Валерию Чкалову, чьё имя лестница носит.',
address: 'Верхне-Волжская набережная, Нижний Новгород',
addressHint: 'От площади Минина и Пожарского к Волге',
coordinates: [44.009444, 56.330833],
collected: false,
geoCheckEnabled: true,
geoRadiusMeters: 300,
facts: [
'Построена в 1943–1949 годах в честь победы в Сталинградской битве.',
'560 ступеней по внешнему контуру — одна из самых длинных лестниц в России.',
'Форма — цифра «8» с двумя смотровыми площадками с видом на Волгу и Стрелку.',
],
photoHint: 'Снимайте так, чтобы лестница читалась целиком.',
background: '/assets/background/nn-bg-chkalov-stairs.svg',
audio: '/assets/audio/chkalov-stairs.mp3',
achievement: '/assets/achivments/chkalov-stairs.png',
model: '/assets/models/chkalov-stairs.glb',
},
{
id: 'kremlin',
title: 'Нижегородский кремль',
description:
'Каменная крепость на высоком берегу Волги и Оки — исторический центр и главный символ Нижнего Новгорода.',
address: 'Кремль, Нижний Новгород',
addressHint: 'Высокий берег Волги и Оки',
coordinates: [44.00235, 56.327244],
collected: false,
geoCheckEnabled: true,
geoRadiusMeters: 300,
facts: [
'Построен в 1508–1515 годах.',
'13 башен (5 проездных, 8 глухих), общая длина стен — около 2045 метров.',
'Ни разу не был взят неприятелем за всю свою историю.',
],
photoHint: 'Снимайте так, чтобы были видны стены и башни кремля.',
background: '/assets/background/nn-bg-kremlin.svg',
audio: '/assets/audio/kremlin.mp3',
achievement: '/assets/achivments/kremlin.png',
model: '/assets/models/kremlin.glb',
},
{
id: 'iron-deer',
title: 'Железный олень',
description:
'Пятиметровая скульптура оленя на Нижневолжской набережной — подарок городу от почётного консула Венгрии и одна из самых фотографируемых точек в городе.',
address: 'Нижне-Волжская набережная, Нижний Новгород',
addressHint: 'На набережной Волги',
coordinates: [44.012083, 56.332055],
collected: false,
geoCheckEnabled: true,
geoRadiusMeters: 300,
facts: [
'Установлен в 2014 году к 793-летию основания Нижнего Новгорода.',
'Автор — венгерский скульптор Габор Миклош Жоке; фигура собрана из металлических пластин.',
'Олень — древний символ, изображён на гербе Нижегородской области.',
],
photoHint: 'Снимайте так, чтобы олень был виден целиком.',
background: '/assets/background/nn-bg-iron-deer.svg',
audio: '/assets/audio/iron-deer.mp3',
achievement: '/assets/achivments/iron-deer.png',
model: '/assets/models/iron-deer.glb',
},
{
id: 'rozhdestvenskaya',
title: 'Рождественская церковь',
description:
'Пятиглавый нарядный храм в стиле строгановского барокко на улице Рождественской — один из самых декоративных храмов города.',
address: 'ул. Рождественская, Нижний Новгород',
addressHint: 'Строгановское барокко',
coordinates: [43.985, 56.327222],
collected: false,
geoCheckEnabled: true,
geoRadiusMeters: 300,
facts: [
'Построена в 1696–1719 годах на средства купца Григория Строганова.',
'Украшена белокаменной резьбой и восьмигранной колокольней с часами.',
'Памятник архитектуры федерального значения; вновь освящена в 1993 году.',
],
photoHint: 'Снимайте так, чтобы храм был виден целиком.',
background: '/assets/background/nn-bg-rozhdestvenskaya.png',
audio: '/assets/audio/rozhdestvenskaya.mp3',
achievement: '/assets/achivments/rozhdestvenskaya.png',
model: '/assets/models/rozhdestvenskaya.glb',
},
{
id: 'river-station',
title: 'Речной вокзал',
description:
'Здание речного вокзала на площади Маркина, на самом слиянии Волги и Оки — когда-то главные «водные ворота» города для пассажирских рейсов.',
address: 'пл. Маркина, Нижний Новгород',
addressHint: 'Слияние Волги и Оки',
coordinates: [43.987823, 56.329641],
collected: false,
geoCheckEnabled: true,
geoRadiusMeters: 300,
facts: [
'Построен в 1964 году по проекту архитектора Чурилина.',
'Полностью застеклённый фасад напоминает аквариум; силуэт здания похож на корабль со шпилем вместо мачты.',
'Сегодня в здании работает выставочное пространство «Река-Река», вход свободный.',
],
photoHint: 'Снимайте так, чтобы силуэт вокзала читался целиком.',
background: '/assets/background/nn-bg-rechnoy-vokzal.svg',
audio: '/assets/audio/river-station.mp3',
achievement: '/assets/achivments/river-station.png',
model: '/assets/models/river-station.glb',
},
],
};
+1 -1
View File
@@ -31,7 +31,7 @@ export class BottomNav {
protected isActive(path: string, exact: boolean): boolean { protected isActive(path: string, exact: boolean): boolean {
const url = this.url(); const url = this.url();
if (path === '/') { if (path === '/') {
return url === '/' || url === '/city'; return url === '/' || /^\/city\/[^/]+$/.test(url);
} }
if (exact) { if (exact) {
return url === path; return url === path;
+3 -3
View File
@@ -6,11 +6,11 @@
<button <button
class="city-map__chip" class="city-map__chip"
type="button" type="button"
[attr.aria-label]="'Показать центр: ' + city.name" [attr.aria-label]="'Показать центр: ' + (cityName() || 'Город')"
(click)="focusCity()" (click)="focusCity()"
> >
<app-icon name="pin" [size]="18" /> <app-icon name="pin" [size]="18" />
<span>{{ city.name }}</span> <span>{{ cityName() || 'Город' }}</span>
</button> </button>
} }
@@ -40,7 +40,7 @@
@if (selected(); as landmark) { @if (selected(); as landmark) {
<div class="city-map__sheet"> <div class="city-map__sheet">
<app-map-item-sheet [landmark]="landmark" /> <app-map-item-sheet [attraction]="landmark" [areaId]="areaId()" />
</div> </div>
} }
</div> </div>
+84 -54
View File
@@ -15,13 +15,13 @@ import {
import { Geolocation, type Position } from '@capacitor/geolocation'; import { Geolocation, type Position } from '@capacitor/geolocation';
import { Store } from '@ngrx/store'; import { Store } from '@ngrx/store';
import { MapItemSheet } from '../map-item-sheet/map-item-sheet'; import type { Attraction } from '../../areas/area.models';
import { CityCatalogService } from '../../root/services/city-catalog.service';
import type { Landmark } from '../../data/nizhny-novgorod';
import { Icon } from '../../shared/icon/icon'; import { Icon } from '../../shared/icon/icon';
import { selectCollectedIdSet } from '../../state'; import { selectCollectedIdSet } from '../../state';
import { MapItemSheet } from '../map-item-sheet/map-item-sheet';
const MAP_KEY = 'bf0a466f-43a6-48c7-b274-7fea5952957b'; const MAP_KEY = 'bf0a466f-43a6-48c7-b274-7fea5952957b';
const CITY_CENTER: [number, number] = [43.99934, 56.329399];
const CITY_ZOOM = 16; const CITY_ZOOM = 16;
const USER_ZOOM = 20; const USER_ZOOM = 20;
const LANDMARK_SIZE = 40; const LANDMARK_SIZE = 40;
@@ -34,6 +34,7 @@ interface DgPoint {
interface DgMarker { interface DgMarker {
addTo(map: DgMap): this; addTo(map: DgMap): this;
remove(): void;
setLatLng(latLng: [number, number]): this; setLatLng(latLng: [number, number]): this;
setZIndexOffset(offset: number): this; setZIndexOffset(offset: number): this;
getElement(): HTMLElement | undefined; getElement(): HTMLElement | undefined;
@@ -135,7 +136,6 @@ export class CityMap implements AfterViewInit, OnDestroy {
@ViewChild('map', { static: true }) @ViewChild('map', { static: true })
private mapElement!: ElementRef<HTMLElement>; private mapElement!: ElementRef<HTMLElement>;
private readonly catalog = inject(CityCatalogService);
private readonly store = inject(Store); private readonly store = inject(Store);
private readonly zone = inject(NgZone); private readonly zone = inject(NgZone);
private raster: DgApi | null = null; private raster: DgApi | null = null;
@@ -152,6 +152,8 @@ export class CityMap implements AfterViewInit, OnDestroy {
private readonly clippedAncestors: HTMLElement[] = []; private readonly clippedAncestors: HTMLElement[] = [];
private readonly markerElements = new Map<string, HTMLElement>(); private readonly markerElements = new Map<string, HTMLElement>();
private readonly markers = new Map<string, DgMarker>(); private readonly markers = new Map<string, DgMarker>();
private readonly mapReady = signal(false);
private placedKey = '';
private readonly collectedIds = this.store.selectSignal(selectCollectedIdSet); private readonly collectedIds = this.store.selectSignal(selectCollectedIdSet);
private readonly stopFollowing = (): void => { private readonly stopFollowing = (): void => {
this.programmaticMove = false; this.programmaticMove = false;
@@ -169,19 +171,24 @@ export class CityMap implements AfterViewInit, OnDestroy {
}; };
readonly embedded = input(false); readonly embedded = input(false);
readonly cityName = input('');
readonly areaId = input('');
readonly attractions = input<Attraction[]>([]);
protected readonly city = this.catalog.city; protected readonly selected = signal<Attraction | null>(null);
protected readonly selected = signal<Landmark | null>(null);
protected readonly following = signal(false); protected readonly following = signal(false);
protected readonly fullscreen = signal(false); protected readonly fullscreen = signal(false);
constructor() { constructor() {
effect(() => { effect(() => {
const items = this.attractions();
const ids = this.collectedIds(); const ids = this.collectedIds();
for (const [id, element] of this.markerElements) { if (!this.mapReady()) {
this.setMarkerIcon(element, ids.has(id)); return;
} }
this.placeMarkers(items, ids);
}); });
effect(() => { effect(() => {
@@ -210,7 +217,7 @@ export class CityMap implements AfterViewInit, OnDestroy {
} }
const map = raster.map(this.mapElement.nativeElement, { const map = raster.map(this.mapElement.nativeElement, {
center: this.toLatLng(this.city.center), center: this.toLatLng(this.focusCenter(this.attractions())),
zoom: CITY_ZOOM, zoom: CITY_ZOOM,
key: MAP_KEY, key: MAP_KEY,
currentLang: 'ru', currentLang: 'ru',
@@ -228,14 +235,9 @@ export class CityMap implements AfterViewInit, OnDestroy {
this.map = map; this.map = map;
map.on('dragstart', this.stopFollowing); map.on('dragstart', this.stopFollowing);
map.on('zoomstart', this.onZoomStart); map.on('zoomstart', this.onZoomStart);
map.on('zoom', () => this.syncRadiusSize());
map.on('move', () => this.syncRadiusSize());
map.on('moveend', this.onMoveEnd); map.on('moveend', this.onMoveEnd);
for (const landmark of this.city.objects) { this.zone.run(() => this.mapReady.set(true));
this.markers.set(landmark.id, this.createMarker(raster, map, landmark));
}
requestAnimationFrame(() => this.resizeMap()); requestAnimationFrame(() => this.resizeMap());
}); });
} }
@@ -268,7 +270,7 @@ export class CityMap implements AfterViewInit, OnDestroy {
protected focusCity(): void { protected focusCity(): void {
this.following.set(false); this.following.set(false);
this.clearSelection(); this.clearSelection();
this.moveMap(this.city.center, CITY_ZOOM, 500); this.moveMap(this.focusCenter(this.attractions()), CITY_ZOOM, 500);
} }
protected async locate(): Promise<void> { protected async locate(): Promise<void> {
@@ -364,25 +366,69 @@ export class CityMap implements AfterViewInit, OnDestroy {
this.watchId = null; this.watchId = null;
} }
private createMarker(api: DgApi, map: DgMap, landmark: Landmark): DgMarker { private placeMarkers(items: Attraction[], collectedIds: Set<string>): void {
const map = this.map;
const api = this.raster;
if (!map || !api) {
return;
}
const key = items.map((item) => `${item.id}:${item.latitude}:${item.longitude}`).join('|');
if (key === this.placedKey) {
for (const item of items) {
const element = this.markerElements.get(item.id);
if (element) {
this.setMarkerIcon(element, collectedIds.has(item.id) || item.visited);
}
}
return;
}
for (const marker of this.markers.values()) {
marker.remove();
}
this.markers.clear();
this.markerElements.clear();
this.placedKey = key;
for (const item of items) {
if (typeof item.latitude !== 'number' || typeof item.longitude !== 'number') {
continue;
}
this.markers.set(item.id, this.createMarker(api, map, item, collectedIds.has(item.id) || item.visited));
}
if (this.markers.size > 0) {
this.moveMap(this.focusCenter(items), CITY_ZOOM, 0);
}
}
private createMarker(api: DgApi, map: DgMap, landmark: Attraction, collected: boolean): DgMarker {
const markerElement = document.createElement('button'); const markerElement = document.createElement('button');
markerElement.type = 'button'; markerElement.type = 'button';
markerElement.className = 'city-map__marker'; markerElement.className = 'city-map__marker';
markerElement.setAttribute('aria-label', landmark.title); markerElement.setAttribute('aria-label', landmark.name);
markerElement.innerHTML = `<span class="city-map__radius"></span><img width="40" height="40" alt="" /><span class="city-map__label"></span>`; markerElement.innerHTML =
'<span class="city-map__radius"></span><img width="40" height="40" alt="" /><span class="city-map__label"></span>';
const label = markerElement.querySelector('.city-map__label'); const label = markerElement.querySelector('.city-map__label');
if (label) { if (label) {
label.textContent = landmark.title; label.textContent = landmark.name;
} }
this.markerElements.set(landmark.id, markerElement); this.markerElements.set(landmark.id, markerElement);
this.setMarkerIcon(markerElement, this.collectedIds().has(landmark.id)); this.setMarkerIcon(markerElement, collected);
const marker = this.addHtmlMarker( const marker = this.addHtmlMarker(
api, api,
map, map,
landmark.coordinates, [landmark.longitude, landmark.latitude],
markerElement, markerElement,
LANDMARK_SIZE, LANDMARK_SIZE,
1, 1,
@@ -396,6 +442,21 @@ export class CityMap implements AfterViewInit, OnDestroy {
return marker; return marker;
} }
private focusCenter(items: Attraction[]): [number, number] {
const points = items.filter(
(item) => typeof item.latitude === 'number' && typeof item.longitude === 'number',
);
if (points.length === 0) {
return CITY_CENTER;
}
const longitude = points.reduce((sum, item) => sum + item.longitude, 0) / points.length;
const latitude = points.reduce((sum, item) => sum + item.latitude, 0) / points.length;
return [longitude, latitude];
}
private addHtmlMarker( private addHtmlMarker(
api: DgApi, api: DgApi,
map: DgMap, map: DgMap,
@@ -443,11 +504,10 @@ export class CityMap implements AfterViewInit, OnDestroy {
element.classList.toggle('city-map__marker--open', collected); element.classList.toggle('city-map__marker--open', collected);
} }
private selectLandmark(landmark: Landmark): void { private selectLandmark(landmark: Attraction): void {
const alreadySelected = this.selected()?.id === landmark.id; const alreadySelected = this.selected()?.id === landmark.id;
this.selected.set(alreadySelected ? null : landmark); this.selected.set(alreadySelected ? null : landmark);
this.syncSelection(); this.syncSelection();
this.syncRadiusSize();
} }
private clearSelection(): void { private clearSelection(): void {
@@ -465,36 +525,6 @@ export class CityMap implements AfterViewInit, OnDestroy {
} }
} }
private syncRadiusSize(): void {
const selected = this.selected();
const map = this.map;
if (!selected || !map) {
return;
}
const element = this.markerElements.get(selected.id);
if (!element) {
return;
}
const diameter = this.metersToPixels(map, selected.geoRadiusMeters, selected.coordinates) * 2;
element.style.setProperty('--radius-px', `${diameter}px`);
}
private metersToPixels(map: DgMap, meters: number, coordinates: [number, number]): number {
const [longitude, latitude] = coordinates;
const origin = map.latLngToContainerPoint(this.toLatLng(coordinates));
const metersPerDegree = 111_320 * Math.cos((latitude * Math.PI) / 180);
const shifted = map.latLngToContainerPoint([
latitude,
longitude + meters / Math.max(metersPerDegree, 1),
]);
return Math.hypot(shifted.x - origin.x, shifted.y - origin.y);
}
private moveMap(center: [number, number], zoom: number | null, durationMs: number): void { private moveMap(center: [number, number], zoom: number | null, durationMs: number): void {
const map = this.map; const map = this.map;
+11 -10
View File
@@ -1,23 +1,24 @@
<article class="card"> <article class="card">
<div class="card__row"> <div class="card__row">
<img class="card__stamp" src="/assets/icons/cell-lock.svg" alt="" width="72" height="72" /> <img
class="card__stamp"
[src]="attraction().iconUrl || '/assets/icons/cell-lock.svg'"
alt=""
width="72"
height="72"
/>
<div class="card__info"> <div class="card__info">
<h2>{{ landmark().title }}</h2> <h2>{{ attraction().name }}</h2>
<p class="card__status"> <p class="card__status">
<app-icon name="lock" [size]="16" /> <app-icon [name]="attraction().visited ? 'check' : 'lock'" [size]="16" />
Не получен {{ attraction().visited ? 'Получен' : 'Не получен' }}
</p>
<p class="card__geo">
<app-icon name="check" [size]="16" />
Вы в радиусе {{ landmark().geoRadiusMeters }} м — можно забирать
</p> </p>
</div> </div>
</div> </div>
<a class="card__action" matButton="filled" [routerLink]="['/items', landmark().id]"> <a class="card__action" matButton="filled" [routerLink]="['/city', areaId(), attraction().id]">
Открыть карточку Открыть карточку
</a> </a>
</article> </article>
+3 -2
View File
@@ -2,7 +2,7 @@ import { ChangeDetectionStrategy, Component, input } from '@angular/core';
import { MatButton } from '@angular/material/button'; import { MatButton } from '@angular/material/button';
import { RouterLink } from '@angular/router'; import { RouterLink } from '@angular/router';
import type { Landmark } from '../../data/nizhny-novgorod'; import type { Attraction } from '../../areas/area.models';
import { Icon } from '../../shared/icon/icon'; import { Icon } from '../../shared/icon/icon';
@Component({ @Component({
@@ -13,5 +13,6 @@ import { Icon } from '../../shared/icon/icon';
changeDetection: ChangeDetectionStrategy.OnPush, changeDetection: ChangeDetectionStrategy.OnPush,
}) })
export class MapItemSheet { export class MapItemSheet {
readonly landmark = input.required<Landmark>(); readonly attraction = input.required<Attraction>();
readonly areaId = input('');
} }
+43 -40
View File
@@ -4,50 +4,53 @@
<p>Приезжайте на место, снимайте — объект попадёт в вашу коллекцию.</p> <p>Приезжайте на место, снимайте — объект попадёт в вашу коллекцию.</p>
</div> </div>
@if (status() === 'loading' && areas().length === 0) {
<p class="cities__status">Загружаем города…</p>
} @else if (status() === 'error' && areas().length === 0) {
<p class="cities__status">{{ error() }}</p>
<button type="button" (click)="reload()">Повторить</button>
}
<div class="cities"> <div class="cities">
<a class="city-card" routerLink="/city" [attr.aria-label]="city.name"> @for (area of areas(); track area.id) {
<div class="city-card__top"> @if (area.attractions.length === 0) {
<div> <article class="city-card city-card--soon">
<h2>{{ city.name }}</h2> <h2>{{ area.name }}</h2>
<p> <p>Скоро появится</p>
Открыто </article>
<strong>{{ openedCount() }} из {{ totalCount }}</strong> } @else {
объектов <a class="city-card" [routerLink]="['/city', area.id]" [attr.aria-label]="area.name">
</p> <div class="city-card__top">
</div> <div>
<h2>{{ area.name }}</h2>
<p>
Открыто
<strong>{{ openedCount(area) }} из {{ totalCount(area) }}</strong>
объектов
</p>
</div>
<div class="city-card__percent" aria-hidden="true">{{ progress() }}%</div> <div class="city-card__percent" aria-hidden="true">{{ progress(area) }}%</div>
</div> </div>
<mat-progress-bar mode="determinate" [value]="progress()" /> <mat-progress-bar mode="determinate" [value]="progress(area)" />
<div class="city-card__cells"> <div class="city-card__cells">
@for (landmark of city.objects; track landmark.id) { @for (attraction of area.attractions; track attraction.id) {
<span <span
class="cell" class="cell"
[class.cell--open]="collectedIds().has(landmark.id)" [class.cell--open]="obtained(attraction)"
[attr.aria-label]=" [attr.aria-label]="attraction.name + (obtained(attraction) ? ', получено' : ', не получен')"
landmark.title + (collectedIds().has(landmark.id) ? ', получено' : ', не получен') >
" <img
> [src]="obtained(attraction) && attraction.iconUrl ? attraction.iconUrl : '/assets/icons/cell-lock.svg'"
<img [alt]=""
[src]=" />
collectedIds().has(landmark.id) </span>
? landmark.achievement }
: '/assets/icons/cell-lock.svg' </div>
" </a>
[alt]="" }
/>
</span>
}
</div>
</a>
@for (name of upcomingCities; track name) {
<article class="city-card city-card--soon">
<h2>{{ name }}</h2>
<p>Скоро появится</p>
</article>
} }
</div> </div>
</section> </section>
+25 -8
View File
@@ -3,8 +3,8 @@ import { MatProgressBar } from '@angular/material/progress-bar';
import { RouterLink } from '@angular/router'; import { RouterLink } from '@angular/router';
import { Store } from '@ngrx/store'; import { Store } from '@ngrx/store';
import { CityCatalogService } from '../../root/services/city-catalog.service'; import { areaOpenedCount, areaProgress, areaTotalCount, type Area, type Attraction } from '../../areas/area.models';
import { selectCollectedIdSet, selectOpenedCount, selectProgress } from '../../state'; import { GorodarActions, selectAreas, selectAreasError, selectAreasStatus, selectCollectedIdSet } from '../../state';
@Component({ @Component({
selector: 'app-cities-page', selector: 'app-cities-page',
@@ -14,13 +14,30 @@ import { selectCollectedIdSet, selectOpenedCount, selectProgress } from '../../s
changeDetection: ChangeDetectionStrategy.OnPush, changeDetection: ChangeDetectionStrategy.OnPush,
}) })
export class CitiesPage { export class CitiesPage {
private readonly catalog = inject(CityCatalogService);
private readonly store = inject(Store); private readonly store = inject(Store);
protected readonly city = this.catalog.city; protected readonly areas = this.store.selectSignal(selectAreas);
protected readonly upcomingCities = ['Москва', 'Санкт-Петербург']; protected readonly status = this.store.selectSignal(selectAreasStatus);
protected readonly error = this.store.selectSignal(selectAreasError);
protected readonly collectedIds = this.store.selectSignal(selectCollectedIdSet); protected readonly collectedIds = this.store.selectSignal(selectCollectedIdSet);
protected readonly openedCount = this.store.selectSignal(selectOpenedCount);
protected readonly totalCount = this.city.objects.length; protected openedCount(area: Area): number {
protected readonly progress = this.store.selectSignal(selectProgress); return areaOpenedCount(area, this.collectedIds());
}
protected totalCount(area: Area): number {
return areaTotalCount(area);
}
protected progress(area: Area): number {
return areaProgress(area, this.collectedIds());
}
protected obtained(attraction: Attraction): boolean {
return attraction.visited || this.collectedIds().has(attraction.id);
}
protected reload(): void {
this.store.dispatch(GorodarActions.areasRequested());
}
} }
+27 -16
View File
@@ -5,6 +5,7 @@
</a> </a>
</header> </header>
@if (area(); as city) {
<div class="page__city"> <div class="page__city">
<img src="/assets/icons/gorodar-mark.svg" alt="" width="96" height="96" /> <img src="/assets/icons/gorodar-mark.svg" alt="" width="96" height="96" />
<div> <div>
@@ -12,7 +13,7 @@
<p> <p>
<app-icon name="pin" [size]="18" /> <app-icon name="pin" [size]="18" />
<span> <span>
<b>{{ openedCount() }}/{{ city.objects.length }}</b> <b>{{ openedCount() }}/{{ totalCount() }}</b>
объектов объектов
</span> </span>
<span>·</span> <span>·</span>
@@ -43,14 +44,18 @@
</button> </button>
</nav> </nav>
@if (tab() === 'objects') { @if (tab() === 'objects' && totalCount() === 0) {
<p class="page__status">В этом городе пока нет объектов.</p>
}
@if (tab() === 'objects' && totalCount() > 0) {
<div class="filters"> <div class="filters">
<button <button
type="button" type="button"
[class.filters__item--active]="filter() === 'all'" [class.filters__item--active]="filter() === 'all'"
(click)="filter.set('all')" (click)="filter.set('all')"
> >
Все · {{ city.objects.length }} Все · {{ totalCount() }}
</button> </button>
<button <button
type="button" type="button"
@@ -71,8 +76,8 @@
<div class="grid"> <div class="grid">
@for (landmark of landmarks(); track landmark.id) { @for (landmark of landmarks(); track landmark.id) {
<a class="card" [routerLink]="objectRoute(landmark.id)"> <a class="card" [routerLink]="objectRoute(landmark.id)">
<div class="card__preview" [class.card__preview--open]="collectedIds().has(landmark.id)"> <div class="card__preview" [class.card__preview--open]="isOpen(landmark)">
@if (collectedIds().has(landmark.id)) { @if (isOpen(landmark)) {
<svg class="card__rays" viewBox="0 0 112 112" aria-hidden="true"> <svg class="card__rays" viewBox="0 0 112 112" aria-hidden="true">
@for (ray of rays; track $index) { @for (ray of rays; track $index) {
<line <line
@@ -93,22 +98,18 @@
<span class="card__spark card__spark--d"></span> <span class="card__spark card__spark--d"></span>
} }
<img <img
[src]=" [src]="isOpen(landmark) && landmark.iconUrl ? landmark.iconUrl : '/assets/icons/cell-lock.svg'"
collectedIds().has(landmark.id)
? landmark.achievement
: '/assets/icons/cell-lock.svg'
"
alt="" alt=""
/> />
</div> </div>
<div class="card__body"> <div class="card__body">
<h2>{{ landmark.title }}</h2> <h2>{{ landmark.name }}</h2>
<span class="card__status" [class.card__status--open]="collectedIds().has(landmark.id)"> <span class="card__status" [class.card__status--open]="isOpen(landmark)">
<app-icon [name]="collectedIds().has(landmark.id) ? 'check' : 'lock'" [size]="15" /> <app-icon [name]="isOpen(landmark) ? 'check' : 'lock'" [size]="15" />
{{ collectedIds().has(landmark.id) ? 'Получен' : 'Не получен' }} {{ isOpen(landmark) ? 'Получен' : 'Не получен' }}
</span> </span>
</div> </div>
<span class="card__bar" [class.card__bar--open]="collectedIds().has(landmark.id)"></span> <span class="card__bar" [class.card__bar--open]="isOpen(landmark)"></span>
</a> </a>
} }
</div> </div>
@@ -116,7 +117,17 @@
@if (mapReady()) { @if (mapReady()) {
<div class="page__map" [class.page__map--off]="tab() !== 'map'"> <div class="page__map" [class.page__map--off]="tab() !== 'map'">
<app-city-map [embedded]="true" /> <app-city-map
[embedded]="true"
[cityName]="city.name"
[areaId]="areaId()"
[attractions]="mapAttractions()"
/>
</div> </div>
} }
} @else if (status() === 'loading') {
<p class="page__status">Загружаем город…</p>
} @else {
<p class="page__status">{{ error() || 'Город не найден.' }}</p>
}
</section> </section>
+62 -12
View File
@@ -1,11 +1,25 @@
import { ChangeDetectionStrategy, Component, computed, inject, signal } from '@angular/core'; import { ChangeDetectionStrategy, Component, computed, effect, inject, input, signal } from '@angular/core';
import { RouterLink } from '@angular/router'; import { RouterLink } from '@angular/router';
import { Store } from '@ngrx/store'; import { Store } from '@ngrx/store';
import {
areaAttractions,
areaOpenedCount,
areaProgress,
areaTotalCount,
findAttraction,
isObtained,
type Attraction,
} from '../../areas/area.models';
import { CityMap } from '../../map/city-map/city-map'; import { CityMap } from '../../map/city-map/city-map';
import { CityCatalogService } from '../../root/services/city-catalog.service';
import { Icon } from '../../shared/icon/icon'; import { Icon } from '../../shared/icon/icon';
import { selectCollectedIdSet, selectOpenedCount, selectProgress } from '../../state'; import {
GorodarActions,
selectAreaDetailError,
selectAreaDetails,
selectAreaDetailStatus,
selectCollectedIdSet,
} from '../../state';
type CollectionFilter = 'all' | 'open' | 'closed'; type CollectionFilter = 'all' | 'open' | 'closed';
type CityTab = 'objects' | 'map'; type CityTab = 'objects' | 'map';
@@ -18,26 +32,47 @@ type CityTab = 'objects' | 'map';
changeDetection: ChangeDetectionStrategy.OnPush, changeDetection: ChangeDetectionStrategy.OnPush,
}) })
export class CityPage { export class CityPage {
private readonly catalog = inject(CityCatalogService);
private readonly store = inject(Store); private readonly store = inject(Store);
protected readonly city = this.catalog.city; readonly areaId = input.required<string>();
private readonly details = this.store.selectSignal(selectAreaDetails);
private readonly detailStatus = this.store.selectSignal(selectAreaDetailStatus);
private readonly detailError = this.store.selectSignal(selectAreaDetailError);
protected readonly status = computed(() => this.detailStatus()[this.areaId()] ?? 'loading');
protected readonly error = computed(() => this.detailError()[this.areaId()] ?? '');
protected readonly area = computed(() => this.details()[this.areaId()] ?? null);
protected readonly tab = signal<CityTab>('objects'); protected readonly tab = signal<CityTab>('objects');
protected readonly mapReady = signal(false); protected readonly mapReady = signal(false);
protected readonly filter = signal<CollectionFilter>('all'); protected readonly filter = signal<CollectionFilter>('all');
protected readonly collectedIds = this.store.selectSignal(selectCollectedIdSet); protected readonly collectedIds = this.store.selectSignal(selectCollectedIdSet);
protected readonly openedCount = this.store.selectSignal(selectOpenedCount); protected readonly openedCount = computed(() => {
protected readonly progress = this.store.selectSignal(selectProgress); const area = this.area();
protected readonly closedCount = computed(() => this.city.objects.length - this.openedCount()); return area ? areaOpenedCount(area, this.collectedIds()) : 0;
});
protected readonly totalCount = computed(() => {
const area = this.area();
return area ? areaTotalCount(area) : 0;
});
protected readonly progress = computed(() => {
const area = this.area();
return area ? areaProgress(area, this.collectedIds()) : 0;
});
protected readonly closedCount = computed(() => this.totalCount() - this.openedCount());
protected readonly mapAttractions = computed(() => {
const area = this.area();
return area ? areaAttractions(area) : [];
});
protected readonly landmarks = computed(() => { protected readonly landmarks = computed(() => {
const items = this.city.objects; const current = this.area();
const items = current ? areaAttractions(current) : [];
const ids = this.collectedIds(); const ids = this.collectedIds();
switch (this.filter()) { switch (this.filter()) {
case 'open': case 'open':
return items.filter((item) => ids.has(item.id)); return items.filter((item) => isObtained(item, ids));
case 'closed': case 'closed':
return items.filter((item) => !ids.has(item.id)); return items.filter((item) => !isObtained(item, ids));
default: default:
return items; return items;
} }
@@ -58,6 +93,12 @@ export class CityPage {
}; };
}); });
constructor() {
effect(() => {
this.store.dispatch(GorodarActions.areaRequested({ id: this.areaId() }));
});
}
protected openObjects(): void { protected openObjects(): void {
this.tab.set('objects'); this.tab.set('objects');
} }
@@ -67,7 +108,16 @@ export class CityPage {
this.tab.set('map'); this.tab.set('map');
} }
protected isOpen(attraction: Attraction): boolean {
return isObtained(attraction, this.collectedIds());
}
protected objectRoute(id: string): string[] { protected objectRoute(id: string): string[] {
return this.collectedIds().has(id) ? ['/city', id, 'icon'] : ['/city', id]; const current = this.area();
const attraction = current ? findAttraction(current, id) : null;
const open = attraction ? isObtained(attraction, this.collectedIds()) : false;
return open
? ['/city', this.areaId(), id, 'icon']
: ['/city', this.areaId(), id];
} }
} }
@@ -1,10 +1,12 @@
<section class="page"> <section class="page">
<header class="account"> @if (authenticated()) {
<p class="account__email">{{ accountEmail() }}</p> <header class="account">
<button class="account__logout" type="button" aria-label="Выйти" (click)="logout()"> <p class="account__email">{{ accountEmail() }}</p>
<app-icon name="logout" [size]="22" /> <button class="account__logout" type="button" aria-label="Выйти" (click)="logout()">
</button> <app-icon name="logout" [size]="22" />
</header> </button>
</header>
}
<div class="page__intro"> <div class="page__intro">
<h1>Вся коллекция</h1> <h1>Вся коллекция</h1>
@@ -17,46 +19,48 @@
<span>{{ objectsLabel() }}</span> <span>{{ objectsLabel() }}</span>
</div> </div>
<div> <div>
<b>1</b> <b>{{ packs().length }}</b>
<span>город</span> <span>{{ citiesLabel() }}</span>
</div> </div>
</section> </section>
<p class="section-label">Мои города</p> <p class="section-label">Мои города</p>
@if (collectedLandmarks().length > 0) { @if (packs().length > 0) {
<article class="pack"> @for (pack of packs(); track pack.area.id) {
<a class="pack__head" routerLink="/city" [attr.aria-label]="'Объекты: ' + city.name"> <article class="pack">
<div> <a class="pack__head" [routerLink]="['/city', pack.area.id]" [attr.aria-label]="'Объекты: ' + pack.area.name">
<h2>{{ city.name }}</h2> <div>
<p>Собрано {{ openedCount() }} из {{ totalCount }}</p> <h2>{{ pack.area.name }}</h2>
</div> <p>Собрано {{ pack.opened }} из {{ pack.total }}</p>
<div class="pack__percent anim-percent" [style.--to-p]="progress()" aria-hidden="true"> </div>
<span>{{ progress() }}%</span> <div class="pack__percent anim-percent" [style.--to-p]="pack.progress" aria-hidden="true">
</div> <span>{{ pack.progress }}%</span>
<span class="pack__go" aria-hidden="true"> </div>
<app-icon name="chevron-right" [size]="20" /> <span class="pack__go" aria-hidden="true">
</span> <app-icon name="chevron-right" [size]="20" />
</a> </span>
</a>
<div class="pack__bar" aria-hidden="true"> <div class="pack__bar" aria-hidden="true">
<span class="anim-grow" [style.--from]="'0%'" [style.--to]="progress() + '%'"></span> <span class="anim-grow" [style.--from]="'0%'" [style.--to]="pack.progress + '%'"></span>
</div> </div>
<div class="picked"> <div class="picked">
@for (landmark of collectedLandmarks(); track landmark.id) { @for (landmark of pack.items; track landmark.id) {
<a class="picked__card" [routerLink]="objectRoute(landmark.id)"> <a class="picked__card" [routerLink]="objectRoute(pack.area.id, landmark)">
<div class="picked__preview"> <div class="picked__preview">
<img [src]="landmark.achievement" alt="" /> <img [src]="landmark.iconUrl" alt="" />
</div> </div>
<div class="picked__body"> <div class="picked__body">
<h3>{{ landmark.title }}</h3> <h3>{{ landmark.name }}</h3>
</div> </div>
<span class="picked__bar" aria-hidden="true"></span> <span class="picked__bar" aria-hidden="true"></span>
</a> </a>
} }
</div> </div>
</article> </article>
}
} @else { } @else {
<p class="empty">Пока нет полученных объектов.</p> <p class="empty">Пока нет полученных объектов.</p>
} }
@@ -2,16 +2,23 @@ import { afterNextRender, ChangeDetectionStrategy, Component, computed, inject }
import { RouterLink } from '@angular/router'; import { RouterLink } from '@angular/router';
import { Store } from '@ngrx/store'; import { Store } from '@ngrx/store';
import { CityCatalogService } from '../../root/services/city-catalog.service'; import {
areaAttractions,
areaOpenedCount,
areaProgress,
areaTotalCount,
isObtained,
type Attraction,
} from '../../areas/area.models';
import { Icon } from '../../shared/icon/icon'; import { Icon } from '../../shared/icon/icon';
import { import {
GorodarActions, GorodarActions,
selectAreas,
selectAuthEmail, selectAuthEmail,
selectAuthenticated, selectAuthenticated,
selectCollectedIdSet, selectCollectedIdSet,
selectOpenedCount, selectOpenedCount,
selectProfile, selectProfile,
selectProgress,
} from '../../state'; } from '../../state';
@Component({ @Component({
@@ -22,23 +29,30 @@ import {
changeDetection: ChangeDetectionStrategy.OnPush, changeDetection: ChangeDetectionStrategy.OnPush,
}) })
export class CollectionsPage { export class CollectionsPage {
private readonly catalog = inject(CityCatalogService);
private readonly store = inject(Store); private readonly store = inject(Store);
protected readonly city = this.catalog.city; private readonly areas = this.store.selectSignal(selectAreas);
protected readonly profile = this.store.selectSignal(selectProfile); protected readonly profile = this.store.selectSignal(selectProfile);
protected readonly collectedIds = this.store.selectSignal(selectCollectedIdSet); protected readonly collectedIds = this.store.selectSignal(selectCollectedIdSet);
protected readonly openedCount = this.store.selectSignal(selectOpenedCount); protected readonly openedCount = this.store.selectSignal(selectOpenedCount);
protected readonly totalCount = this.city.objects.length; protected readonly authenticated = this.store.selectSignal(selectAuthenticated);
protected readonly progress = this.store.selectSignal(selectProgress);
private readonly authenticated = this.store.selectSignal(selectAuthenticated);
private readonly authEmail = this.store.selectSignal(selectAuthEmail); private readonly authEmail = this.store.selectSignal(selectAuthEmail);
protected readonly accountEmail = computed(() => protected readonly accountEmail = computed(() =>
this.authenticated() ? this.authEmail() : this.profile().email, this.authenticated() ? this.authEmail() : this.profile().email,
); );
protected readonly collectedLandmarks = computed(() => protected readonly packs = computed(() => {
this.city.objects.filter((item) => this.collectedIds().has(item.id)), const ids = this.collectedIds();
);
return this.areas()
.map((area) => ({
area,
items: areaAttractions(area).filter((item) => isObtained(item, ids)),
opened: areaOpenedCount(area, ids),
total: areaTotalCount(area),
progress: areaProgress(area, ids),
}))
.filter((pack) => pack.items.length > 0);
});
constructor() { constructor() {
afterNextRender(() => { afterNextRender(() => {
@@ -50,8 +64,14 @@ export class CollectionsPage {
this.plural(this.openedCount(), ['объект', 'объекта', 'объектов']), this.plural(this.openedCount(), ['объект', 'объекта', 'объектов']),
); );
protected objectRoute(id: string): string[] { protected readonly citiesLabel = computed(() =>
return this.collectedIds().has(id) ? ['/city', id, 'icon'] : ['/city', id]; this.plural(this.packs().length, ['город', 'города', 'городов']),
);
protected objectRoute(areaId: string, attraction: Attraction): string[] {
return isObtained(attraction, this.collectedIds())
? ['/city', areaId, attraction.id, 'icon']
: ['/city', areaId, attraction.id];
} }
protected logout(): void { protected logout(): void {
@@ -2,14 +2,19 @@
@if (collected()) { @if (collected()) {
<app-collect-success <app-collect-success
mode="preview" mode="preview"
[title]="item.title" [title]="item.name"
[image]="item.achievement" [image]="item.iconUrl"
[model]="item.model" [model]="item.modelUrl || undefined"
[areaId]="areaId()"
/> />
} }
} @else if (status() === 'loading') {
<section class="missing">
<p>Загружаем…</p>
</section>
} @else { } @else {
<section class="missing"> <section class="missing">
<p>Объект не найден.</p> <p>Объект не найден.</p>
<a routerLink="/city">К списку объектов</a> <a [routerLink]="['/city', areaId()]">К списку объектов</a>
</section> </section>
} }
@@ -2,9 +2,9 @@ import { ChangeDetectionStrategy, Component, computed, effect, inject, input } f
import { Router, RouterLink } from '@angular/router'; import { Router, RouterLink } from '@angular/router';
import { Store } from '@ngrx/store'; import { Store } from '@ngrx/store';
import { findAttraction, isObtained } from '../../areas/area.models';
import { CollectSuccess } from '../../claim/collect-success/collect-success'; import { CollectSuccess } from '../../claim/collect-success/collect-success';
import { CityCatalogService } from '../../root/services/city-catalog.service'; import { GorodarActions, selectAreaDetails, selectAreaDetailStatus, selectCollectedIdSet } from '../../state';
import { selectCollectedIdSet } from '../../state';
@Component({ @Component({
selector: 'app-icon-preview-page', selector: 'app-icon-preview-page',
@@ -14,28 +14,45 @@ import { selectCollectedIdSet } from '../../state';
changeDetection: ChangeDetectionStrategy.OnPush, changeDetection: ChangeDetectionStrategy.OnPush,
}) })
export class IconPreviewPage { export class IconPreviewPage {
private readonly catalog = inject(CityCatalogService);
private readonly store = inject(Store); private readonly store = inject(Store);
private readonly router = inject(Router); private readonly router = inject(Router);
private readonly details = this.store.selectSignal(selectAreaDetails);
private readonly detailStatus = this.store.selectSignal(selectAreaDetailStatus);
protected readonly status = computed(() => this.detailStatus()[this.areaId()] ?? 'loading');
private readonly collectedIds = this.store.selectSignal(selectCollectedIdSet); private readonly collectedIds = this.store.selectSignal(selectCollectedIdSet);
readonly areaId = input.required<string>();
readonly id = input.required<string>(); readonly id = input.required<string>();
protected readonly landmark = computed(() => this.catalog.landmarkById(this.id())); protected readonly landmark = computed(() => {
const area = this.details()[this.areaId()];
return area ? findAttraction(area, this.id()) : null;
});
protected readonly collected = computed(() => { protected readonly collected = computed(() => {
const item = this.landmark(); const item = this.landmark();
return item ? this.collectedIds().has(item.id) : false; return item ? isObtained(item, this.collectedIds()) : false;
}); });
constructor() { constructor() {
effect(() => { effect(() => {
const item = this.landmark(); const areaId = this.areaId();
const status = this.detailStatus()[areaId];
if (!item || this.collectedIds().has(item.id)) { if (this.details()[areaId] || status === 'loading' || status === 'ready') {
return; return;
} }
void this.router.navigate(['/city', item.id], { replaceUrl: true }); this.store.dispatch(GorodarActions.areaRequested({ id: areaId }));
});
effect(() => {
const item = this.landmark();
if (this.status() !== 'ready' || !item || isObtained(item, this.collectedIds())) {
return;
}
void this.router.navigate(['/city', this.areaId(), item.id], { replaceUrl: true });
}); });
} }
} }
+49 -32
View File
@@ -1,18 +1,26 @@
@if (landmark(); as item) { @if (landmark(); as item) {
@if (claiming()) { @if (claiming()) {
<app-claim-flow [landmark]="item" /> <app-claim-flow
[landmark]="item"
[cityName]="area()?.name ?? ''"
[opened]="openedCount()"
[total]="totalCount()"
[areaId]="areaId()"
/>
} @else { } @else {
<article class="object" [class.object--owned]="collected()"> <article class="object" [class.object--owned]="collected()">
<header class="object__hero"> <header class="object__hero">
<img class="object__hero-img" [src]="item.background" alt="" /> @if (item.backgroundUrl || item.photoUrl) {
<img class="object__hero-img" [src]="item.backgroundUrl || item.photoUrl" alt="" />
}
<button class="object__back" type="button" aria-label="Назад" (click)="goBack()"> <button class="object__back" type="button" aria-label="Назад" (click)="goBack()">
<app-icon name="chevron-left" [size]="22" /> <app-icon name="chevron-left" [size]="22" />
</button> </button>
<span class="object__city">{{ city.name }}</span> <span class="object__city">{{ area()?.name }}</span>
</header> </header>
<div class="object__intro"> <div class="object__intro">
<h1>{{ item.title }}</h1> <h1>{{ item.name }}</h1>
<div class="object__chips"> <div class="object__chips">
<span class="chip" [class.chip--open]="collected()"> <span class="chip" [class.chip--open]="collected()">
@@ -21,39 +29,44 @@
</span> </span>
</div> </div>
<div class="object__address"> @if (item.address) {
<app-icon name="pin" [size]="18" /> <div class="object__address">
<div> <app-icon name="pin" [size]="18" />
<p>{{ item.address }}</p> <div>
<span>{{ item.addressHint }}</span> <p>{{ item.address }}</p>
</div>
</div> </div>
</div> }
</div> </div>
<div class="object__body"> <div class="object__body">
<section> @if (item.about) {
<h2>О месте</h2> <section>
<p>{{ item.description }}</p> <h2>О месте</h2>
</section> <p>{{ item.about }}</p>
</section>
}
<section> @if (item.facts.length > 0) {
<h2>Аудиогид</h2> <section>
<app-audio-guide [src]="item.audio" /> <h2>Интересные факты</h2>
</section> <ol class="facts">
@for (fact of item.facts; track fact; let index = $index) {
<li>
<span class="facts__number">{{ index + 1 }}</span>
<span class="facts__value">{{ fact }}</span>
</li>
}
</ol>
</section>
}
<section> @if (item.audioUrl) {
<h2>Интересные факты</h2> <section>
<ol class="facts"> <h2>Аудиогид</h2>
@for (fact of item.facts; track fact; let index = $index) { <app-audio-guide [src]="item.audioUrl" />
<li> </section>
<span class="facts__number">{{ index + 1 }}</span> }
<span class="facts__value">
{{ fact }}
</span>
</li>
}
</ol>
</section>
@if (collected()) { @if (collected()) {
<section> <section>
@@ -111,9 +124,13 @@
</div> </div>
} }
} }
} @else if (status() === 'loading') {
<section class="object object--empty">
<p>Загружаем…</p>
</section>
} @else { } @else {
<section class="object object--empty"> <section class="object object--empty">
<p>Объект не найден.</p> <p>{{ error() || 'Объект не найден.' }}</p>
<button matButton="outlined" type="button" (click)="goBack()">Назад</button> <button matButton="outlined" type="button" (click)="goBack()">Назад</button>
</section> </section>
} }
+44 -6
View File
@@ -3,6 +3,7 @@ import {
ChangeDetectionStrategy, ChangeDetectionStrategy,
Component, Component,
computed, computed,
effect,
HostListener, HostListener,
inject, inject,
input, input,
@@ -12,12 +13,17 @@ import { MatButton } from '@angular/material/button';
import { Router } from '@angular/router'; import { Router } from '@angular/router';
import { Store } from '@ngrx/store'; import { Store } from '@ngrx/store';
import { areaOpenedCount, areaTotalCount, isObtained, type AreaDetails } from '../../areas/area.models';
import { ClaimFlow } from '../../claim/claim-flow/claim-flow'; import { ClaimFlow } from '../../claim/claim-flow/claim-flow';
import { CityCatalogService } from '../../root/services/city-catalog.service';
import { AudioGuide } from '../../shared/audio-guide/audio-guide'; import { AudioGuide } from '../../shared/audio-guide/audio-guide';
import { Icon } from '../../shared/icon/icon'; import { Icon } from '../../shared/icon/icon';
import { import {
GorodarActions, GorodarActions,
selectAreaDetails,
selectAreaDetailStatus,
selectAttractionError,
selectAttractions,
selectAttractionStatus,
selectAuthenticated, selectAuthenticated,
selectClaim, selectClaim,
selectCollectedAt, selectCollectedAt,
@@ -33,24 +39,39 @@ import {
changeDetection: ChangeDetectionStrategy.OnPush, changeDetection: ChangeDetectionStrategy.OnPush,
}) })
export class MapItemPage { export class MapItemPage {
private readonly catalog = inject(CityCatalogService);
private readonly store = inject(Store); private readonly store = inject(Store);
private readonly location = inject(Location); private readonly location = inject(Location);
private readonly router = inject(Router); private readonly router = inject(Router);
private readonly authenticated = this.store.selectSignal(selectAuthenticated); private readonly authenticated = this.store.selectSignal(selectAuthenticated);
private readonly details = this.store.selectSignal(selectAreaDetails);
private readonly detailStatus = this.store.selectSignal(selectAreaDetailStatus);
private readonly attractions = this.store.selectSignal(selectAttractions);
private readonly attractionStatuses = this.store.selectSignal(selectAttractionStatus);
private readonly attractionErrors = this.store.selectSignal(selectAttractionError);
readonly areaId = input.required<string>();
readonly id = input.required<string>(); readonly id = input.required<string>();
protected readonly city = this.catalog.city; protected readonly status = computed(() => this.attractionStatuses()[this.id()] ?? 'loading');
protected readonly landmark = computed(() => this.catalog.landmarkById(this.id())); protected readonly error = computed(() => this.attractionErrors()[this.id()] ?? '');
protected readonly area = computed((): AreaDetails | null => this.details()[this.areaId()] ?? null);
protected readonly landmark = computed(() => this.attractions()[this.id()] ?? null);
protected readonly collectedIds = this.store.selectSignal(selectCollectedIdSet); protected readonly collectedIds = this.store.selectSignal(selectCollectedIdSet);
protected readonly photos = this.store.selectSignal(selectPhotos); protected readonly photos = this.store.selectSignal(selectPhotos);
protected readonly collectedAtMap = this.store.selectSignal(selectCollectedAt); protected readonly collectedAtMap = this.store.selectSignal(selectCollectedAt);
protected readonly claim = this.store.selectSignal(selectClaim); protected readonly claim = this.store.selectSignal(selectClaim);
protected readonly openedCount = computed(() => {
const area = this.area();
return area ? areaOpenedCount(area, this.collectedIds()) : 0;
});
protected readonly totalCount = computed(() => {
const area = this.area();
return area ? areaTotalCount(area) : 0;
});
protected readonly collected = computed(() => { protected readonly collected = computed(() => {
const item = this.landmark(); const item = this.landmark();
return item ? this.collectedIds().has(item.id) || item.collected : false; return item ? isObtained(item, this.collectedIds()) : false;
}); });
protected readonly userPhoto = computed(() => { protected readonly userPhoto = computed(() => {
@@ -85,13 +106,30 @@ export class MapItemPage {
protected readonly photoOpen = signal(false); protected readonly photoOpen = signal(false);
constructor() {
effect(() => {
const areaId = this.areaId();
const status = this.detailStatus()[areaId];
if (this.details()[areaId] || status === 'loading' || status === 'ready') {
return;
}
this.store.dispatch(GorodarActions.areaRequested({ id: areaId }));
});
effect(() => {
this.store.dispatch(GorodarActions.attractionRequested({ id: this.id() }));
});
}
protected goBack(): void { protected goBack(): void {
if (window.history.length > 1) { if (window.history.length > 1) {
this.location.back(); this.location.back();
return; return;
} }
void this.router.navigateByUrl('/city'); void this.router.navigate(['/city', this.areaId()]);
} }
protected claimItem(): void { protected claimItem(): void {
@@ -1,14 +0,0 @@
import { Injectable } from '@angular/core';
import { NIZHNY_NOVGOROD, type City, type Landmark } from '../../data/nizhny-novgorod';
@Injectable({
providedIn: 'root',
})
export class CityCatalogService {
readonly city: City = NIZHNY_NOVGOROD;
landmarkById(id: string): Landmark | undefined {
return this.city.objects.find((item) => item.id === id);
}
}
+62
View File
@@ -0,0 +1,62 @@
import { Injectable, inject } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { catchError, map, mergeMap, of, switchMap } from 'rxjs';
import { AreasApiService } from '../areas/areas-api.service';
import { authErrorMessage } from '../auth/auth-error';
import { GorodarActions } from './gorodar.actions';
@Injectable()
export class AreasEffects {
private readonly actions$ = inject(Actions);
private readonly api = inject(AreasApiService);
readonly loadAreas$ = createEffect(() =>
this.actions$.pipe(
ofType(GorodarActions.areasRequested),
switchMap(() =>
this.api.getAreas().pipe(
map((areas) => GorodarActions.areasLoaded({ areas })),
catchError((error: unknown) =>
of(GorodarActions.areasFailed({ error: authErrorMessage(error) })),
),
),
),
),
);
readonly loadArea$ = createEffect(() =>
this.actions$.pipe(
ofType(GorodarActions.areaRequested),
mergeMap(({ id }) =>
this.api.getArea(id).pipe(
map((area) => GorodarActions.areaLoaded({ area })),
catchError((error: unknown) =>
of(GorodarActions.areaFailed({ id, error: authErrorMessage(error) })),
),
),
),
),
);
readonly loadAttraction$ = createEffect(() =>
this.actions$.pipe(
ofType(GorodarActions.attractionRequested),
mergeMap(({ id }) =>
this.api.getAttraction(id).pipe(
map((attraction) => GorodarActions.attractionLoaded({ attraction })),
catchError((error: unknown) =>
of(GorodarActions.attractionFailed({ id, error: authErrorMessage(error) })),
),
),
),
),
);
readonly reloadAreas$ = createEffect(() =>
this.actions$.pipe(
ofType(GorodarActions.authCodeConfirmSucceeded, GorodarActions.logout),
map(() => GorodarActions.areasRequested()),
),
);
}
+20 -1
View File
@@ -1,5 +1,8 @@
import { createActionGroup, emptyProps, props } from '@ngrx/store'; import { createActionGroup, emptyProps, props } from '@ngrx/store';
import type { Area, AreaDetails, AreaProgress, AttractionDetails } from '../areas/area.models';
import type { ClaimFailure } from './gorodar.models';
export const GorodarActions = createActionGroup({ export const GorodarActions = createActionGroup({
source: 'Gorodar', source: 'Gorodar',
events: { events: {
@@ -7,7 +10,14 @@ export const GorodarActions = createActionGroup({
'Photo Captured': props<{ landmarkId: string; photo: string }>(), 'Photo Captured': props<{ landmarkId: string; photo: string }>(),
'Photo Cancelled': emptyProps(), 'Photo Cancelled': emptyProps(),
'Claim Step Changed': props<{ step: number }>(), 'Claim Step Changed': props<{ step: number }>(),
'Claim Completed': props<{ landmarkId: string; photo: string; collectedAt: string }>(), 'Claim Completed': props<{
landmarkId: string;
photo: string;
collectedAt: string;
alreadyVisited: boolean;
progress: AreaProgress;
}>(),
'Claim Failed': props<{ failure: ClaimFailure; confidence: number | null }>(),
'Claim Reset': emptyProps(), 'Claim Reset': emptyProps(),
'Auth Sheet Opened': props<{ intent: 'claim' | 'collection'; landmarkId?: string }>(), 'Auth Sheet Opened': props<{ intent: 'claim' | 'collection'; landmarkId?: string }>(),
'Auth Sheet Dismissed': emptyProps(), 'Auth Sheet Dismissed': emptyProps(),
@@ -28,5 +38,14 @@ export const GorodarActions = createActionGroup({
'Auth Code Confirm Failed': props<{ error: string }>(), 'Auth Code Confirm Failed': props<{ error: string }>(),
'Auth Resend Ticked': props<{ seconds: number }>(), 'Auth Resend Ticked': props<{ seconds: number }>(),
Logout: emptyProps(), Logout: emptyProps(),
'Areas Requested': emptyProps(),
'Areas Loaded': props<{ areas: Area[] }>(),
'Areas Failed': props<{ error: string }>(),
'Area Requested': props<{ id: string }>(),
'Area Loaded': props<{ area: AreaDetails }>(),
'Area Failed': props<{ id: string; error: string }>(),
'Attraction Requested': props<{ id: string }>(),
'Attraction Loaded': props<{ attraction: AttractionDetails }>(),
'Attraction Failed': props<{ id: string; error: string }>(),
}, },
}); });
+71 -14
View File
@@ -1,14 +1,33 @@
import { inject, Injectable } from '@angular/core'; import { inject, Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects'; import { Actions, createEffect, ofType } from '@ngrx/effects';
import { catchError, concat, delay, exhaustMap, from, map, of, switchMap, takeUntil } from 'rxjs'; import {
catchError,
EMPTY,
exhaustMap,
from,
map,
merge,
of,
shareReplay,
switchMap,
take,
takeUntil,
timer,
} from 'rxjs';
import { AreasApiService } from '../areas/areas-api.service';
import type { VisitResult } from '../areas/area.models';
import { resizePhoto } from '../areas/resize-photo';
import { CameraService } from '../root/services/camera.service'; import { CameraService } from '../root/services/camera.service';
import { GorodarActions } from './gorodar.actions'; import { GorodarActions } from './gorodar.actions';
const COMPARE_MS = 6_000;
@Injectable() @Injectable()
export class GorodarEffects { export class GorodarEffects {
private readonly actions$ = inject(Actions); private readonly actions$ = inject(Actions);
private readonly camera = inject(CameraService); private readonly camera = inject(CameraService);
private readonly areasApi = inject(AreasApiService);
readonly takePhoto$ = createEffect(() => readonly takePhoto$ = createEffect(() =>
this.actions$.pipe( this.actions$.pipe(
@@ -29,19 +48,57 @@ export class GorodarEffects {
readonly runCheck$ = createEffect(() => readonly runCheck$ = createEffect(() =>
this.actions$.pipe( this.actions$.pipe(
ofType(GorodarActions.photoCaptured), ofType(GorodarActions.photoCaptured),
switchMap(({ landmarkId, photo }) => switchMap(({ landmarkId, photo }) => {
concat( const visit$ = from(resizePhoto(photo)).pipe(
of(GorodarActions.claimStepChanged({ step: 2 })).pipe(delay(6_000)), switchMap((file) => this.areasApi.visit(landmarkId, file)),
of(GorodarActions.claimStepChanged({ step: 3 })).pipe(delay(3_000)), takeUntil(this.actions$.pipe(ofType(GorodarActions.claimReset))),
of( shareReplay({ bufferSize: 1, refCount: false }),
GorodarActions.claimCompleted({ );
landmarkId,
photo, const answered$ = visit$.pipe(
collectedAt: new Date().toISOString(), take(1),
}), catchError(() => of(null)),
).pipe(delay(1_000)), );
).pipe(takeUntil(this.actions$.pipe(ofType(GorodarActions.claimReset)))),
), return merge(
timer(COMPARE_MS).pipe(
map(() => GorodarActions.claimStepChanged({ step: 2 })),
takeUntil(answered$),
),
visit$.pipe(
take(1),
switchMap((result) => this.finishVisit(landmarkId, photo, result)),
catchError(() => of(GorodarActions.claimFailed({ failure: 'not_matched', confidence: null }))),
),
).pipe(takeUntil(this.actions$.pipe(ofType(GorodarActions.claimReset))));
}),
), ),
); );
private finishVisit(landmarkId: string, photo: string, result: VisitResult) {
if (result.status !== 'VISITED' && result.status !== 'ALREADY_VISITED') {
return of(
GorodarActions.claimFailed({
failure: result.status === 'UNCERTAIN' ? 'uncertain' : 'not_matched',
confidence: result.confidence,
}),
);
}
const completed = GorodarActions.claimCompleted({
landmarkId,
photo,
collectedAt: new Date().toISOString(),
alreadyVisited: result.status === 'ALREADY_VISITED',
progress: result.progress,
});
return merge(
of(GorodarActions.claimStepChanged({ step: 3 }), completed),
this.areasApi.getAttraction(landmarkId).pipe(
map((attraction) => GorodarActions.attractionLoaded({ attraction })),
catchError(() => EMPTY),
),
);
}
} }
+15 -1
View File
@@ -1,12 +1,17 @@
import type { Area, AreaDetails, AreasStatus, AttractionDetails } from '../areas/area.models';
import type { AuthIntent, AuthSession, AuthStep } from '../auth/auth.models'; import type { AuthIntent, AuthSession, AuthStep } from '../auth/auth.models';
export type ClaimStage = 'idle' | 'check' | 'success'; export type ClaimStage = 'idle' | 'check' | 'success' | 'failed';
export type ClaimFailure = 'not_matched' | 'uncertain';
export interface ClaimState { export interface ClaimState {
landmarkId: string | null; landmarkId: string | null;
photo: string | null; photo: string | null;
stage: ClaimStage; stage: ClaimStage;
step: number; step: number;
failure: ClaimFailure | null;
confidence: number | null;
alreadyVisited: boolean;
} }
export interface ProfileState { export interface ProfileState {
@@ -43,6 +48,15 @@ export interface GorodarState {
claim: ClaimState; claim: ClaimState;
profile: ProfileState; profile: ProfileState;
auth: AuthState; auth: AuthState;
areas: Area[];
areasStatus: AreasStatus;
areasError: string;
areaDetails: Record<string, AreaDetails>;
areaDetailStatus: Record<string, AreasStatus>;
areaDetailError: Record<string, string>;
attractions: Record<string, AttractionDetails>;
attractionStatus: Record<string, AreasStatus>;
attractionError: Record<string, string>;
} }
export const RESEND_SECONDS = 60; export const RESEND_SECONDS = 60;
+212 -18
View File
@@ -1,5 +1,12 @@
import { createFeature, createReducer, on } from '@ngrx/store'; import { createFeature, createReducer, on } from '@ngrx/store';
import {
areaAttractions,
type AreaDetails,
type AreaProgress,
type Attraction,
type AttractionDetails,
} from '../areas/area.models';
import { readAuthSession } from '../auth/auth-session'; import { readAuthSession } from '../auth/auth-session';
import { GorodarActions } from './gorodar.actions'; import { GorodarActions } from './gorodar.actions';
import { RESEND_SECONDS, sessionToAuth, type AuthState, type ClaimState, type GorodarState } from './gorodar.models'; import { RESEND_SECONDS, sessionToAuth, type AuthState, type ClaimState, type GorodarState } from './gorodar.models';
@@ -8,7 +15,10 @@ const initialClaim: ClaimState = {
landmarkId: null, landmarkId: null,
photo: null, photo: null,
stage: 'idle', stage: 'idle',
step: 1, step: 0,
failure: null,
confidence: null,
alreadyVisited: false,
}; };
const blankAuth: AuthState = { const blankAuth: AuthState = {
@@ -46,6 +56,15 @@ export const initialState: GorodarState = {
phone: '+7 900 123-45-67', phone: '+7 900 123-45-67',
joinedLabel: 'Сентябрь 2026', joinedLabel: 'Сентябрь 2026',
}, },
areas: [],
areasStatus: 'loading',
areasError: '',
areaDetails: {},
areaDetailStatus: {},
areaDetailError: {},
attractions: {},
attractionStatus: {},
attractionError: {},
}; };
const gorodarReducer = createReducer( const gorodarReducer = createReducer(
@@ -54,27 +73,19 @@ const gorodarReducer = createReducer(
GorodarActions.photoCaptured, GorodarActions.photoCaptured,
(state, { landmarkId, photo }): GorodarState => ({ (state, { landmarkId, photo }): GorodarState => ({
...state, ...state,
claim: { claim: { ...initialClaim, landmarkId, photo, stage: 'check', step: 1 },
landmarkId,
photo,
stage: 'check',
step: 1,
},
}), }),
), ),
on( on(
GorodarActions.claimStepChanged, GorodarActions.claimStepChanged,
(state, { step }): GorodarState => ({ (state, { step }): GorodarState => ({
...state, ...state,
claim: { claim: { ...state.claim, step },
...state.claim,
step,
},
}), }),
), ),
on( on(
GorodarActions.claimCompleted, GorodarActions.claimCompleted,
(state, { landmarkId, photo, collectedAt }): GorodarState => ({ (state, { landmarkId, photo, collectedAt, alreadyVisited, progress }): GorodarState => ({
...state, ...state,
collectedIds: state.collectedIds.includes(landmarkId) collectedIds: state.collectedIds.includes(landmarkId)
? state.collectedIds ? state.collectedIds
@@ -87,12 +98,16 @@ const gorodarReducer = createReducer(
...state.collectedAt, ...state.collectedAt,
[landmarkId]: collectedAt, [landmarkId]: collectedAt,
}, },
claim: { areaDetails: markAreaVisited(state.areaDetails, landmarkId, progress),
landmarkId, attractions: markAttractionVisited(state.attractions, landmarkId),
photo, claim: { ...initialClaim, landmarkId, photo, stage: 'success', step: 3, alreadyVisited },
stage: 'success', }),
step: 3, ),
}, on(
GorodarActions.claimFailed,
(state, { failure, confidence }): GorodarState => ({
...state,
claim: { ...state.claim, stage: 'failed', failure, confidence },
}), }),
), ),
on( on(
@@ -253,15 +268,194 @@ const gorodarReducer = createReducer(
GorodarActions.logout, GorodarActions.logout,
(state): GorodarState => ({ (state): GorodarState => ({
...state, ...state,
collectedIds: [],
photos: {},
collectedAt: {},
claim: initialClaim,
auth: blankAuth, auth: blankAuth,
profile: { profile: {
...state.profile, ...state.profile,
email: '', email: '',
}, },
areaDetails: {},
areaDetailStatus: {},
areaDetailError: {},
attractions: {},
attractionStatus: {},
attractionError: {},
}),
),
on(
GorodarActions.areasRequested,
(state): GorodarState => ({
...state,
areasStatus: 'loading',
areasError: '',
}),
),
on(
GorodarActions.areasLoaded,
(state, { areas }): GorodarState => ({
...state,
areas,
areasStatus: 'ready',
areasError: '',
}),
),
on(
GorodarActions.areasFailed,
(state, { error }): GorodarState => ({
...state,
areasStatus: 'error',
areasError: error,
}),
),
on(
GorodarActions.areaRequested,
(state, { id }): GorodarState => ({
...state,
areaDetailStatus: {
...state.areaDetailStatus,
[id]: 'loading',
},
areaDetailError: {
...state.areaDetailError,
[id]: '',
},
}),
),
on(
GorodarActions.areaLoaded,
(state, { area }): GorodarState => ({
...state,
areaDetails: {
...state.areaDetails,
[area.id]: area,
},
areaDetailStatus: {
...state.areaDetailStatus,
[area.id]: 'ready',
},
areaDetailError: {
...state.areaDetailError,
[area.id]: '',
},
}),
),
on(
GorodarActions.areaFailed,
(state, { id, error }): GorodarState => ({
...state,
areaDetailStatus: {
...state.areaDetailStatus,
[id]: 'error',
},
areaDetailError: {
...state.areaDetailError,
[id]: error,
},
}),
),
on(
GorodarActions.attractionRequested,
(state, { id }): GorodarState => ({
...state,
attractionStatus: {
...state.attractionStatus,
[id]: 'loading',
},
attractionError: {
...state.attractionError,
[id]: '',
},
}),
),
on(
GorodarActions.attractionLoaded,
(state, { attraction }): GorodarState => ({
...state,
attractions: {
...state.attractions,
[attraction.id]: attraction,
},
attractionStatus: {
...state.attractionStatus,
[attraction.id]: 'ready',
},
attractionError: {
...state.attractionError,
[attraction.id]: '',
},
}),
),
on(
GorodarActions.attractionFailed,
(state, { id, error }): GorodarState => ({
...state,
attractionStatus: {
...state.attractionStatus,
[id]: 'error',
},
attractionError: {
...state.attractionError,
[id]: error,
},
}), }),
), ),
); );
function markVisited(item: Attraction, id: string): Attraction {
return item.id === id ? { ...item, visited: true } : item;
}
function markAreaVisited(
details: Record<string, AreaDetails>,
landmarkId: string,
progress: AreaProgress,
): Record<string, AreaDetails> {
return Object.fromEntries(
Object.entries(details).map(([id, area]) => {
const contains = areaAttractions(area).some((item) => item.id === landmarkId);
if (!contains) {
return [id, area];
}
return [
id,
{
...area,
progress: progress ?? area.progress,
attractions: area.attractions.map((item) => markVisited(item, landmarkId)),
children: area.children.map((child) => ({
...child,
attractions: child.attractions.map((item) => markVisited(item, landmarkId)),
})),
},
];
}),
);
}
function markAttractionVisited(
attractions: Record<string, AttractionDetails>,
landmarkId: string,
): Record<string, AttractionDetails> {
const current = attractions[landmarkId];
if (!current) {
return attractions;
}
return {
...attractions,
[landmarkId]: {
...current,
visited: true,
},
};
}
export const gorodarFeature = createFeature({ export const gorodarFeature = createFeature({
name: 'gorodar', name: 'gorodar',
reducer: gorodarReducer, reducer: gorodarReducer,
+24 -10
View File
@@ -1,6 +1,6 @@
import { createSelector } from '@ngrx/store'; import { createSelector } from '@ngrx/store';
import { NIZHNY_NOVGOROD } from '../data/nizhny-novgorod'; import { areaOpenedCount, areaTotalCount, type Area, type AreaDetails } from '../areas/area.models';
import { gorodarFeature } from './gorodar.reducer'; import { gorodarFeature } from './gorodar.reducer';
export const { export const {
@@ -10,19 +10,37 @@ export const {
selectClaim, selectClaim,
selectProfile, selectProfile,
selectAuth, selectAuth,
selectAreas,
selectAreasStatus,
selectAreasError,
selectAreaDetails,
selectAreaDetailStatus,
selectAreaDetailError,
selectAttractions,
selectAttractionStatus,
selectAttractionError,
} = gorodarFeature; } = gorodarFeature;
export const selectCollectedIdSet = createSelector(selectCollectedIds, (ids) => new Set(ids)); export const selectCollectedIdSet = createSelector(selectCollectedIds, (ids) => new Set(ids));
export const selectTotalCount = NIZHNY_NOVGOROD.objects.length;
export const selectOpenedCount = createSelector( export const selectOpenedCount = createSelector(
selectAreas,
selectAreaDetails,
selectCollectedIdSet, selectCollectedIdSet,
(ids) => NIZHNY_NOVGOROD.objects.filter((item) => ids.has(item.id) || item.collected).length, (areas, details, ids) =>
areas.reduce((sum, area) => sum + areaOpenedCount(resolveArea(area, details), ids), 0),
); );
export const selectProgress = createSelector(selectOpenedCount, (opened) => export const selectTotalCount = createSelector(selectAreas, selectAreaDetails, (areas, details) =>
Math.round((opened / selectTotalCount) * 100), areas.reduce((sum, area) => sum + areaTotalCount(resolveArea(area, details)), 0),
);
function resolveArea(area: Area, details: Record<string, AreaDetails>): Area | AreaDetails {
return details[area.id] ?? area;
}
export const selectProgress = createSelector(selectOpenedCount, selectTotalCount, (opened, total) =>
total ? Math.round((opened / total) * 100) : 0,
); );
export const selectAuthenticated = createSelector(selectAuth, (auth) => auth.authenticated); export const selectAuthenticated = createSelector(selectAuth, (auth) => auth.authenticated);
@@ -34,7 +52,3 @@ export const selectAuthResendSeconds = createSelector(selectAuth, (auth) => auth
export const selectAuthSheetVisible = createSelector(selectAuth, (auth) => auth.sheetVisible); export const selectAuthSheetVisible = createSelector(selectAuth, (auth) => auth.sheetVisible);
export const selectAuthIntent = createSelector(selectAuth, (auth) => auth.intent); export const selectAuthIntent = createSelector(selectAuth, (auth) => auth.intent);
export const selectAuthCodeRequestId = createSelector(selectAuth, (auth) => auth.codeRequestId); export const selectAuthCodeRequestId = createSelector(selectAuth, (auth) => auth.codeRequestId);
export const selectClaimPhoto = createSelector(selectClaim, (claim) => claim.photo);
export const selectClaimStage = createSelector(selectClaim, (claim) => claim.stage);
export const selectClaimStep = createSelector(selectClaim, (claim) => claim.step);
+1
View File
@@ -1,4 +1,5 @@
export { GorodarActions } from './gorodar.actions'; export { GorodarActions } from './gorodar.actions';
export { AreasEffects } from './areas.effects';
export { AuthEffects } from './auth.effects'; export { AuthEffects } from './auth.effects';
export { GorodarEffects } from './gorodar.effects'; export { GorodarEffects } from './gorodar.effects';
export { gorodarFeature, initialState } from './gorodar.reducer'; export { gorodarFeature, initialState } from './gorodar.reducer';
+4
View File
@@ -9,6 +9,10 @@ export const endpoints = {
authorize: `${API_URL}/oauth2/authorize`, authorize: `${API_URL}/oauth2/authorize`,
token: `${API_URL}/oauth2/token`, token: `${API_URL}/oauth2/token`,
}, },
areas: `${API_URL}/api/areas`,
area: (id: string) => `${API_URL}/api/areas/${id}`,
attraction: (id: string) => `${API_URL}/api/attractions/${id}`,
visit: (id: string) => `${API_URL}/api/attractions/${id}/visits`,
} as const; } as const;
export const grants = { export const grants = {
+1 -1
View File
@@ -1,4 +1,4 @@
export const environment = { export const environment = {
production: true, production: true,
apiUrl: '', apiUrl: 'https://gorodar.ru',
}; };
+1 -1
View File
@@ -1,4 +1,4 @@
export const environment = { export const environment = {
production: false, production: false,
apiUrl: '', apiUrl: 'https://gorodar.ru',
}; };
-1
View File
@@ -24,6 +24,5 @@
</head> </head>
<body> <body>
<app-root></app-root> <app-root></app-root>
<noscript>Чтобы пользоваться Городаром, включите JavaScript.</noscript>
</body> </body>
</html> </html>