first commit
This commit is contained in:
22
libs/web/identity/application/README.md
Normal file
22
libs/web/identity/application/README.md
Normal file
@@ -0,0 +1,22 @@
|
||||
# web-identity-application
|
||||
|
||||
Estado de autenticación (NgRx Signals con eventos) detrás de una facade.
|
||||
|
||||
- **Import**: `@task-stream/web/identity/application`
|
||||
- **Capa**: `application` · **Tags**: `scope:web-identity`, `type:application`
|
||||
|
||||
## Contenido
|
||||
|
||||
- `AuthFacade` (lo único que se exporta, junto al tipo `AuthStatus`): sesión y usuario como señales; `signInWith*()`,
|
||||
`completeSignIn()`, `signOut()`, `validAccessToken()`.
|
||||
- Interno: `AuthStore` (login con PKCE o email y contraseña de Pireon; restaura la sesión al arrancar y renueva el
|
||||
token) y eventos `authPageEvents`, `authApiEvents`, `sessionEvents`.
|
||||
|
||||
## Comandos
|
||||
|
||||
```sh
|
||||
npx nx lint web-identity-application
|
||||
npx nx test web-identity-application # Vitest
|
||||
```
|
||||
|
||||
Reglas de dependencia entre capas: [Arquitectura](../../../../docs/02-arquitectura.md#21-capas-hexagonales).
|
||||
34
libs/web/identity/application/eslint.config.mjs
Normal file
34
libs/web/identity/application/eslint.config.mjs
Normal file
@@ -0,0 +1,34 @@
|
||||
import nx from '@nx/eslint-plugin';
|
||||
import baseConfig from '../../../../eslint.config.mjs';
|
||||
|
||||
export default [
|
||||
...nx.configs['flat/angular'],
|
||||
...nx.configs['flat/angular-template'],
|
||||
...baseConfig,
|
||||
{
|
||||
files: ['**/*.ts'],
|
||||
rules: {
|
||||
'@angular-eslint/directive-selector': [
|
||||
'error',
|
||||
{
|
||||
type: 'attribute',
|
||||
prefix: 'ts',
|
||||
style: 'camelCase',
|
||||
},
|
||||
],
|
||||
'@angular-eslint/component-selector': [
|
||||
'error',
|
||||
{
|
||||
type: 'element',
|
||||
prefix: 'ts',
|
||||
style: 'kebab-case',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['**/*.html'],
|
||||
// Override or add rules here
|
||||
rules: {},
|
||||
},
|
||||
];
|
||||
20
libs/web/identity/application/project.json
Normal file
20
libs/web/identity/application/project.json
Normal file
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"name": "web-identity-application",
|
||||
"$schema": "../../../../node_modules/nx/schemas/project-schema.json",
|
||||
"sourceRoot": "libs/web/identity/application/src",
|
||||
"prefix": "ts",
|
||||
"projectType": "library",
|
||||
"tags": ["scope:web-identity", "type:application"],
|
||||
"targets": {
|
||||
"test": {
|
||||
"executor": "@nx/vitest:test",
|
||||
"outputs": ["{options.reportsDirectory}"],
|
||||
"options": {
|
||||
"reportsDirectory": "coverage/libs/web/identity/application"
|
||||
}
|
||||
},
|
||||
"lint": {
|
||||
"executor": "@nx/eslint:lint"
|
||||
}
|
||||
}
|
||||
}
|
||||
2
libs/web/identity/application/src/index.ts
Normal file
2
libs/web/identity/application/src/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export * from './lib/auth.facade';
|
||||
export type { AuthStatus } from './lib/auth.store';
|
||||
51
libs/web/identity/application/src/lib/auth.events.ts
Normal file
51
libs/web/identity/application/src/lib/auth.events.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import { type } from '@ngrx/signals';
|
||||
import { eventGroup } from '@ngrx/signals/events';
|
||||
import {
|
||||
AuthConfig,
|
||||
CurrentUser,
|
||||
Session,
|
||||
} from '@task-stream/web/identity/domain';
|
||||
|
||||
/** What the user does on the sign-in screens. */
|
||||
export const authPageEvents = eventGroup({
|
||||
source: 'Auth Page',
|
||||
events: {
|
||||
opened: type<void>(),
|
||||
signInWithPireon: type<{ returnUrl: string }>(),
|
||||
signInWithPassword: type<{
|
||||
username: string;
|
||||
password: string;
|
||||
returnUrl: string;
|
||||
}>(),
|
||||
callbackReceived: type<{ query: string }>(),
|
||||
},
|
||||
});
|
||||
|
||||
/** Anywhere in the app. */
|
||||
export const sessionEvents = eventGroup({
|
||||
source: 'Session',
|
||||
events: {
|
||||
signOutRequested: type<void>(),
|
||||
/** The API rejected the token (expired / revoked / user deactivated). */
|
||||
expired: type<void>(),
|
||||
},
|
||||
});
|
||||
|
||||
/** Results of talking to the API / identity server. */
|
||||
export const authApiEvents = eventGroup({
|
||||
source: 'Auth API',
|
||||
events: {
|
||||
configLoaded: type<AuthConfig | null>(),
|
||||
signedIn: type<{
|
||||
session: Session;
|
||||
user: CurrentUser;
|
||||
returnUrl: string;
|
||||
}>(),
|
||||
signInFailed: type<string>(),
|
||||
sessionRestored: type<{ session: Session; user: CurrentUser }>(),
|
||||
sessionRefreshed: type<Session>(),
|
||||
signedOut: type<void>(),
|
||||
/** Startup without a usable stored session (no redirect: guards decide). */
|
||||
anonymous: type<void>(),
|
||||
},
|
||||
});
|
||||
65
libs/web/identity/application/src/lib/auth.facade.ts
Normal file
65
libs/web/identity/application/src/lib/auth.facade.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
import { computed, inject, Injectable } from '@angular/core';
|
||||
import { injectDispatch } from '@ngrx/signals/events';
|
||||
import { authPageEvents, sessionEvents } from './auth.events';
|
||||
import { AuthStore } from './auth.store';
|
||||
|
||||
/**
|
||||
* Entry point to the session for presenters (and other contexts): read state
|
||||
* as signals, express intentions as methods. Behind it, each method dispatches
|
||||
* an event that the `AuthStore` reduces and handles.
|
||||
*/
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class AuthFacade {
|
||||
private readonly store = inject(AuthStore);
|
||||
private readonly page = injectDispatch(authPageEvents);
|
||||
private readonly session = injectDispatch(sessionEvents);
|
||||
|
||||
readonly status = this.store.status;
|
||||
readonly user = this.store.user;
|
||||
/** undefined = not loaded yet, null = only personal access tokens. */
|
||||
readonly config = this.store.config;
|
||||
readonly error = this.store.error;
|
||||
readonly isAuthenticated = this.store.isAuthenticated;
|
||||
readonly initials = this.store.initials;
|
||||
readonly signingIn = computed(() => this.store.status() === 'signing-in');
|
||||
/** False until the stored session has been restored (or discarded). */
|
||||
readonly settled = computed(
|
||||
() => !['restoring', 'signing-in'].includes(this.store.status()),
|
||||
);
|
||||
|
||||
/** The sign-in screen opened: loads how the API lets users sign in. */
|
||||
openSignIn(): void {
|
||||
this.page.opened();
|
||||
}
|
||||
|
||||
signInWithPireon(returnUrl: string): void {
|
||||
this.page.signInWithPireon({ returnUrl });
|
||||
}
|
||||
|
||||
signInWithPassword(
|
||||
username: string,
|
||||
password: string,
|
||||
returnUrl: string,
|
||||
): void {
|
||||
this.page.signInWithPassword({ username, password, returnUrl });
|
||||
}
|
||||
|
||||
/** Back from Pireon with `?code=…&state=…`. */
|
||||
completeSignIn(query: string): void {
|
||||
this.page.callbackReceived({ query });
|
||||
}
|
||||
|
||||
signOut(): void {
|
||||
this.session.signOutRequested();
|
||||
}
|
||||
|
||||
/** A valid access token for API calls, refreshed when about to expire. */
|
||||
validAccessToken(): Promise<string | null> {
|
||||
return this.store.validAccessToken();
|
||||
}
|
||||
|
||||
/** The API rejected the token. */
|
||||
expire(): void {
|
||||
this.store.expire();
|
||||
}
|
||||
}
|
||||
289
libs/web/identity/application/src/lib/auth.store.ts
Normal file
289
libs/web/identity/application/src/lib/auth.store.ts
Normal file
@@ -0,0 +1,289 @@
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { computed, inject } from '@angular/core';
|
||||
import { Router } from '@angular/router';
|
||||
import { mapResponse } from '@ngrx/operators';
|
||||
import {
|
||||
signalStore,
|
||||
withComputed,
|
||||
withHooks,
|
||||
withMethods,
|
||||
withState,
|
||||
} from '@ngrx/signals';
|
||||
import {
|
||||
Dispatcher,
|
||||
Events,
|
||||
on,
|
||||
withEventHandlers,
|
||||
withReducer,
|
||||
} from '@ngrx/signals/events';
|
||||
import {
|
||||
AuthConfig,
|
||||
AuthGateway,
|
||||
AuthorizationFlow,
|
||||
CurrentUser,
|
||||
isExpired,
|
||||
ProfileGateway,
|
||||
Session,
|
||||
SessionStorage,
|
||||
} from '@task-stream/web/identity/domain';
|
||||
import { exhaustMap, firstValueFrom, from, map, switchMap, tap } from 'rxjs';
|
||||
import { authApiEvents, authPageEvents, sessionEvents } from './auth.events';
|
||||
|
||||
export type AuthStatus =
|
||||
| 'restoring'
|
||||
| 'anonymous'
|
||||
| 'signing-in'
|
||||
| 'authenticated';
|
||||
|
||||
interface AuthState {
|
||||
status: AuthStatus;
|
||||
session: Session | null;
|
||||
user: CurrentUser | null;
|
||||
/** undefined = not loaded yet, null = only personal access tokens. */
|
||||
config: AuthConfig | null | undefined;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
const initialState: AuthState = {
|
||||
status: 'restoring',
|
||||
session: null,
|
||||
user: null,
|
||||
config: undefined,
|
||||
error: null,
|
||||
};
|
||||
|
||||
function describe(error: unknown): string {
|
||||
if (error instanceof HttpErrorResponse) {
|
||||
return (
|
||||
(error.error as { message?: string } | null)?.message ?? error.message
|
||||
);
|
||||
}
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
export const AuthStore = signalStore(
|
||||
{ providedIn: 'root' },
|
||||
withState(initialState),
|
||||
withComputed(({ status, user }) => ({
|
||||
isAuthenticated: computed(() => status() === 'authenticated'),
|
||||
initials: computed(() =>
|
||||
(user()?.name ?? '')
|
||||
.split(/\s+/)
|
||||
.map((part) => part[0])
|
||||
.join('')
|
||||
.slice(0, 2)
|
||||
.toUpperCase(),
|
||||
),
|
||||
})),
|
||||
withReducer(
|
||||
on(authApiEvents.configLoaded, ({ payload }) => ({ config: payload })),
|
||||
on(
|
||||
authPageEvents.signInWithPassword,
|
||||
authPageEvents.signInWithPireon,
|
||||
authPageEvents.callbackReceived,
|
||||
() => ({ status: 'signing-in' as const, error: null }),
|
||||
),
|
||||
on(
|
||||
authApiEvents.signedIn,
|
||||
authApiEvents.sessionRestored,
|
||||
({ payload }) => ({
|
||||
status: 'authenticated' as const,
|
||||
session: payload.session,
|
||||
user: payload.user,
|
||||
error: null,
|
||||
}),
|
||||
),
|
||||
on(authApiEvents.sessionRefreshed, ({ payload }) => ({ session: payload })),
|
||||
on(authApiEvents.signInFailed, ({ payload }) => ({
|
||||
status: 'anonymous' as const,
|
||||
session: null,
|
||||
user: null,
|
||||
error: payload,
|
||||
})),
|
||||
on(authApiEvents.signedOut, authApiEvents.anonymous, () => ({
|
||||
status: 'anonymous' as const,
|
||||
session: null,
|
||||
user: null,
|
||||
})),
|
||||
),
|
||||
withEventHandlers(
|
||||
(
|
||||
store,
|
||||
events = inject(Events),
|
||||
auth = inject(AuthGateway),
|
||||
profile = inject(ProfileGateway),
|
||||
flow = inject(AuthorizationFlow),
|
||||
storage = inject(SessionStorage),
|
||||
router = inject(Router),
|
||||
) => {
|
||||
/** Token → who is it → signed in. */
|
||||
const signIn = (
|
||||
session$: ReturnType<AuthGateway['password']>,
|
||||
returnUrl: string,
|
||||
) =>
|
||||
session$.pipe(
|
||||
switchMap((session) =>
|
||||
profile
|
||||
.me(session.accessToken)
|
||||
.pipe(map((user) => ({ session, user }))),
|
||||
),
|
||||
mapResponse({
|
||||
next: ({ session, user }) =>
|
||||
authApiEvents.signedIn({ session, user, returnUrl }),
|
||||
error: (error) => authApiEvents.signInFailed(describe(error)),
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
loadConfig$: events.on(authPageEvents.opened).pipe(
|
||||
exhaustMap(() =>
|
||||
auth.config().pipe(
|
||||
mapResponse({
|
||||
next: (config) => authApiEvents.configLoaded(config),
|
||||
error: () => authApiEvents.configLoaded(null),
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
redirectToPireon$: events.on(authPageEvents.signInWithPireon).pipe(
|
||||
exhaustMap(({ payload }) => {
|
||||
const config = store.config();
|
||||
if (!config)
|
||||
return [
|
||||
authApiEvents.signInFailed(
|
||||
'Pireon sign-in is not configured on the API',
|
||||
),
|
||||
];
|
||||
return from(flow.start(config, payload.returnUrl)).pipe(
|
||||
map(() => null),
|
||||
);
|
||||
}),
|
||||
),
|
||||
password$: events
|
||||
.on(authPageEvents.signInWithPassword)
|
||||
.pipe(
|
||||
exhaustMap(({ payload }) =>
|
||||
signIn(
|
||||
auth.password(payload.username, payload.password),
|
||||
payload.returnUrl,
|
||||
),
|
||||
),
|
||||
),
|
||||
callback$: events.on(authPageEvents.callbackReceived).pipe(
|
||||
exhaustMap(({ payload }) => {
|
||||
try {
|
||||
const response = flow.complete(
|
||||
new URLSearchParams(payload.query),
|
||||
);
|
||||
return signIn(
|
||||
auth.exchangeCode(
|
||||
response.code,
|
||||
response.codeVerifier,
|
||||
response.redirectUri,
|
||||
),
|
||||
response.returnUrl,
|
||||
);
|
||||
} catch (error) {
|
||||
return [authApiEvents.signInFailed(describe(error))];
|
||||
}
|
||||
}),
|
||||
),
|
||||
persist$: events
|
||||
.on(authApiEvents.signedIn, authApiEvents.sessionRefreshed)
|
||||
.pipe(
|
||||
tap(() => {
|
||||
const session = store.session();
|
||||
if (session) storage.save(session);
|
||||
}),
|
||||
),
|
||||
navigateIn$: events
|
||||
.on(authApiEvents.signedIn)
|
||||
.pipe(
|
||||
tap(
|
||||
({ payload }) =>
|
||||
void router.navigateByUrl(payload.returnUrl || '/'),
|
||||
),
|
||||
),
|
||||
signOut$: events
|
||||
.on(sessionEvents.signOutRequested, sessionEvents.expired)
|
||||
.pipe(
|
||||
tap(() => storage.clear()),
|
||||
map(() => authApiEvents.signedOut()),
|
||||
),
|
||||
navigateOut$: events
|
||||
.on(authApiEvents.signedOut)
|
||||
.pipe(tap(() => void router.navigateByUrl('/login'))),
|
||||
};
|
||||
},
|
||||
),
|
||||
withMethods(
|
||||
(store, auth = inject(AuthGateway), dispatcher = inject(Dispatcher)) => {
|
||||
let refreshing: Promise<string | null> | null = null;
|
||||
|
||||
return {
|
||||
/**
|
||||
* A valid access token for API calls: refreshed when about to expire
|
||||
* (once, even if many requests ask at the same time).
|
||||
*/
|
||||
async validAccessToken(): Promise<string | null> {
|
||||
const session = store.session();
|
||||
if (!session) return null;
|
||||
if (!isExpired(session)) return session.accessToken;
|
||||
if (!session.refreshToken) {
|
||||
dispatcher.dispatch(sessionEvents.expired());
|
||||
return null;
|
||||
}
|
||||
refreshing ??= firstValueFrom(auth.refresh(session.refreshToken))
|
||||
.then((fresh) => {
|
||||
dispatcher.dispatch(authApiEvents.sessionRefreshed(fresh));
|
||||
return fresh.accessToken;
|
||||
})
|
||||
.catch(() => {
|
||||
dispatcher.dispatch(sessionEvents.expired());
|
||||
return null;
|
||||
})
|
||||
.finally(() => (refreshing = null));
|
||||
return refreshing;
|
||||
},
|
||||
expire(): void {
|
||||
if (store.status() === 'authenticated')
|
||||
dispatcher.dispatch(sessionEvents.expired());
|
||||
},
|
||||
};
|
||||
},
|
||||
),
|
||||
withHooks({
|
||||
/** Restores the stored session (and checks it is still accepted). */
|
||||
onInit(store) {
|
||||
const storage = inject(SessionStorage);
|
||||
const profile = inject(ProfileGateway);
|
||||
const dispatcher = inject(Dispatcher);
|
||||
const stored = storage.load();
|
||||
if (!stored) {
|
||||
dispatcher.dispatch(authApiEvents.anonymous());
|
||||
return;
|
||||
}
|
||||
// Seed the token so validAccessToken() can refresh it if needed.
|
||||
dispatcher.dispatch(authApiEvents.sessionRefreshed(stored));
|
||||
void store.validAccessToken().then((token) => {
|
||||
if (!token) {
|
||||
dispatcher.dispatch(authApiEvents.anonymous());
|
||||
return;
|
||||
}
|
||||
profile.me(token).subscribe({
|
||||
next: (user) =>
|
||||
dispatcher.dispatch(
|
||||
authApiEvents.sessionRestored({
|
||||
session: store.session() ?? stored,
|
||||
user,
|
||||
}),
|
||||
),
|
||||
error: () => {
|
||||
storage.clear();
|
||||
dispatcher.dispatch(authApiEvents.anonymous());
|
||||
},
|
||||
});
|
||||
});
|
||||
},
|
||||
}),
|
||||
);
|
||||
5
libs/web/identity/application/src/test-setup.ts
Normal file
5
libs/web/identity/application/src/test-setup.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
import '@angular/compiler';
|
||||
import '@analogjs/vitest-angular/setup-snapshots';
|
||||
import { setupTestBed } from '@analogjs/vitest-angular/setup-testbed';
|
||||
|
||||
setupTestBed();
|
||||
30
libs/web/identity/application/tsconfig.json
Normal file
30
libs/web/identity/application/tsconfig.json
Normal file
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"extends": "../../../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"isolatedModules": true,
|
||||
"target": "es2022",
|
||||
"strict": true,
|
||||
"noImplicitOverride": true,
|
||||
"noPropertyAccessFromIndexSignature": true,
|
||||
"noImplicitReturns": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"emitDecoratorMetadata": false,
|
||||
"module": "preserve"
|
||||
},
|
||||
"angularCompilerOptions": {
|
||||
"enableI18nLegacyMessageIdFormat": false,
|
||||
"strictInjectionParameters": true,
|
||||
"strictInputAccessModifiers": true,
|
||||
"strictTemplates": true
|
||||
},
|
||||
"files": [],
|
||||
"include": [],
|
||||
"references": [
|
||||
{
|
||||
"path": "./tsconfig.lib.json"
|
||||
},
|
||||
{
|
||||
"path": "./tsconfig.spec.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
26
libs/web/identity/application/tsconfig.lib.json
Normal file
26
libs/web/identity/application/tsconfig.lib.json
Normal file
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "../../../../dist/out-tsc",
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"inlineSources": true,
|
||||
"types": []
|
||||
},
|
||||
"include": ["src/**/*.ts"],
|
||||
"exclude": [
|
||||
"src/**/*.spec.ts",
|
||||
"src/**/*.test.ts",
|
||||
"vite.config.ts",
|
||||
"vite.config.mts",
|
||||
"vitest.config.ts",
|
||||
"vitest.config.mts",
|
||||
"src/**/*.test.tsx",
|
||||
"src/**/*.spec.tsx",
|
||||
"src/**/*.test.js",
|
||||
"src/**/*.spec.js",
|
||||
"src/**/*.test.jsx",
|
||||
"src/**/*.spec.jsx",
|
||||
"src/test-setup.ts"
|
||||
]
|
||||
}
|
||||
29
libs/web/identity/application/tsconfig.spec.json
Normal file
29
libs/web/identity/application/tsconfig.spec.json
Normal file
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "../../../../dist/out-tsc",
|
||||
"types": [
|
||||
"vitest/globals",
|
||||
"vitest/importMeta",
|
||||
"vite/client",
|
||||
"node",
|
||||
"vitest"
|
||||
]
|
||||
},
|
||||
"include": [
|
||||
"vite.config.ts",
|
||||
"vite.config.mts",
|
||||
"vitest.config.ts",
|
||||
"vitest.config.mts",
|
||||
"src/**/*.test.ts",
|
||||
"src/**/*.spec.ts",
|
||||
"src/**/*.test.tsx",
|
||||
"src/**/*.spec.tsx",
|
||||
"src/**/*.test.js",
|
||||
"src/**/*.spec.js",
|
||||
"src/**/*.test.jsx",
|
||||
"src/**/*.spec.jsx",
|
||||
"src/**/*.d.ts"
|
||||
],
|
||||
"files": ["src/test-setup.ts"]
|
||||
}
|
||||
29
libs/web/identity/application/vite.config.mts
Normal file
29
libs/web/identity/application/vite.config.mts
Normal file
@@ -0,0 +1,29 @@
|
||||
/// <reference types='vitest' />
|
||||
import { defineConfig } from 'vite';
|
||||
import angular from '@analogjs/vite-plugin-angular';
|
||||
import { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths.plugin';
|
||||
import { nxCopyAssetsPlugin } from '@nx/vite/plugins/nx-copy-assets.plugin';
|
||||
|
||||
export default defineConfig(() => ({
|
||||
root: import.meta.dirname,
|
||||
cacheDir: '../../../../node_modules/.vite/libs/web/identity/application',
|
||||
plugins: [angular(), nxViteTsPaths(), nxCopyAssetsPlugin(['*.md'])],
|
||||
// Uncomment this if you are using workers.
|
||||
// worker: {
|
||||
// plugins: () => [ nxViteTsPaths() ],
|
||||
// },
|
||||
test: {
|
||||
name: 'web-identity-application',
|
||||
watch: false,
|
||||
passWithNoTests: true,
|
||||
globals: true,
|
||||
environment: 'jsdom',
|
||||
include: ['{src,tests}/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],
|
||||
setupFiles: ['src/test-setup.ts'],
|
||||
reporters: ['default'],
|
||||
coverage: {
|
||||
reportsDirectory: '../../../../coverage/libs/web/identity/application',
|
||||
provider: 'v8' as const,
|
||||
},
|
||||
},
|
||||
}));
|
||||
20
libs/web/identity/domain/README.md
Normal file
20
libs/web/identity/domain/README.md
Normal file
@@ -0,0 +1,20 @@
|
||||
# web-identity-domain
|
||||
|
||||
Sesión y usuario en el navegador.
|
||||
|
||||
- **Import**: `@task-stream/web/identity/domain`
|
||||
- **Capa**: `domain` · **Tags**: `scope:web-identity`, `type:domain`
|
||||
|
||||
## Contenido
|
||||
|
||||
- `Session`, `CurrentUser`, `AuthConfig`, `isExpired`, `sessionFrom`.
|
||||
- Puertos: `AuthGateway`, `ProfileGateway`, `SessionStorage`, `AuthorizationFlow`.
|
||||
|
||||
## Comandos
|
||||
|
||||
```sh
|
||||
npx nx lint web-identity-domain
|
||||
npx nx test web-identity-domain # Jest
|
||||
```
|
||||
|
||||
Reglas de dependencia entre capas: [Arquitectura](../../../../docs/02-arquitectura.md#21-capas-hexagonales).
|
||||
3
libs/web/identity/domain/eslint.config.mjs
Normal file
3
libs/web/identity/domain/eslint.config.mjs
Normal file
@@ -0,0 +1,3 @@
|
||||
import baseConfig from '../../../../eslint.config.mjs';
|
||||
|
||||
export default [...baseConfig];
|
||||
11
libs/web/identity/domain/jest.config.cts
Normal file
11
libs/web/identity/domain/jest.config.cts
Normal file
@@ -0,0 +1,11 @@
|
||||
module.exports = {
|
||||
displayName: 'web-identity-domain',
|
||||
preset: '../../../../jest.preset.js',
|
||||
testEnvironment: 'node',
|
||||
passWithNoTests: true,
|
||||
transform: {
|
||||
'^.+\\.[tj]s$': ['ts-jest', { tsconfig: '<rootDir>/tsconfig.spec.json' }],
|
||||
},
|
||||
moduleFileExtensions: ['ts', 'js', 'html'],
|
||||
coverageDirectory: '../../../../coverage/libs/web/identity/domain',
|
||||
};
|
||||
9
libs/web/identity/domain/project.json
Normal file
9
libs/web/identity/domain/project.json
Normal file
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"name": "web-identity-domain",
|
||||
"$schema": "../../../../node_modules/nx/schemas/project-schema.json",
|
||||
"sourceRoot": "libs/web/identity/domain/src",
|
||||
"projectType": "library",
|
||||
"tags": ["scope:web-identity", "type:domain"],
|
||||
"// targets": "to see all targets run: nx show project web-identity-domain --web",
|
||||
"targets": {}
|
||||
}
|
||||
2
libs/web/identity/domain/src/index.ts
Normal file
2
libs/web/identity/domain/src/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export * from './lib/session';
|
||||
export * from './lib/ports';
|
||||
41
libs/web/identity/domain/src/lib/ports.ts
Normal file
41
libs/web/identity/domain/src/lib/ports.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import { Observable } from 'rxjs';
|
||||
import { AuthConfig, CurrentUser, Session } from './session';
|
||||
|
||||
/** The API's sign-in endpoints (/api/auth/*). */
|
||||
export abstract class AuthGateway {
|
||||
abstract config(): Observable<AuthConfig | null>;
|
||||
abstract exchangeCode(
|
||||
code: string,
|
||||
codeVerifier: string,
|
||||
redirectUri: string,
|
||||
): Observable<Session>;
|
||||
abstract password(username: string, password: string): Observable<Session>;
|
||||
abstract refresh(refreshToken: string): Observable<Session>;
|
||||
}
|
||||
|
||||
/** Who the current token belongs to (GraphQL `me`). */
|
||||
export abstract class ProfileGateway {
|
||||
abstract me(accessToken: string): Observable<CurrentUser>;
|
||||
}
|
||||
|
||||
export abstract class SessionStorage {
|
||||
abstract load(): Session | null;
|
||||
abstract save(session: Session): void;
|
||||
abstract clear(): void;
|
||||
}
|
||||
|
||||
export interface AuthorizationResponse {
|
||||
code: string;
|
||||
codeVerifier: string;
|
||||
redirectUri: string;
|
||||
/** Where the user wanted to go before signing in. */
|
||||
returnUrl: string;
|
||||
}
|
||||
|
||||
/** Authorization Code + PKCE in the browser (redirect out and back). */
|
||||
export abstract class AuthorizationFlow {
|
||||
/** Leaves the app towards the identity server's authorize page. */
|
||||
abstract start(config: AuthConfig, returnUrl: string): Promise<void>;
|
||||
/** Validates `state` and returns what is needed to exchange the code. */
|
||||
abstract complete(params: URLSearchParams): AuthorizationResponse;
|
||||
}
|
||||
23
libs/web/identity/domain/src/lib/session.spec.ts
Normal file
23
libs/web/identity/domain/src/lib/session.spec.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { isExpired, sessionFrom } from './session';
|
||||
|
||||
describe('session', () => {
|
||||
it('computes the expiry from expires_in', () => {
|
||||
const session = sessionFrom(
|
||||
{ accessToken: 't', refreshToken: 'r', expiresIn: 3600 },
|
||||
1_000,
|
||||
);
|
||||
expect(session).toEqual({
|
||||
accessToken: 't',
|
||||
refreshToken: 'r',
|
||||
expiresAt: 3_601_000,
|
||||
});
|
||||
});
|
||||
|
||||
it('treats tokens about to expire as expired', () => {
|
||||
const session = sessionFrom({ accessToken: 't', expiresIn: 30 }, 0);
|
||||
expect(isExpired(session, 0)).toBe(true);
|
||||
expect(
|
||||
isExpired(sessionFrom({ accessToken: 't', expiresIn: 3600 }, 0), 0),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
46
libs/web/identity/domain/src/lib/session.ts
Normal file
46
libs/web/identity/domain/src/lib/session.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
/** Tokens issued by Pireon (through the API's /api/auth/token proxy). */
|
||||
export interface Session {
|
||||
accessToken: string;
|
||||
refreshToken: string | null;
|
||||
/** Epoch milliseconds. */
|
||||
expiresAt: number;
|
||||
}
|
||||
|
||||
export interface CurrentUser {
|
||||
id: string;
|
||||
name: string;
|
||||
email: string;
|
||||
appRoles: string[];
|
||||
}
|
||||
|
||||
/** How the browser can sign in (null config = the API has no Pireon client yet). */
|
||||
export interface AuthConfig {
|
||||
authorizeUrl: string;
|
||||
clientId: string;
|
||||
scopes: string[];
|
||||
passwordGrant: boolean;
|
||||
}
|
||||
|
||||
/** Refresh a little before the token actually expires. */
|
||||
export const EXPIRY_MARGIN_MS = 60_000;
|
||||
|
||||
export function isExpired(session: Session, now = Date.now()): boolean {
|
||||
return session.expiresAt - EXPIRY_MARGIN_MS <= now;
|
||||
}
|
||||
|
||||
export function sessionFrom(
|
||||
token: {
|
||||
accessToken: string;
|
||||
refreshToken?: string | null;
|
||||
expiresIn?: number | null;
|
||||
},
|
||||
now = Date.now(),
|
||||
): Session {
|
||||
// Personal access tokens are long-lived and come without expiry: one year.
|
||||
const expiresIn = token.expiresIn ?? 365 * 24 * 3600;
|
||||
return {
|
||||
accessToken: token.accessToken,
|
||||
refreshToken: token.refreshToken ?? null,
|
||||
expiresAt: now + expiresIn * 1000,
|
||||
};
|
||||
}
|
||||
23
libs/web/identity/domain/tsconfig.json
Normal file
23
libs/web/identity/domain/tsconfig.json
Normal file
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"extends": "../../../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"strict": true,
|
||||
"importHelpers": true,
|
||||
"noImplicitOverride": true,
|
||||
"noImplicitReturns": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noPropertyAccessFromIndexSignature": true
|
||||
},
|
||||
"files": [],
|
||||
"include": [],
|
||||
"references": [
|
||||
{
|
||||
"path": "./tsconfig.lib.json"
|
||||
},
|
||||
{
|
||||
"path": "./tsconfig.spec.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
15
libs/web/identity/domain/tsconfig.lib.json
Normal file
15
libs/web/identity/domain/tsconfig.lib.json
Normal file
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "../../../../dist/out-tsc",
|
||||
"declaration": true,
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src/**/*.ts"],
|
||||
"exclude": [
|
||||
"jest.config.ts",
|
||||
"jest.config.cts",
|
||||
"src/**/*.spec.ts",
|
||||
"src/**/*.test.ts"
|
||||
]
|
||||
}
|
||||
16
libs/web/identity/domain/tsconfig.spec.json
Normal file
16
libs/web/identity/domain/tsconfig.spec.json
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "../../../../dist/out-tsc",
|
||||
"module": "commonjs",
|
||||
"moduleResolution": "bundler",
|
||||
"types": ["jest", "node"]
|
||||
},
|
||||
"include": [
|
||||
"jest.config.ts",
|
||||
"jest.config.cts",
|
||||
"src/**/*.test.ts",
|
||||
"src/**/*.spec.ts",
|
||||
"src/**/*.d.ts"
|
||||
]
|
||||
}
|
||||
21
libs/web/identity/infrastructure/README.md
Normal file
21
libs/web/identity/infrastructure/README.md
Normal file
@@ -0,0 +1,21 @@
|
||||
# web-identity-infrastructure
|
||||
|
||||
Adaptadores de identidad del navegador.
|
||||
|
||||
- **Import**: `@task-stream/web/identity/infrastructure`
|
||||
- **Capa**: `infrastructure` · **Tags**: `scope:web-identity`, `type:infrastructure`
|
||||
|
||||
## Contenido
|
||||
|
||||
- `HttpAuthGateway` (`/api/auth/*`), `GraphqlProfileGateway` (`me`), `LocalSessionStorage`.
|
||||
- `BrowserAuthorizationFlow`: Authorization Code + PKCE con Web Crypto y `state`.
|
||||
- `SessionTokenSource`: conecta el cliente GraphQL con la `AuthFacade`.
|
||||
- `provideIdentityInfrastructure()`.
|
||||
|
||||
## Comandos
|
||||
|
||||
```sh
|
||||
npx nx lint web-identity-infrastructure
|
||||
```
|
||||
|
||||
Reglas de dependencia entre capas: [Arquitectura](../../../../docs/02-arquitectura.md#21-capas-hexagonales).
|
||||
34
libs/web/identity/infrastructure/eslint.config.mjs
Normal file
34
libs/web/identity/infrastructure/eslint.config.mjs
Normal file
@@ -0,0 +1,34 @@
|
||||
import nx from '@nx/eslint-plugin';
|
||||
import baseConfig from '../../../../eslint.config.mjs';
|
||||
|
||||
export default [
|
||||
...nx.configs['flat/angular'],
|
||||
...nx.configs['flat/angular-template'],
|
||||
...baseConfig,
|
||||
{
|
||||
files: ['**/*.ts'],
|
||||
rules: {
|
||||
'@angular-eslint/directive-selector': [
|
||||
'error',
|
||||
{
|
||||
type: 'attribute',
|
||||
prefix: 'ts',
|
||||
style: 'camelCase',
|
||||
},
|
||||
],
|
||||
'@angular-eslint/component-selector': [
|
||||
'error',
|
||||
{
|
||||
type: 'element',
|
||||
prefix: 'ts',
|
||||
style: 'kebab-case',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['**/*.html'],
|
||||
// Override or add rules here
|
||||
rules: {},
|
||||
},
|
||||
];
|
||||
13
libs/web/identity/infrastructure/project.json
Normal file
13
libs/web/identity/infrastructure/project.json
Normal file
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"name": "web-identity-infrastructure",
|
||||
"$schema": "../../../../node_modules/nx/schemas/project-schema.json",
|
||||
"sourceRoot": "libs/web/identity/infrastructure/src",
|
||||
"prefix": "ts",
|
||||
"projectType": "library",
|
||||
"tags": ["scope:web-identity", "type:infrastructure"],
|
||||
"targets": {
|
||||
"lint": {
|
||||
"executor": "@nx/eslint:lint"
|
||||
}
|
||||
}
|
||||
}
|
||||
2
libs/web/identity/infrastructure/src/index.ts
Normal file
2
libs/web/identity/infrastructure/src/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export * from './lib/identity-infrastructure.providers';
|
||||
export { CALLBACK_PATH } from './lib/adapters/browser-authorization.flow';
|
||||
@@ -0,0 +1,90 @@
|
||||
import { DOCUMENT } from '@angular/common';
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import {
|
||||
AuthConfig,
|
||||
AuthorizationFlow,
|
||||
AuthorizationResponse,
|
||||
} from '@task-stream/web/identity/domain';
|
||||
|
||||
const PENDING_KEY = 'task-stream.pkce';
|
||||
export const CALLBACK_PATH = '/auth/callback';
|
||||
|
||||
interface PendingAuthorization {
|
||||
state: string;
|
||||
codeVerifier: string;
|
||||
returnUrl: string;
|
||||
}
|
||||
|
||||
/** Authorization Code + PKCE (RFC 7636) with the browser's Web Crypto. */
|
||||
@Injectable()
|
||||
export class BrowserAuthorizationFlow extends AuthorizationFlow {
|
||||
private readonly document = inject(DOCUMENT);
|
||||
|
||||
async start(config: AuthConfig, returnUrl: string): Promise<void> {
|
||||
const codeVerifier = randomString(64);
|
||||
const state = randomString(32);
|
||||
sessionStorage.setItem(
|
||||
PENDING_KEY,
|
||||
JSON.stringify({
|
||||
state,
|
||||
codeVerifier,
|
||||
returnUrl,
|
||||
} satisfies PendingAuthorization),
|
||||
);
|
||||
|
||||
const url = new URL(config.authorizeUrl);
|
||||
url.search = new URLSearchParams({
|
||||
client_id: config.clientId,
|
||||
redirect_uri: this.redirectUri(),
|
||||
response_type: 'code',
|
||||
scope: config.scopes.join(' '),
|
||||
state,
|
||||
code_challenge: await challengeOf(codeVerifier),
|
||||
code_challenge_method: 'S256',
|
||||
}).toString();
|
||||
this.document.location.assign(url.toString());
|
||||
}
|
||||
|
||||
complete(params: URLSearchParams): AuthorizationResponse {
|
||||
const raw = sessionStorage.getItem(PENDING_KEY);
|
||||
sessionStorage.removeItem(PENDING_KEY);
|
||||
const pending = raw ? (JSON.parse(raw) as PendingAuthorization) : null;
|
||||
|
||||
const error = params.get('error_description') ?? params.get('error');
|
||||
if (error) throw new Error(error);
|
||||
const code = params.get('code');
|
||||
if (!pending || !code || params.get('state') !== pending.state) {
|
||||
throw new Error(
|
||||
'The sign-in response is invalid or expired. Please try again.',
|
||||
);
|
||||
}
|
||||
return {
|
||||
code,
|
||||
codeVerifier: pending.codeVerifier,
|
||||
redirectUri: this.redirectUri(),
|
||||
returnUrl: pending.returnUrl,
|
||||
};
|
||||
}
|
||||
|
||||
private redirectUri(): string {
|
||||
return `${this.document.location.origin}${CALLBACK_PATH}`;
|
||||
}
|
||||
}
|
||||
|
||||
function randomString(length: number): string {
|
||||
const alphabet =
|
||||
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~';
|
||||
const bytes = crypto.getRandomValues(new Uint8Array(length));
|
||||
return Array.from(bytes, (b) => alphabet[b % alphabet.length]).join('');
|
||||
}
|
||||
|
||||
async function challengeOf(verifier: string): Promise<string> {
|
||||
const digest = await crypto.subtle.digest(
|
||||
'SHA-256',
|
||||
new TextEncoder().encode(verifier),
|
||||
);
|
||||
return btoa(String.fromCharCode(...new Uint8Array(digest)))
|
||||
.replace(/\+/g, '-')
|
||||
.replace(/\//g, '_')
|
||||
.replace(/=+$/, '');
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { API_CONFIG } from '@task-stream/web/shared/infrastructure';
|
||||
import { CurrentUser, ProfileGateway } from '@task-stream/web/identity/domain';
|
||||
import { print } from 'graphql';
|
||||
import { map, Observable } from 'rxjs';
|
||||
import { MeDocument, type MeQuery } from '../graphql/generated';
|
||||
|
||||
/**
|
||||
* `me` with an explicit token: used right after signing in, before the
|
||||
* session is stored, so it does not go through the shared Apollo auth link.
|
||||
*/
|
||||
@Injectable()
|
||||
export class GraphqlProfileGateway extends ProfileGateway {
|
||||
private readonly http = inject(HttpClient);
|
||||
private readonly api = inject(API_CONFIG);
|
||||
private readonly query = print(MeDocument);
|
||||
|
||||
me(accessToken: string): Observable<CurrentUser> {
|
||||
return this.http
|
||||
.post<{
|
||||
data: MeQuery | null;
|
||||
errors?: { message: string }[];
|
||||
}>(
|
||||
this.api.graphqlUrl,
|
||||
{ query: this.query },
|
||||
{ headers: { Authorization: `Bearer ${accessToken}` } },
|
||||
)
|
||||
.pipe(
|
||||
map((response) => {
|
||||
if (!response.data)
|
||||
throw new Error(response.errors?.[0]?.message ?? 'Unauthenticated');
|
||||
return response.data.me;
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { API_CONFIG } from '@task-stream/web/shared/infrastructure';
|
||||
import {
|
||||
AuthConfig,
|
||||
AuthGateway,
|
||||
Session,
|
||||
sessionFrom,
|
||||
} from '@task-stream/web/identity/domain';
|
||||
import { map, Observable } from 'rxjs';
|
||||
|
||||
interface TokenResponse {
|
||||
access_token: string;
|
||||
refresh_token: string | null;
|
||||
expires_in: number;
|
||||
}
|
||||
|
||||
/** The API's sign-in proxy to Pireon (/api/auth/*). */
|
||||
@Injectable()
|
||||
export class HttpAuthGateway extends AuthGateway {
|
||||
private readonly http = inject(HttpClient);
|
||||
private readonly api = inject(API_CONFIG);
|
||||
|
||||
config(): Observable<AuthConfig | null> {
|
||||
return this.http.get<AuthConfig | null>(`${this.api.restUrl}/auth/config`);
|
||||
}
|
||||
|
||||
exchangeCode(
|
||||
code: string,
|
||||
codeVerifier: string,
|
||||
redirectUri: string,
|
||||
): Observable<Session> {
|
||||
return this.token({
|
||||
grant_type: 'authorization_code',
|
||||
code,
|
||||
code_verifier: codeVerifier,
|
||||
redirect_uri: redirectUri,
|
||||
});
|
||||
}
|
||||
|
||||
password(username: string, password: string): Observable<Session> {
|
||||
return this.token({ grant_type: 'password', username, password });
|
||||
}
|
||||
|
||||
refresh(refreshToken: string): Observable<Session> {
|
||||
return this.token({
|
||||
grant_type: 'refresh_token',
|
||||
refresh_token: refreshToken,
|
||||
});
|
||||
}
|
||||
|
||||
private token(body: Record<string, string>): Observable<Session> {
|
||||
return this.http
|
||||
.post<TokenResponse>(`${this.api.restUrl}/auth/token`, body)
|
||||
.pipe(
|
||||
map((token) =>
|
||||
sessionFrom({
|
||||
accessToken: token.access_token,
|
||||
refreshToken: token.refresh_token,
|
||||
expiresIn: token.expires_in,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { Session, SessionStorage } from '@task-stream/web/identity/domain';
|
||||
|
||||
const KEY = 'task-stream.session';
|
||||
|
||||
@Injectable()
|
||||
export class LocalSessionStorage extends SessionStorage {
|
||||
load(): Session | null {
|
||||
try {
|
||||
const raw = localStorage.getItem(KEY);
|
||||
return raw ? (JSON.parse(raw) as Session) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
save(session: Session): void {
|
||||
try {
|
||||
localStorage.setItem(KEY, JSON.stringify(session));
|
||||
} catch {
|
||||
// Private browsing / storage disabled: the session lasts this tab only.
|
||||
}
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
try {
|
||||
localStorage.removeItem(KEY);
|
||||
} catch {
|
||||
// Nothing to clear.
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { AccessTokenSource } from '@task-stream/web/shared/infrastructure';
|
||||
import { AuthFacade } from '@task-stream/web/identity/application';
|
||||
|
||||
/** Gives the shared GraphQL client the session's token (refreshing it when needed). */
|
||||
@Injectable()
|
||||
export class SessionTokenSource extends AccessTokenSource {
|
||||
private readonly auth = inject(AuthFacade);
|
||||
|
||||
accessToken(): Promise<string | null> {
|
||||
return this.auth.validAccessToken();
|
||||
}
|
||||
|
||||
unauthenticated(): void {
|
||||
this.auth.expire();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/** Internal type. DO NOT USE DIRECTLY. */
|
||||
type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] };
|
||||
/** Internal type. DO NOT USE DIRECTLY. */
|
||||
export type Incremental<T> =
|
||||
| T
|
||||
| {
|
||||
[P in keyof T]?: P extends ' $fragmentName' | '__typename' ? T[P] : never;
|
||||
};
|
||||
import type { TypedDocumentNode as DocumentNode } from '@graphql-typed-document-node/core';
|
||||
export type MeQueryVariables = Exact<{ [key: string]: never }>;
|
||||
|
||||
export type MeQuery = {
|
||||
me: { id: string; name: string; email: string; appRoles: Array<string> };
|
||||
};
|
||||
|
||||
export const MeDocument = {
|
||||
kind: 'Document',
|
||||
definitions: [
|
||||
{
|
||||
kind: 'OperationDefinition',
|
||||
operation: 'query',
|
||||
name: { kind: 'Name', value: 'Me' },
|
||||
selectionSet: {
|
||||
kind: 'SelectionSet',
|
||||
selections: [
|
||||
{
|
||||
kind: 'Field',
|
||||
name: { kind: 'Name', value: 'me' },
|
||||
selectionSet: {
|
||||
kind: 'SelectionSet',
|
||||
selections: [
|
||||
{ kind: 'Field', name: { kind: 'Name', value: 'id' } },
|
||||
{ kind: 'Field', name: { kind: 'Name', value: 'name' } },
|
||||
{ kind: 'Field', name: { kind: 'Name', value: 'email' } },
|
||||
{ kind: 'Field', name: { kind: 'Name', value: 'appRoles' } },
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
} as unknown as DocumentNode<MeQuery, MeQueryVariables>;
|
||||
@@ -0,0 +1,8 @@
|
||||
query Me {
|
||||
me {
|
||||
id
|
||||
name
|
||||
email
|
||||
appRoles
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import {
|
||||
makeEnvironmentProviders,
|
||||
type EnvironmentProviders,
|
||||
} from '@angular/core';
|
||||
import {
|
||||
AuthGateway,
|
||||
AuthorizationFlow,
|
||||
ProfileGateway,
|
||||
SessionStorage,
|
||||
} from '@task-stream/web/identity/domain';
|
||||
import { AccessTokenSource } from '@task-stream/web/shared/infrastructure';
|
||||
import { SessionTokenSource } from './adapters/session.token-source';
|
||||
import { BrowserAuthorizationFlow } from './adapters/browser-authorization.flow';
|
||||
import { GraphqlProfileGateway } from './adapters/graphql-profile.gateway';
|
||||
import { HttpAuthGateway } from './adapters/http-auth.gateway';
|
||||
import { LocalSessionStorage } from './adapters/local-session.storage';
|
||||
|
||||
export function provideIdentityInfrastructure(): EnvironmentProviders {
|
||||
return makeEnvironmentProviders([
|
||||
{ provide: AuthGateway, useClass: HttpAuthGateway },
|
||||
{ provide: ProfileGateway, useClass: GraphqlProfileGateway },
|
||||
{ provide: SessionStorage, useClass: LocalSessionStorage },
|
||||
{ provide: AuthorizationFlow, useClass: BrowserAuthorizationFlow },
|
||||
{ provide: AccessTokenSource, useClass: SessionTokenSource },
|
||||
]);
|
||||
}
|
||||
27
libs/web/identity/infrastructure/tsconfig.json
Normal file
27
libs/web/identity/infrastructure/tsconfig.json
Normal file
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"extends": "../../../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"isolatedModules": true,
|
||||
"target": "es2022",
|
||||
"strict": true,
|
||||
"noImplicitOverride": true,
|
||||
"noPropertyAccessFromIndexSignature": true,
|
||||
"noImplicitReturns": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"emitDecoratorMetadata": false,
|
||||
"module": "preserve"
|
||||
},
|
||||
"angularCompilerOptions": {
|
||||
"enableI18nLegacyMessageIdFormat": false,
|
||||
"strictInjectionParameters": true,
|
||||
"strictInputAccessModifiers": true,
|
||||
"strictTemplates": true
|
||||
},
|
||||
"files": [],
|
||||
"include": [],
|
||||
"references": [
|
||||
{
|
||||
"path": "./tsconfig.lib.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
12
libs/web/identity/infrastructure/tsconfig.lib.json
Normal file
12
libs/web/identity/infrastructure/tsconfig.lib.json
Normal file
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "../../../../dist/out-tsc",
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"inlineSources": true,
|
||||
"types": []
|
||||
},
|
||||
"include": ["src/**/*.ts"],
|
||||
"exclude": ["src/**/*.spec.ts", "src/**/*.test.ts"]
|
||||
}
|
||||
19
libs/web/identity/presenters/README.md
Normal file
19
libs/web/identity/presenters/README.md
Normal file
@@ -0,0 +1,19 @@
|
||||
# web-identity-presenters
|
||||
|
||||
Pantallas y guards de identidad.
|
||||
|
||||
- **Import**: `@task-stream/web/identity/presenters`
|
||||
- **Capa**: `presenters` · **Tags**: `scope:web-identity`, `type:presenters`
|
||||
|
||||
## Contenido
|
||||
|
||||
- Rutas `identityRoutes`: `/login` y `/auth/callback`.
|
||||
- `authGuard`, `guestGuard` y `UserMenuComponent`.
|
||||
|
||||
## Comandos
|
||||
|
||||
```sh
|
||||
npx nx lint web-identity-presenters
|
||||
```
|
||||
|
||||
Reglas de dependencia entre capas: [Arquitectura](../../../../docs/02-arquitectura.md#21-capas-hexagonales).
|
||||
34
libs/web/identity/presenters/eslint.config.mjs
Normal file
34
libs/web/identity/presenters/eslint.config.mjs
Normal file
@@ -0,0 +1,34 @@
|
||||
import nx from '@nx/eslint-plugin';
|
||||
import baseConfig from '../../../../eslint.config.mjs';
|
||||
|
||||
export default [
|
||||
...nx.configs['flat/angular'],
|
||||
...nx.configs['flat/angular-template'],
|
||||
...baseConfig,
|
||||
{
|
||||
files: ['**/*.ts'],
|
||||
rules: {
|
||||
'@angular-eslint/directive-selector': [
|
||||
'error',
|
||||
{
|
||||
type: 'attribute',
|
||||
prefix: 'ts',
|
||||
style: 'camelCase',
|
||||
},
|
||||
],
|
||||
'@angular-eslint/component-selector': [
|
||||
'error',
|
||||
{
|
||||
type: 'element',
|
||||
prefix: 'ts',
|
||||
style: 'kebab-case',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['**/*.html'],
|
||||
// Override or add rules here
|
||||
rules: {},
|
||||
},
|
||||
];
|
||||
13
libs/web/identity/presenters/project.json
Normal file
13
libs/web/identity/presenters/project.json
Normal file
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"name": "web-identity-presenters",
|
||||
"$schema": "../../../../node_modules/nx/schemas/project-schema.json",
|
||||
"sourceRoot": "libs/web/identity/presenters/src",
|
||||
"prefix": "ts",
|
||||
"projectType": "library",
|
||||
"tags": ["scope:web-identity", "type:presenters"],
|
||||
"targets": {
|
||||
"lint": {
|
||||
"executor": "@nx/eslint:lint"
|
||||
}
|
||||
}
|
||||
}
|
||||
3
libs/web/identity/presenters/src/index.ts
Normal file
3
libs/web/identity/presenters/src/index.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export * from './lib/guards';
|
||||
export * from './lib/identity.routes';
|
||||
export * from './lib/components/user-menu';
|
||||
74
libs/web/identity/presenters/src/lib/components/user-menu.ts
Normal file
74
libs/web/identity/presenters/src/lib/components/user-menu.ts
Normal file
@@ -0,0 +1,74 @@
|
||||
import { ChangeDetectionStrategy, Component, inject } from '@angular/core';
|
||||
import { PiIconComponent } from '@pi/ui';
|
||||
import { AuthFacade } from '@task-stream/web/identity/application';
|
||||
|
||||
/** Signed-in user in the header: initials, name, sign out. */
|
||||
@Component({
|
||||
selector: 'ts-user-menu',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
imports: [PiIconComponent],
|
||||
template: `
|
||||
@if (auth.user(); as user) {
|
||||
<div class="ts-user" [title]="user.email">
|
||||
<span class="ts-user__avatar" aria-hidden="true">{{
|
||||
auth.initials()
|
||||
}}</span>
|
||||
<span class="ts-user__name">{{ user.name }}</span>
|
||||
<button
|
||||
type="button"
|
||||
class="ts-icon-button ts-user__out"
|
||||
aria-label="Cerrar sesión"
|
||||
title="Cerrar sesión"
|
||||
(click)="auth.signOut()"
|
||||
>
|
||||
<pi-icon icon="logout" size="small" />
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
`,
|
||||
styles: `
|
||||
.ts-user {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
padding: 0.1875rem;
|
||||
border: 1px solid var(--ts-line);
|
||||
border-radius: 999px;
|
||||
background: var(--ts-surface);
|
||||
}
|
||||
.ts-user__avatar {
|
||||
display: inline-grid;
|
||||
place-items: center;
|
||||
width: 1.875rem;
|
||||
height: 1.875rem;
|
||||
border-radius: 50%;
|
||||
background: linear-gradient(
|
||||
135deg,
|
||||
var(--pi-color-primary),
|
||||
var(--pi-color-accent)
|
||||
);
|
||||
color: #fff;
|
||||
font-size: 0.6875rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
.ts-user__name {
|
||||
font-size: 0.875rem;
|
||||
font-weight: 600;
|
||||
white-space: nowrap;
|
||||
@media (max-width: 640px) {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
.ts-user__out {
|
||||
--ts-icon-button-size: 1.875rem;
|
||||
color: var(--ts-muted);
|
||||
&:hover {
|
||||
color: var(--ts-ink);
|
||||
background: var(--pi-color-primary-25);
|
||||
}
|
||||
}
|
||||
`,
|
||||
})
|
||||
export class UserMenuComponent {
|
||||
protected readonly auth = inject(AuthFacade);
|
||||
}
|
||||
37
libs/web/identity/presenters/src/lib/guards.ts
Normal file
37
libs/web/identity/presenters/src/lib/guards.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import { inject } from '@angular/core';
|
||||
import { toObservable } from '@angular/core/rxjs-interop';
|
||||
import { CanActivateFn, Router } from '@angular/router';
|
||||
import { AuthFacade } from '@task-stream/web/identity/application';
|
||||
import { filter, map, take } from 'rxjs';
|
||||
|
||||
/** Waits for the stored session to be restored before deciding. */
|
||||
function whenSettled() {
|
||||
const auth = inject(AuthFacade);
|
||||
return toObservable(auth.settled).pipe(
|
||||
filter(Boolean),
|
||||
take(1),
|
||||
map(() => auth.isAuthenticated()),
|
||||
);
|
||||
}
|
||||
|
||||
export const authGuard: CanActivateFn = (_route, state) => {
|
||||
const router = inject(Router);
|
||||
return whenSettled().pipe(
|
||||
map((authenticated) =>
|
||||
authenticated
|
||||
? true
|
||||
: router.createUrlTree(['/login'], {
|
||||
queryParams: { returnUrl: state.url },
|
||||
}),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
export const guestGuard: CanActivateFn = () => {
|
||||
const router = inject(Router);
|
||||
return whenSettled().pipe(
|
||||
map((authenticated) =>
|
||||
authenticated ? router.createUrlTree(['/']) : true,
|
||||
),
|
||||
);
|
||||
};
|
||||
18
libs/web/identity/presenters/src/lib/identity.routes.ts
Normal file
18
libs/web/identity/presenters/src/lib/identity.routes.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { Routes } from '@angular/router';
|
||||
import { guestGuard } from './guards';
|
||||
|
||||
/** /login and /auth/callback (the Pireon redirect URI). */
|
||||
export const identityRoutes: Routes = [
|
||||
{
|
||||
path: 'login',
|
||||
canActivate: [guestGuard],
|
||||
title: 'Entrar · TaskStream',
|
||||
loadComponent: () => import('./pages/login.page').then((m) => m.LoginPage),
|
||||
},
|
||||
{
|
||||
path: 'auth/callback',
|
||||
title: 'Entrando · TaskStream',
|
||||
loadComponent: () =>
|
||||
import('./pages/callback.page').then((m) => m.CallbackPage),
|
||||
},
|
||||
];
|
||||
43
libs/web/identity/presenters/src/lib/pages/callback.page.ts
Normal file
43
libs/web/identity/presenters/src/lib/pages/callback.page.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import {
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
inject,
|
||||
OnInit,
|
||||
} from '@angular/core';
|
||||
import { DOCUMENT } from '@angular/common';
|
||||
import { RouterLink } from '@angular/router';
|
||||
import { PiNoteComponent, PiSpinnerComponent } from '@pi/ui';
|
||||
import { AuthFacade } from '@task-stream/web/identity/application';
|
||||
|
||||
/** Where Pireon sends the user back with `?code=…&state=…`. */
|
||||
@Component({
|
||||
selector: 'ts-callback-page',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
imports: [RouterLink, PiSpinnerComponent, PiNoteComponent],
|
||||
template: `
|
||||
<div style="display:grid;justify-items:center;gap:1rem;padding-top:15vh">
|
||||
@if (auth.error(); as error) {
|
||||
<pi-note
|
||||
gap="xs"
|
||||
status="error"
|
||||
appearance="fill"
|
||||
type="status"
|
||||
title="No se pudo iniciar sesión"
|
||||
[text]="error"
|
||||
/>
|
||||
<a routerLink="/login">Volver a intentarlo</a>
|
||||
} @else {
|
||||
<pi-spinner [isLoading]="true" [diameter]="48" />
|
||||
<p>Completando el inicio de sesión…</p>
|
||||
}
|
||||
</div>
|
||||
`,
|
||||
})
|
||||
export class CallbackPage implements OnInit {
|
||||
protected readonly auth = inject(AuthFacade);
|
||||
private readonly document = inject(DOCUMENT);
|
||||
|
||||
ngOnInit(): void {
|
||||
this.auth.completeSignIn(this.document.location.search);
|
||||
}
|
||||
}
|
||||
194
libs/web/identity/presenters/src/lib/pages/login.page.scss
Normal file
194
libs/web/identity/presenters/src/lib/pages/login.page.scss
Normal file
@@ -0,0 +1,194 @@
|
||||
// Two columns: the product's pitch over a live-looking event stream, and the
|
||||
// sign-in card. Stacks on small screens (card first).
|
||||
.ts-login {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1.15fr) minmax(0, 26rem);
|
||||
align-items: center;
|
||||
gap: clamp(2rem, 5vw, 5rem);
|
||||
min-height: calc(100vh - 12rem);
|
||||
max-width: 72rem;
|
||||
margin-inline: auto;
|
||||
|
||||
@media (max-width: 900px) {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
min-height: 0;
|
||||
|
||||
.ts-login__card {
|
||||
order: -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.ts-login__intro {
|
||||
min-width: 0;
|
||||
|
||||
// Same scale as pireon.dev's hero title.
|
||||
h1 {
|
||||
margin: 0 0 1.25rem;
|
||||
font-size: clamp(2.25rem, 6vw, 3.75rem);
|
||||
font-weight: 700;
|
||||
line-height: 1.08;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
}
|
||||
|
||||
.ts-login__eyebrow {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.625rem;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
|
||||
.ts-login__live {
|
||||
width: 0.5rem;
|
||||
height: 0.5rem;
|
||||
border-radius: 50%;
|
||||
background: var(--ts-s-done);
|
||||
box-shadow: 0 0 0 0 color-mix(in srgb, var(--ts-s-done) 60%, transparent);
|
||||
animation: ts-pulse 2s ease-out infinite;
|
||||
}
|
||||
|
||||
@keyframes ts-pulse {
|
||||
70% {
|
||||
box-shadow: 0 0 0 0.5rem transparent;
|
||||
}
|
||||
100% {
|
||||
box-shadow: 0 0 0 0 transparent;
|
||||
}
|
||||
}
|
||||
|
||||
.ts-login__lead {
|
||||
max-width: 46ch;
|
||||
margin: 0 0 2.25rem;
|
||||
font-size: 1.0625rem;
|
||||
line-height: 1.55;
|
||||
color: var(--ts-muted);
|
||||
}
|
||||
|
||||
// Event stream: a Pireon card scrolling upwards, faded at both ends.
|
||||
.ts-feed {
|
||||
height: 15.5rem;
|
||||
overflow: hidden;
|
||||
mask-image: linear-gradient(transparent, #000 18%, #000 82%, transparent);
|
||||
|
||||
@media (max-width: 900px) {
|
||||
height: 9.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
.ts-feed__track {
|
||||
display: grid;
|
||||
animation: ts-scroll 22s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes ts-scroll {
|
||||
to {
|
||||
transform: translateY(-50%);
|
||||
}
|
||||
}
|
||||
|
||||
.ts-feed__row {
|
||||
display: grid;
|
||||
grid-template-columns: 3rem 4.25rem minmax(0, 1fr) auto;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
padding: 0.625rem 1.125rem;
|
||||
border-bottom: 1px dashed var(--ts-line);
|
||||
font-family: var(--ts-font-mono);
|
||||
font-size: 0.8125rem;
|
||||
|
||||
@media (max-width: 520px) {
|
||||
grid-template-columns: 2.75rem 3.75rem minmax(0, 1fr);
|
||||
gap: 0.5rem;
|
||||
padding-inline: 0.875rem;
|
||||
|
||||
.ts-feed__from,
|
||||
.ts-feed__arrow,
|
||||
.ts-feed__who {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.ts-feed__time,
|
||||
.ts-feed__who {
|
||||
color: var(--ts-muted);
|
||||
}
|
||||
|
||||
.ts-feed__key {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.ts-feed__move {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
min-width: 0;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.ts-feed__from {
|
||||
color: var(--ts-muted);
|
||||
}
|
||||
|
||||
.ts-feed__arrow {
|
||||
color: var(--ts-line-strong);
|
||||
}
|
||||
|
||||
.ts-feed__to {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.375rem;
|
||||
font-weight: 600;
|
||||
color: color-mix(in srgb, var(--tone) 85%, var(--ts-ink));
|
||||
|
||||
&::before {
|
||||
content: '';
|
||||
width: 0.4375rem;
|
||||
height: 0.4375rem;
|
||||
border-radius: 50%;
|
||||
background: var(--tone);
|
||||
}
|
||||
}
|
||||
|
||||
// Sign-in card (a Pireon card)
|
||||
.ts-login__card {
|
||||
padding: 2rem;
|
||||
box-shadow: var(--ts-lift);
|
||||
|
||||
@media (max-width: 480px) {
|
||||
padding: 1.5rem 1.25rem;
|
||||
}
|
||||
}
|
||||
|
||||
.ts-login__card-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.875rem;
|
||||
margin-bottom: 1.75rem;
|
||||
|
||||
h2 {
|
||||
margin: 0;
|
||||
font-size: 1.5rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 0.125rem 0 0;
|
||||
color: var(--ts-muted);
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
}
|
||||
|
||||
.ts-login__content,
|
||||
.ts-login__form {
|
||||
display: grid;
|
||||
gap: 1.25rem;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
// The field's label sits above its outline: leave room after the previous field's error.
|
||||
.ts-login__form {
|
||||
row-gap: 1.75rem;
|
||||
}
|
||||
276
libs/web/identity/presenters/src/lib/pages/login.page.ts
Normal file
276
libs/web/identity/presenters/src/lib/pages/login.page.ts
Normal file
@@ -0,0 +1,276 @@
|
||||
import {
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
computed,
|
||||
inject,
|
||||
input,
|
||||
OnInit,
|
||||
signal,
|
||||
} from '@angular/core';
|
||||
import { emailError, requiredError } from '@angular/forms/signals';
|
||||
import {
|
||||
PiActionButtonComponent,
|
||||
PiDividerComponent,
|
||||
PiEmailFieldComponent,
|
||||
PiLabelDirective,
|
||||
PiNoteComponent,
|
||||
PiPasswordFieldComponent,
|
||||
} from '@pi/ui';
|
||||
import { AuthFacade } from '@task-stream/web/identity/application';
|
||||
import { LogoComponent } from '@task-stream/web/shared/ui';
|
||||
|
||||
const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
|
||||
/** Illustrative events for the welcome panel (decorative, not real data). */
|
||||
const SAMPLE_FEED = [
|
||||
{
|
||||
time: '09:41',
|
||||
key: 'WEB-12',
|
||||
from: 'En QA',
|
||||
to: 'Hecho',
|
||||
tone: 'done',
|
||||
who: 'Quinn',
|
||||
},
|
||||
{
|
||||
time: '09:38',
|
||||
key: 'API-7',
|
||||
from: 'En curso',
|
||||
to: 'En revisión',
|
||||
tone: 'review',
|
||||
who: 'Dan',
|
||||
},
|
||||
{
|
||||
time: '09:35',
|
||||
key: 'WEB-14',
|
||||
from: 'En QA',
|
||||
to: 'QA fallido',
|
||||
tone: 'failed',
|
||||
who: 'Quinn',
|
||||
},
|
||||
{
|
||||
time: '09:31',
|
||||
key: 'MOB-3',
|
||||
from: 'Por hacer',
|
||||
to: 'En curso',
|
||||
tone: 'progress',
|
||||
who: 'Bob',
|
||||
},
|
||||
{
|
||||
time: '09:27',
|
||||
key: 'WEB-9',
|
||||
from: 'En revisión',
|
||||
to: 'Listo para QA',
|
||||
tone: 'ready',
|
||||
who: 'Ana',
|
||||
},
|
||||
{
|
||||
time: '09:22',
|
||||
key: 'API-4',
|
||||
from: 'Listo para QA',
|
||||
to: 'En QA',
|
||||
tone: 'qa',
|
||||
who: 'Quinn',
|
||||
},
|
||||
{
|
||||
time: '09:18',
|
||||
key: 'WEB-3',
|
||||
from: 'Backlog',
|
||||
to: 'Por hacer',
|
||||
tone: 'todo',
|
||||
who: 'Ana',
|
||||
},
|
||||
];
|
||||
|
||||
@Component({
|
||||
selector: 'ts-login-page',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
imports: [
|
||||
LogoComponent,
|
||||
PiActionButtonComponent,
|
||||
PiDividerComponent,
|
||||
PiEmailFieldComponent,
|
||||
PiPasswordFieldComponent,
|
||||
PiLabelDirective,
|
||||
PiNoteComponent,
|
||||
],
|
||||
styleUrl: './login.page.scss',
|
||||
template: `
|
||||
<section class="ts-login">
|
||||
<div class="ts-login__intro">
|
||||
<p class="ts-eyebrow ts-login__eyebrow">
|
||||
<span class="ts-login__live"></span> Pireon · TaskStream
|
||||
</p>
|
||||
<h1>
|
||||
Cada cambio,<br /><span class="ts-gradient-text"
|
||||
>en cuanto pasa.</span
|
||||
>
|
||||
</h1>
|
||||
<p class="ts-login__lead">
|
||||
Bugs, cambios de UI, features y QA de tu equipo en un tablero que se
|
||||
mueve solo. Front, back y QA, enlazados de punta a punta.
|
||||
</p>
|
||||
<div class="ts-feed ts-panel" aria-hidden="true">
|
||||
<div class="ts-feed__track">
|
||||
@for (event of feed; track $index) {
|
||||
<div
|
||||
class="ts-feed__row"
|
||||
[style.--tone]="'var(--ts-s-' + event.tone + ')'"
|
||||
>
|
||||
<span class="ts-feed__time">{{ event.time }}</span>
|
||||
<span class="ts-feed__key">{{ event.key }}</span>
|
||||
<span class="ts-feed__move">
|
||||
<span class="ts-feed__from">{{ event.from }}</span>
|
||||
<span class="ts-feed__arrow">→</span>
|
||||
<span class="ts-feed__to">{{ event.to }}</span>
|
||||
</span>
|
||||
<span class="ts-feed__who">{{ event.who }}</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="ts-login__card ts-panel">
|
||||
<div class="ts-login__card-head">
|
||||
<ts-logo [size]="40" />
|
||||
<div>
|
||||
<h2>Entrar</h2>
|
||||
<p>Con tu cuenta de Pireon.</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="ts-login__content">
|
||||
@if (!configured()) {
|
||||
<pi-note
|
||||
gap="xs"
|
||||
flexDirection="column"
|
||||
alignment="flex-start"
|
||||
status="info"
|
||||
appearance="fill"
|
||||
type="status"
|
||||
title="Inicio de sesión no configurado"
|
||||
text="La API necesita un cliente OAuth de Pireon: PIREON_CLIENT_ID y PIREON_CLIENT_SECRET en .env."
|
||||
/>
|
||||
} @else if (auth.error(); as error) {
|
||||
<pi-note
|
||||
gap="xs"
|
||||
flexDirection="column"
|
||||
alignment="flex-start"
|
||||
status="error"
|
||||
appearance="fill"
|
||||
type="status"
|
||||
title="No se pudo iniciar sesión"
|
||||
[text]="error"
|
||||
/>
|
||||
}
|
||||
|
||||
@if (auth.config(); as config) {
|
||||
<pi-action-button
|
||||
size="w100"
|
||||
color="primary"
|
||||
text="Entrar con Pireon"
|
||||
[hasIcon]="true"
|
||||
[disabled]="busy()"
|
||||
(execute)="auth.signInWithPireon(returnUrl())"
|
||||
/>
|
||||
@if (config.passwordGrant) {
|
||||
<pi-divider color="grey" label="o" gap="m" />
|
||||
}
|
||||
}
|
||||
|
||||
@if (passwordEnabled()) {
|
||||
<form
|
||||
class="ts-login__form"
|
||||
(submit)="$event.preventDefault(); signIn()"
|
||||
novalidate
|
||||
>
|
||||
<pi-email-field
|
||||
name="email"
|
||||
placeholder="tu@email.com"
|
||||
[required]="true"
|
||||
[disabled]="busy()"
|
||||
[errors]="emailErrors()"
|
||||
[(value)]="email"
|
||||
(touch)="emailTouched.set(true)"
|
||||
>
|
||||
<pi-label [isRequired]="true">Email de Pireon</pi-label>
|
||||
</pi-email-field>
|
||||
<pi-password-field
|
||||
name="password"
|
||||
placeholder="Contraseña"
|
||||
[required]="true"
|
||||
[disabled]="busy()"
|
||||
[errors]="passwordErrors()"
|
||||
[(value)]="password"
|
||||
(touch)="passwordTouched.set(true)"
|
||||
>
|
||||
<pi-label [isRequired]="true">Contraseña</pi-label>
|
||||
</pi-password-field>
|
||||
<pi-action-button
|
||||
size="w100"
|
||||
color="primary"
|
||||
[text]="busy() ? 'Entrando…' : 'Entrar'"
|
||||
[hasIcon]="!busy()"
|
||||
[disabled]="busy() || !configured()"
|
||||
(execute)="signIn()"
|
||||
/>
|
||||
</form>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
`,
|
||||
})
|
||||
export class LoginPage implements OnInit {
|
||||
/** Bound from the query string by the router (withComponentInputBinding). */
|
||||
readonly returnUrl = input<string>('/');
|
||||
|
||||
protected readonly auth = inject(AuthFacade);
|
||||
/** Twice, so the vertical marquee loops without a jump. */
|
||||
protected readonly feed = [...SAMPLE_FEED, ...SAMPLE_FEED];
|
||||
protected readonly busy = this.auth.signingIn;
|
||||
/** Email and password go to Pireon through the API (password grant). */
|
||||
/** null = the API has no Pireon client: nobody can sign in yet. */
|
||||
protected readonly configured = computed(() => this.auth.config() !== null);
|
||||
protected readonly passwordEnabled = computed(
|
||||
() => this.auth.config()?.passwordGrant !== false,
|
||||
);
|
||||
|
||||
protected readonly email = signal('');
|
||||
protected readonly password = signal('');
|
||||
// Errors show once the user leaves a field or tries to sign in, not on load
|
||||
// (`@pi/ui` fields paint any error they receive, touched or not).
|
||||
protected readonly emailTouched = signal(false);
|
||||
protected readonly passwordTouched = signal(false);
|
||||
|
||||
private readonly emailProblems = computed(() => {
|
||||
const value = this.email().trim();
|
||||
if (!value) return [requiredError()];
|
||||
return EMAIL.test(value) ? [] : [emailError()];
|
||||
});
|
||||
private readonly passwordProblems = computed(() =>
|
||||
this.password() ? [] : [requiredError()],
|
||||
);
|
||||
protected readonly emailErrors = computed(() =>
|
||||
this.emailTouched() ? this.emailProblems() : [],
|
||||
);
|
||||
protected readonly passwordErrors = computed(() =>
|
||||
this.passwordTouched() ? this.passwordProblems() : [],
|
||||
);
|
||||
|
||||
ngOnInit(): void {
|
||||
this.auth.openSignIn();
|
||||
}
|
||||
|
||||
protected signIn(): void {
|
||||
this.emailTouched.set(true);
|
||||
this.passwordTouched.set(true);
|
||||
const invalid =
|
||||
this.emailProblems().length > 0 || this.passwordProblems().length > 0;
|
||||
if (invalid || this.busy() || !this.configured()) return;
|
||||
this.auth.signInWithPassword(
|
||||
this.email().trim(),
|
||||
this.password(),
|
||||
this.returnUrl(),
|
||||
);
|
||||
}
|
||||
}
|
||||
27
libs/web/identity/presenters/tsconfig.json
Normal file
27
libs/web/identity/presenters/tsconfig.json
Normal file
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"extends": "../../../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"isolatedModules": true,
|
||||
"target": "es2022",
|
||||
"strict": true,
|
||||
"noImplicitOverride": true,
|
||||
"noPropertyAccessFromIndexSignature": true,
|
||||
"noImplicitReturns": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"emitDecoratorMetadata": false,
|
||||
"module": "preserve"
|
||||
},
|
||||
"angularCompilerOptions": {
|
||||
"enableI18nLegacyMessageIdFormat": false,
|
||||
"strictInjectionParameters": true,
|
||||
"strictInputAccessModifiers": true,
|
||||
"strictTemplates": true
|
||||
},
|
||||
"files": [],
|
||||
"include": [],
|
||||
"references": [
|
||||
{
|
||||
"path": "./tsconfig.lib.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
12
libs/web/identity/presenters/tsconfig.lib.json
Normal file
12
libs/web/identity/presenters/tsconfig.lib.json
Normal file
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "../../../../dist/out-tsc",
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"inlineSources": true,
|
||||
"types": []
|
||||
},
|
||||
"include": ["src/**/*.ts"],
|
||||
"exclude": ["src/**/*.spec.ts", "src/**/*.test.ts"]
|
||||
}
|
||||
20
libs/web/shared/infrastructure/README.md
Normal file
20
libs/web/shared/infrastructure/README.md
Normal file
@@ -0,0 +1,20 @@
|
||||
# web-shared-infrastructure
|
||||
|
||||
Cliente GraphQL de la web.
|
||||
|
||||
- **Import**: `@task-stream/web/shared/infrastructure`
|
||||
- **Capa**: `infrastructure` · **Tags**: `scope:web-shared`, `type:infrastructure`
|
||||
|
||||
## Contenido
|
||||
|
||||
- `provideGraphql()`: Apollo con HTTP para queries/mutations y `graphql-ws` para subscriptions; caché desactivada.
|
||||
- `AccessTokenSource` (puerto): de dónde sale el token (lo implementa identity).
|
||||
- `API_CONFIG` / `apiConfigFromLocation()`: la API se sirve en el mismo origen (`/api`, `/graphql`).
|
||||
|
||||
## Comandos
|
||||
|
||||
```sh
|
||||
npx nx lint web-shared-infrastructure
|
||||
```
|
||||
|
||||
Reglas de dependencia entre capas: [Arquitectura](../../../../docs/02-arquitectura.md#21-capas-hexagonales).
|
||||
34
libs/web/shared/infrastructure/eslint.config.mjs
Normal file
34
libs/web/shared/infrastructure/eslint.config.mjs
Normal file
@@ -0,0 +1,34 @@
|
||||
import nx from '@nx/eslint-plugin';
|
||||
import baseConfig from '../../../../eslint.config.mjs';
|
||||
|
||||
export default [
|
||||
...nx.configs['flat/angular'],
|
||||
...nx.configs['flat/angular-template'],
|
||||
...baseConfig,
|
||||
{
|
||||
files: ['**/*.ts'],
|
||||
rules: {
|
||||
'@angular-eslint/directive-selector': [
|
||||
'error',
|
||||
{
|
||||
type: 'attribute',
|
||||
prefix: 'ts',
|
||||
style: 'camelCase',
|
||||
},
|
||||
],
|
||||
'@angular-eslint/component-selector': [
|
||||
'error',
|
||||
{
|
||||
type: 'element',
|
||||
prefix: 'ts',
|
||||
style: 'kebab-case',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['**/*.html'],
|
||||
// Override or add rules here
|
||||
rules: {},
|
||||
},
|
||||
];
|
||||
13
libs/web/shared/infrastructure/project.json
Normal file
13
libs/web/shared/infrastructure/project.json
Normal file
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"name": "web-shared-infrastructure",
|
||||
"$schema": "../../../../node_modules/nx/schemas/project-schema.json",
|
||||
"sourceRoot": "libs/web/shared/infrastructure/src",
|
||||
"prefix": "ts",
|
||||
"projectType": "library",
|
||||
"tags": ["scope:web-shared", "type:infrastructure"],
|
||||
"targets": {
|
||||
"lint": {
|
||||
"executor": "@nx/eslint:lint"
|
||||
}
|
||||
}
|
||||
}
|
||||
4
libs/web/shared/infrastructure/src/index.ts
Normal file
4
libs/web/shared/infrastructure/src/index.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
export * from './lib/api-config';
|
||||
export * from './lib/access-token-source';
|
||||
export * from './lib/graphql.provider';
|
||||
export * from './lib/graphql-errors';
|
||||
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* Port used by the GraphQL client to authenticate requests. Implemented by
|
||||
* the identity context (which knows how to refresh and sign out).
|
||||
*/
|
||||
export abstract class AccessTokenSource {
|
||||
/** A valid access token (refreshed if needed), or null when signed out. */
|
||||
abstract accessToken(): Promise<string | null>;
|
||||
/** The API rejected the token: the session is over. */
|
||||
abstract unauthenticated(): void;
|
||||
}
|
||||
32
libs/web/shared/infrastructure/src/lib/api-config.ts
Normal file
32
libs/web/shared/infrastructure/src/lib/api-config.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import {
|
||||
InjectionToken,
|
||||
makeEnvironmentProviders,
|
||||
type EnvironmentProviders,
|
||||
} from '@angular/core';
|
||||
|
||||
export interface ApiConfig {
|
||||
/** Base of the REST endpoints, e.g. `/api`. */
|
||||
restUrl: string;
|
||||
/** GraphQL over HTTP, e.g. `/graphql`. */
|
||||
graphqlUrl: string;
|
||||
/** GraphQL subscriptions (graphql-ws), e.g. `ws://localhost:4200/graphql`. */
|
||||
graphqlWsUrl: string;
|
||||
}
|
||||
|
||||
export const API_CONFIG = new InjectionToken<ApiConfig>('API_CONFIG');
|
||||
|
||||
export function provideApiConfig(config: ApiConfig): EnvironmentProviders {
|
||||
return makeEnvironmentProviders([{ provide: API_CONFIG, useValue: config }]);
|
||||
}
|
||||
|
||||
/** Relative URLs resolved against the page, so the dev proxy / reverse proxy can serve the API. */
|
||||
export function apiConfigFromLocation(
|
||||
location: Location = window.location,
|
||||
): ApiConfig {
|
||||
const ws = location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
return {
|
||||
restUrl: '/api',
|
||||
graphqlUrl: '/graphql',
|
||||
graphqlWsUrl: `${ws}//${location.host}/graphql`,
|
||||
};
|
||||
}
|
||||
10
libs/web/shared/infrastructure/src/lib/graphql-errors.ts
Normal file
10
libs/web/shared/infrastructure/src/lib/graphql-errors.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { CombinedGraphQLErrors } from '@apollo/client/errors';
|
||||
|
||||
/** A message fit for a toast from whatever the GraphQL client threw. */
|
||||
export function errorMessage(error: unknown): string {
|
||||
if (CombinedGraphQLErrors.is(error)) {
|
||||
return error.errors.map((e) => e.message).join('\n');
|
||||
}
|
||||
if (error instanceof Error) return error.message;
|
||||
return String(error);
|
||||
}
|
||||
95
libs/web/shared/infrastructure/src/lib/graphql.provider.ts
Normal file
95
libs/web/shared/infrastructure/src/lib/graphql.provider.ts
Normal file
@@ -0,0 +1,95 @@
|
||||
import {
|
||||
inject,
|
||||
makeEnvironmentProviders,
|
||||
type EnvironmentProviders,
|
||||
} from '@angular/core';
|
||||
import { ApolloLink, InMemoryCache } from '@apollo/client';
|
||||
import { SetContextLink } from '@apollo/client/link/context';
|
||||
import { ErrorLink } from '@apollo/client/link/error';
|
||||
import { GraphQLWsLink } from '@apollo/client/link/subscriptions';
|
||||
import { getMainDefinition } from '@apollo/client/utilities';
|
||||
import { CombinedGraphQLErrors } from '@apollo/client/errors';
|
||||
import { provideApollo } from 'apollo-angular';
|
||||
import { HttpLink } from 'apollo-angular/http';
|
||||
import { createClient } from 'graphql-ws';
|
||||
import { AccessTokenSource } from './access-token-source';
|
||||
import { API_CONFIG } from './api-config';
|
||||
|
||||
/**
|
||||
* Apollo client for the task-stream API: HTTP for queries/mutations,
|
||||
* graphql-ws for subscriptions (token in `connection_init`).
|
||||
*
|
||||
* The cache is disabled on purpose: state lives in the NgRx signal stores,
|
||||
* which are fed by queries and kept fresh by subscriptions.
|
||||
*/
|
||||
export function provideGraphql(): EnvironmentProviders {
|
||||
return makeEnvironmentProviders([
|
||||
provideApollo(() => {
|
||||
const config = inject(API_CONFIG);
|
||||
const tokens = inject(AccessTokenSource);
|
||||
const httpLink = inject(HttpLink);
|
||||
|
||||
const auth = new SetContextLink(async (prevContext) => {
|
||||
const token = await tokens.accessToken();
|
||||
return token
|
||||
? {
|
||||
headers: {
|
||||
...prevContext['headers'],
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
}
|
||||
: {};
|
||||
});
|
||||
|
||||
const errors = new ErrorLink(({ error }) => {
|
||||
if (
|
||||
CombinedGraphQLErrors.is(error) &&
|
||||
error.errors.some((e) => e.extensions?.['code'] === 'UNAUTHENTICATED')
|
||||
) {
|
||||
tokens.unauthenticated();
|
||||
}
|
||||
});
|
||||
|
||||
const ws = new GraphQLWsLink(
|
||||
createClient({
|
||||
url: config.graphqlWsUrl,
|
||||
lazy: true,
|
||||
retryAttempts: Infinity,
|
||||
shouldRetry: () => true,
|
||||
connectionParams: async () => {
|
||||
const token = await tokens.accessToken();
|
||||
return token ? { authorization: `Bearer ${token}` } : {};
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const http = ApolloLink.from([
|
||||
auth,
|
||||
errors,
|
||||
httpLink.create({ uri: config.graphqlUrl }),
|
||||
]);
|
||||
|
||||
const link = ApolloLink.split(
|
||||
({ query }) => {
|
||||
const definition = getMainDefinition(query);
|
||||
return (
|
||||
definition.kind === 'OperationDefinition' &&
|
||||
definition.operation === 'subscription'
|
||||
);
|
||||
},
|
||||
ApolloLink.from([errors, ws]),
|
||||
http,
|
||||
);
|
||||
|
||||
return {
|
||||
link,
|
||||
cache: new InMemoryCache(),
|
||||
defaultOptions: {
|
||||
query: { fetchPolicy: 'no-cache' },
|
||||
watchQuery: { fetchPolicy: 'no-cache' },
|
||||
mutate: { fetchPolicy: 'no-cache' },
|
||||
},
|
||||
};
|
||||
}),
|
||||
]);
|
||||
}
|
||||
27
libs/web/shared/infrastructure/tsconfig.json
Normal file
27
libs/web/shared/infrastructure/tsconfig.json
Normal file
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"extends": "../../../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"isolatedModules": true,
|
||||
"target": "es2022",
|
||||
"strict": true,
|
||||
"noImplicitOverride": true,
|
||||
"noPropertyAccessFromIndexSignature": true,
|
||||
"noImplicitReturns": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"emitDecoratorMetadata": false,
|
||||
"module": "preserve"
|
||||
},
|
||||
"angularCompilerOptions": {
|
||||
"enableI18nLegacyMessageIdFormat": false,
|
||||
"strictInjectionParameters": true,
|
||||
"strictInputAccessModifiers": true,
|
||||
"strictTemplates": true
|
||||
},
|
||||
"files": [],
|
||||
"include": [],
|
||||
"references": [
|
||||
{
|
||||
"path": "./tsconfig.lib.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
12
libs/web/shared/infrastructure/tsconfig.lib.json
Normal file
12
libs/web/shared/infrastructure/tsconfig.lib.json
Normal file
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "../../../../dist/out-tsc",
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"inlineSources": true,
|
||||
"types": []
|
||||
},
|
||||
"include": ["src/**/*.ts"],
|
||||
"exclude": ["src/**/*.spec.ts", "src/**/*.test.ts"]
|
||||
}
|
||||
24
libs/web/shared/ui/README.md
Normal file
24
libs/web/shared/ui/README.md
Normal file
@@ -0,0 +1,24 @@
|
||||
# web-shared-ui
|
||||
|
||||
Integración de `@pi/ui` y piezas de interfaz comunes.
|
||||
|
||||
- **Import**: `@task-stream/web/shared/ui`
|
||||
- **Capa**: `presenters` · **Tags**: `scope:web-shared`, `type:presenters`
|
||||
|
||||
## Contenido
|
||||
|
||||
- `providePiUi()`: animaciones, iconos, textos de la librería, tema y modo oscuro.
|
||||
- `icons.ts`: iconos SVG en línea, incluidos los que usa la propia librería.
|
||||
- `AppearanceService` (modo oscuro), `ToastService` (`pi-snack-bar`), `DrawerService` (`pi-drawer`), `AppShellComponent`
|
||||
(la cabecera de pireon.dev: logo, «Pireon | TaskStream», luces de fondo) y `LogoComponent` (el logo de pireon.dev,
|
||||
en `apps/web/public`).
|
||||
|
||||
Particularidades de `@pi/ui`: [Cliente web](../../../../docs/04-cliente-web.md#44-piui).
|
||||
|
||||
## Comandos
|
||||
|
||||
```sh
|
||||
npx nx lint web-shared-ui
|
||||
```
|
||||
|
||||
Reglas de dependencia entre capas: [Arquitectura](../../../../docs/02-arquitectura.md#21-capas-hexagonales).
|
||||
34
libs/web/shared/ui/eslint.config.mjs
Normal file
34
libs/web/shared/ui/eslint.config.mjs
Normal file
@@ -0,0 +1,34 @@
|
||||
import nx from '@nx/eslint-plugin';
|
||||
import baseConfig from '../../../../eslint.config.mjs';
|
||||
|
||||
export default [
|
||||
...nx.configs['flat/angular'],
|
||||
...nx.configs['flat/angular-template'],
|
||||
...baseConfig,
|
||||
{
|
||||
files: ['**/*.ts'],
|
||||
rules: {
|
||||
'@angular-eslint/directive-selector': [
|
||||
'error',
|
||||
{
|
||||
type: 'attribute',
|
||||
prefix: 'ts',
|
||||
style: 'camelCase',
|
||||
},
|
||||
],
|
||||
'@angular-eslint/component-selector': [
|
||||
'error',
|
||||
{
|
||||
type: 'element',
|
||||
prefix: 'ts',
|
||||
style: 'kebab-case',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['**/*.html'],
|
||||
// Override or add rules here
|
||||
rules: {},
|
||||
},
|
||||
];
|
||||
13
libs/web/shared/ui/project.json
Normal file
13
libs/web/shared/ui/project.json
Normal file
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"name": "web-shared-ui",
|
||||
"$schema": "../../../../node_modules/nx/schemas/project-schema.json",
|
||||
"sourceRoot": "libs/web/shared/ui/src",
|
||||
"prefix": "ts",
|
||||
"projectType": "library",
|
||||
"tags": ["scope:web-shared", "type:presenters"],
|
||||
"targets": {
|
||||
"lint": {
|
||||
"executor": "@nx/eslint:lint"
|
||||
}
|
||||
}
|
||||
}
|
||||
7
libs/web/shared/ui/src/index.ts
Normal file
7
libs/web/shared/ui/src/index.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
export * from './lib/pi-ui.providers';
|
||||
export * from './lib/appearance';
|
||||
export * from './lib/toast.service';
|
||||
export * from './lib/app-shell';
|
||||
export * from './lib/icons';
|
||||
export * from './lib/drawer.service';
|
||||
export * from './lib/logo';
|
||||
188
libs/web/shared/ui/src/lib/app-shell.scss
Normal file
188
libs/web/shared/ui/src/lib/app-shell.scss
Normal file
@@ -0,0 +1,188 @@
|
||||
:host {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 100vh;
|
||||
// The lights below spill sideways: clipped here (not `hidden`, which would
|
||||
// make a scroll container and break the sticky header).
|
||||
overflow-x: clip;
|
||||
}
|
||||
|
||||
// Same bar as pireon.dev's site header.
|
||||
.ts-header {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 50;
|
||||
background-color: color-mix(in srgb, var(--ts-surface) 88%, transparent);
|
||||
backdrop-filter: blur(12px);
|
||||
border-bottom: 1px solid var(--ts-line);
|
||||
}
|
||||
|
||||
.ts-header__inner {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1.5rem;
|
||||
max-width: 96rem;
|
||||
height: 4rem;
|
||||
margin-inline: auto;
|
||||
padding-inline: 1.25rem;
|
||||
box-sizing: border-box;
|
||||
|
||||
@media (min-width: 768px) {
|
||||
padding-inline: 2rem;
|
||||
}
|
||||
}
|
||||
|
||||
.ts-brand {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.625rem;
|
||||
color: var(--ts-ink);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.ts-brand__platform {
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
// The product, after the platform: "Pireon | TaskStream".
|
||||
.ts-brand__product {
|
||||
padding-left: 0.625rem;
|
||||
border-left: 1px solid var(--ts-line-strong);
|
||||
font-weight: 600;
|
||||
background: linear-gradient(
|
||||
100deg,
|
||||
var(--pi-color-primary),
|
||||
var(--pi-color-accent)
|
||||
);
|
||||
-webkit-background-clip: text;
|
||||
background-clip: text;
|
||||
color: transparent;
|
||||
}
|
||||
|
||||
.ts-header__nav {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.25rem;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow-x: auto;
|
||||
scrollbar-width: none;
|
||||
}
|
||||
|
||||
.ts-header__actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.ts-header__icon {
|
||||
--ts-icon-button-size: 2.25rem;
|
||||
--ts-icon-button-border: var(--ts-line);
|
||||
color: var(--ts-muted);
|
||||
transition:
|
||||
color 0.15s ease,
|
||||
background-color 0.15s ease;
|
||||
|
||||
&:hover {
|
||||
color: var(--ts-ink);
|
||||
background: var(--pi-color-primary-25);
|
||||
}
|
||||
}
|
||||
|
||||
// A shadow under the header once the page moves, as on pireon.dev.
|
||||
@keyframes header-lift {
|
||||
to {
|
||||
border-bottom-color: transparent;
|
||||
box-shadow: 0 10px 30px -18px
|
||||
color-mix(in srgb, var(--pi-color-primary) 45%, transparent);
|
||||
}
|
||||
}
|
||||
|
||||
@supports (animation-timeline: scroll()) {
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
.ts-header {
|
||||
animation: header-lift linear both;
|
||||
animation-timeline: scroll(root);
|
||||
animation-range: 0 5rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Content over the platform's two soft lights (pireon.dev's `glow`).
|
||||
.ts-main {
|
||||
position: relative;
|
||||
isolation: isolate;
|
||||
flex: 1;
|
||||
width: 100%;
|
||||
max-width: 96rem;
|
||||
margin-inline: auto;
|
||||
padding: 2.5rem 1.25rem 4rem;
|
||||
box-sizing: border-box;
|
||||
|
||||
@media (min-width: 768px) {
|
||||
padding-inline: 2rem;
|
||||
}
|
||||
|
||||
&::before,
|
||||
&::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
z-index: -1;
|
||||
border-radius: 50%;
|
||||
pointer-events: none;
|
||||
filter: blur(80px);
|
||||
}
|
||||
|
||||
&::before {
|
||||
top: -16rem;
|
||||
left: 50%;
|
||||
width: 64rem;
|
||||
height: 34rem;
|
||||
transform: translateX(-58%);
|
||||
opacity: 0.4;
|
||||
background: radial-gradient(
|
||||
closest-side,
|
||||
var(--pi-color-primary),
|
||||
transparent
|
||||
);
|
||||
}
|
||||
|
||||
&::after {
|
||||
top: -4rem;
|
||||
right: -10rem;
|
||||
width: 26rem;
|
||||
height: 26rem;
|
||||
opacity: 0.28;
|
||||
background: radial-gradient(
|
||||
closest-side,
|
||||
var(--pi-color-accent),
|
||||
transparent
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.ts-header__inner {
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.ts-brand__platform {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.ts-brand__product {
|
||||
padding-left: 0;
|
||||
border-left: 0;
|
||||
}
|
||||
|
||||
.ts-main {
|
||||
padding-top: 1.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
// On a phone the brand already leads to the projects list.
|
||||
@media (max-width: 480px) {
|
||||
.ts-header__nav {
|
||||
visibility: hidden;
|
||||
}
|
||||
}
|
||||
54
libs/web/shared/ui/src/lib/app-shell.ts
Normal file
54
libs/web/shared/ui/src/lib/app-shell.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import { ChangeDetectionStrategy, Component, inject } from '@angular/core';
|
||||
import { RouterLink } from '@angular/router';
|
||||
import { PiIconComponent } from '@pi/ui';
|
||||
import { AppearanceService } from './appearance';
|
||||
import { LogoComponent } from './logo';
|
||||
|
||||
/**
|
||||
* Page frame, in the Pireon platform's look (same header as pireon.dev):
|
||||
* translucent bar with the Pireon mark and the product name, navigation,
|
||||
* appearance and user; the routed content over the platform's soft lights.
|
||||
* Navigation and user menu are projected by the app.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'ts-app-shell',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
imports: [RouterLink, PiIconComponent, LogoComponent],
|
||||
styleUrl: './app-shell.scss',
|
||||
template: `
|
||||
<header class="ts-header">
|
||||
<div class="ts-header__inner">
|
||||
<a
|
||||
class="ts-brand"
|
||||
routerLink="/"
|
||||
aria-label="Pireon TaskStream, inicio"
|
||||
>
|
||||
<ts-logo [size]="32" />
|
||||
<span class="ts-brand__platform">Pireon</span>
|
||||
<span class="ts-brand__product">TaskStream</span>
|
||||
</a>
|
||||
<nav class="ts-header__nav" aria-label="Principal">
|
||||
<ng-content select="[shellNav]" />
|
||||
</nav>
|
||||
<div class="ts-header__actions">
|
||||
<button
|
||||
type="button"
|
||||
class="ts-icon-button ts-header__icon"
|
||||
[attr.aria-label]="appearance.dark() ? 'Modo claro' : 'Modo oscuro'"
|
||||
[attr.title]="appearance.dark() ? 'Modo claro' : 'Modo oscuro'"
|
||||
(click)="appearance.toggle()"
|
||||
>
|
||||
<pi-icon [icon]="appearance.dark() ? 'sun' : 'moon'" size="small" />
|
||||
</button>
|
||||
<ng-content select="[shellUser]" />
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
<main class="ts-main">
|
||||
<ng-content />
|
||||
</main>
|
||||
`,
|
||||
})
|
||||
export class AppShellComponent {
|
||||
protected readonly appearance = inject(AppearanceService);
|
||||
}
|
||||
46
libs/web/shared/ui/src/lib/appearance.ts
Normal file
46
libs/web/shared/ui/src/lib/appearance.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* Dark mode, owned here rather than by `@pi/ui`.
|
||||
*
|
||||
* `PiThemeService` toggles `html.dark-mode` and persists the choice, but it
|
||||
* reads its key back with `!!localStorage.getItem(key)` while writing the
|
||||
* boolean as a string — so `"false"` reads back as dark. (Same workaround as
|
||||
* landing-web.) This service keeps its own key and drives the library.
|
||||
*/
|
||||
import { computed, inject, Injectable } from '@angular/core';
|
||||
import { PiThemeService } from '@pi/ui';
|
||||
|
||||
const APPEARANCE_KEY = 'task-stream.appearance';
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class AppearanceService {
|
||||
private readonly theme = inject(PiThemeService);
|
||||
|
||||
readonly dark = computed(() => this.theme.darkMode());
|
||||
|
||||
restore(): void {
|
||||
this.theme.setDarkMode(this.preferred());
|
||||
}
|
||||
|
||||
toggle(): void {
|
||||
this.set(!this.dark());
|
||||
}
|
||||
|
||||
set(dark: boolean): void {
|
||||
this.theme.setDarkMode(dark);
|
||||
try {
|
||||
localStorage.setItem(APPEARANCE_KEY, dark ? 'dark' : 'light');
|
||||
} catch {
|
||||
// Storage disabled: the choice lasts this visit only.
|
||||
}
|
||||
}
|
||||
|
||||
private preferred(): boolean {
|
||||
try {
|
||||
const stored = localStorage.getItem(APPEARANCE_KEY);
|
||||
if (stored === 'dark' || stored === 'light') return stored === 'dark';
|
||||
} catch {
|
||||
// Fall through to the system preference.
|
||||
}
|
||||
return window.matchMedia?.('(prefers-color-scheme: dark)').matches ?? false;
|
||||
}
|
||||
}
|
||||
24
libs/web/shared/ui/src/lib/drawer.service.ts
Normal file
24
libs/web/shared/ui/src/lib/drawer.service.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { inject, Injectable, TemplateRef } from '@angular/core';
|
||||
import { MatDialog, MatDialogRef } from '@angular/material/dialog';
|
||||
import { DrawerConfigKeys, getDrawerConfigs, PiDrawerComponent } from '@pi/ui';
|
||||
|
||||
/** Side panel for forms (new ticket, new release…) with the library's `pi-drawer`. */
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class DrawerService {
|
||||
private readonly dialog = inject(MatDialog);
|
||||
|
||||
open(
|
||||
title: string,
|
||||
template: TemplateRef<unknown>,
|
||||
width = '32rem',
|
||||
): MatDialogRef<PiDrawerComponent> {
|
||||
return this.dialog.open(PiDrawerComponent, {
|
||||
...getDrawerConfigs(DrawerConfigKeys.Right, { title, template } as never),
|
||||
width,
|
||||
});
|
||||
}
|
||||
|
||||
closeAll(): void {
|
||||
this.dialog.closeAll();
|
||||
}
|
||||
}
|
||||
182
libs/web/shared/ui/src/lib/icons.ts
Normal file
182
libs/web/shared/ui/src/lib/icons.ts
Normal file
@@ -0,0 +1,182 @@
|
||||
/**
|
||||
* The app's icon set, inlined (same stroke style as the landing's).
|
||||
*
|
||||
* `@pi/ui` ships no SVGs: `pi-icon` renders a `mat-icon` whose name is looked
|
||||
* up in Material's registry. Registering literals avoids one HTTP request per
|
||||
* icon and works offline.
|
||||
*/
|
||||
import {
|
||||
inject,
|
||||
makeEnvironmentProviders,
|
||||
provideAppInitializer,
|
||||
type EnvironmentProviders,
|
||||
} from '@angular/core';
|
||||
import { DomSanitizer } from '@angular/platform-browser';
|
||||
import { MatIconRegistry } from '@angular/material/icon';
|
||||
|
||||
export const APP_ICONS: Record<string, string> = {
|
||||
'arrow-forward':
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M4 12h15M13 6l6 6-6 6"/></svg>',
|
||||
briefcase:
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="7" width="18" height="13" rx="2"/><path d="M9 7V5a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v2M3 12h18"/></svg>',
|
||||
buildings:
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M3 21V8l6-3v16M9 21h12V11l-6-2M13 21v-4h4v4"/><path d="M6 11h.01M6 15h.01"/></svg>',
|
||||
calendar:
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="5" width="18" height="16" rx="2"/><path d="M3 10h18M8 3v4M16 3v4"/></svg>',
|
||||
chat: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a8 8 0 0 1-11.6 7.1L4 20.5l1.4-5.2A8 8 0 1 1 21 12Z"/></svg>',
|
||||
'check-rounded':
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="m8 12.2 2.7 2.8L16 9.5"/></svg>',
|
||||
check:
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="m4.5 12.5 5 5 10-11"/></svg>',
|
||||
'chevron-back':
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="m14.5 6-6 6 6 6"/></svg>',
|
||||
'chevron-down':
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="m6 9.5 6 6 6-6"/></svg>',
|
||||
'chevron-forward':
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="m9.5 6 6 6-6 6"/></svg>',
|
||||
'chevron-up':
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="m6 14.5 6-6 6 6"/></svg>',
|
||||
'close-rounded':
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="m9 9 6 6M15 9l-6 6"/></svg>',
|
||||
close:
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M6 6l12 12M18 6 6 18"/></svg>',
|
||||
coins:
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><ellipse cx="12" cy="6.5" rx="7" ry="3"/><path d="M5 6.5v5c0 1.7 3.1 3 7 3s7-1.3 7-3v-5M5 11.5v5c0 1.7 3.1 3 7 3s7-1.3 7-3v-5"/></svg>',
|
||||
document:
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8l-5-5Z"/><path d="M14 3v5h5M9 13h6M9 17h4"/></svg>',
|
||||
email:
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="5" width="18" height="14" rx="2"/><path d="m3.5 7 7.4 5.3a2 2 0 0 0 2.2 0L20.5 7"/></svg>',
|
||||
exclamation:
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="M12 7.5v5.5M12 16.3h.01"/></svg>',
|
||||
focus:
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M3 8V5a2 2 0 0 1 2-2h3M16 3h3a2 2 0 0 1 2 2v3M21 16v3a2 2 0 0 1-2 2h-3M8 21H5a2 2 0 0 1-2-2v-3"/></svg>',
|
||||
globe:
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a15 15 0 0 1 0 18 15 15 0 0 1 0-18Z"/></svg>',
|
||||
graphic:
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M4 20V4M4 20h16"/><path d="m7.5 15 3.5-4 3 2.6L20 7"/></svg>',
|
||||
grid: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="7.5" height="7.5" rx="1.5"/><rect x="13.5" y="3" width="7.5" height="7.5" rx="1.5"/><rect x="3" y="13.5" width="7.5" height="7.5" rx="1.5"/><rect x="13.5" y="13.5" width="7.5" height="7.5" rx="1.5"/></svg>',
|
||||
info: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="M12 11v5.5M12 7.7h.01"/></svg>',
|
||||
'light-bulb':
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M9 18h6M10 21h4"/><path d="M12 3a6 6 0 0 0-3.5 10.9c.6.4 1 1.1 1 1.9v.2h5v-.2c0-.8.4-1.5 1-1.9A6 6 0 0 0 12 3Z"/></svg>',
|
||||
link: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.1.1l2.9-2.9a5 5 0 0 0-7.1-7.1L11 4.9"/><path d="M14 11a5 5 0 0 0-7.1-.1L4 13.8a5 5 0 0 0 7.1 7.1l1.9-1.9"/></svg>',
|
||||
list: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M8 6h13M8 12h13M8 18h13M3.5 6h.01M3.5 12h.01M3.5 18h.01"/></svg>',
|
||||
location:
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M12 21s7-5.6 7-11a7 7 0 1 0-14 0c0 5.4 7 11 7 11Z"/><circle cx="12" cy="10" r="2.5"/></svg>',
|
||||
moon: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M20 13.4A8 8 0 1 1 10.6 4a6.6 6.6 0 0 0 9.4 9.4Z"/></svg>',
|
||||
'play-arrow':
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M8 5.5v13l10-6.5-10-6.5Z"/></svg>',
|
||||
search:
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="6.5"/><path d="m16 16 4.5 4.5"/></svg>',
|
||||
'star-fill':
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="m12 3.6 2.5 5.2 5.7.8-4.1 4 1 5.6-5.1-2.7-5.1 2.7 1-5.6-4.1-4 5.7-.8L12 3.6Z"/></svg>',
|
||||
sun: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="4"/><path d="M12 2.5v2M12 19.5v2M2.5 12h2M19.5 12h2M5.3 5.3l1.4 1.4M17.3 17.3l1.4 1.4M18.7 5.3l-1.4 1.4M6.7 17.3l-1.4 1.4"/></svg>',
|
||||
support:
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="M9.5 9.5 5.6 5.6M14.5 9.5l3.9-3.9M14.5 14.5l3.9 3.9M9.5 14.5l-3.9 3.9"/><circle cx="12" cy="12" r="3.5"/></svg>',
|
||||
'time-detail':
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="M12 7v5.2l3.2 2"/></svg>',
|
||||
user: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="8" r="4"/><path d="M4 21v-1a6 6 0 0 1 6-6h4a6 6 0 0 1 6 6v1"/></svg>',
|
||||
'verification-list':
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M9 4h9a2 2 0 0 1 2 2v13a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V8"/><path d="M4 5.5 5.8 7.5 9 3.8M9 11h7M9 15h5"/></svg>',
|
||||
plus: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M12 5v14M5 12h14"/></svg>',
|
||||
bug: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><rect x="7" y="7" width="10" height="13" rx="5"/><path d="M12 11v9M9 4l1.5 2.5M15 4l-1.5 2.5M3 13h4M17 13h4M4 8l3 2M20 8l-3 2M4 19l3-2M20 19l-3-2"/></svg>',
|
||||
kanban:
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="16" rx="2"/><path d="M9 4v16M15 4v16"/></svg>',
|
||||
rocket:
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M5 15c-1 1-1.5 4-1.5 4.5s3.5-.5 4.5-1.5M9 12l3 3M14.5 4.5c2-1 4.5-1 5-.5s.5 3-.5 5L13 15.5 8.5 11Z"/><circle cx="15.5" cy="8.5" r="1.25"/></svg>',
|
||||
users:
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><circle cx="9" cy="8" r="3.5"/><path d="M2.5 20a6.5 6.5 0 0 1 13 0M16 4.6a3.5 3.5 0 0 1 0 6.8M18.5 14.5a6.5 6.5 0 0 1 3 5.5"/></svg>',
|
||||
logout:
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M15 4h3a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2h-3M10 16l-4-4 4-4M6 12h10"/></svg>',
|
||||
trash:
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M4 7h16M9 7V4h6v3M6 7l1 13h10l1-13M10 11v6M14 11v6"/></svg>',
|
||||
edit: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M4 20h4L19 9l-4-4L4 16v4ZM13.5 6.5l4 4"/></svg>',
|
||||
activity:
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12h4l3-8 4 16 3-8h4"/></svg>',
|
||||
flag: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M5 21V4M5 4h11l-2 4 2 4H5"/></svg>',
|
||||
filter:
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M4 5h16l-6 8v6l-4-2v-4Z"/></svg>',
|
||||
qa: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="7"/><path d="m8.5 11 2 2 3.5-4M20 20l-4-4"/></svg>',
|
||||
figma:
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M9 3h3v6H9a3 3 0 0 1 0-6ZM12 3h3a3 3 0 0 1 0 6h-3ZM9 9h3v6H9a3 3 0 0 1 0-6ZM12 12a3 3 0 1 1 6 0 3 3 0 0 1-6 0ZM9 15h3v3a3 3 0 1 1-3-3Z"/></svg>',
|
||||
key: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><circle cx="8" cy="15" r="4"/><path d="m11 12 9-9M16 7l3 3M14 9l2 2"/></svg>',
|
||||
archive:
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="5" rx="1"/><path d="M5 9v10a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V9M10 13h4"/></svg>',
|
||||
feature:
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="m12 3 2.6 5.3 5.9.9-4.3 4.1 1 5.8L12 16.4 6.8 19.1l1-5.8L3.5 9.2l5.9-.9Z"/></svg>',
|
||||
task: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><rect x="4" y="4" width="16" height="16" rx="3"/><path d="m8.5 12 2.5 2.5 4.5-5"/></svg>',
|
||||
palette:
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3a9 9 0 0 0 0 18c1.1 0 1.5-.8 1.5-1.5 0-1.2-1-1.5-1-2.5s.7-1.5 1.7-1.5H17a4 4 0 0 0 4-4c0-4.7-4-8.5-9-8.5Z"/><circle cx="7.5" cy="11" r="1"/><circle cx="10" cy="7" r="1"/><circle cx="15" cy="7.5" r="1"/></svg>',
|
||||
eye: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12Z"/><circle cx="12" cy="12" r="3"/></svg>',
|
||||
'eye-off':
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M3 3l18 18M10.6 5.1A10.4 10.4 0 0 1 12 5c6.5 0 10 7 10 7a17 17 0 0 1-3.2 4.1M6.6 6.6A17 17 0 0 0 2 12s3.5 7 10 7a10 10 0 0 0 5.4-1.6M9.9 9.9a3 3 0 0 0 4.2 4.2"/></svg>',
|
||||
add: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M12 5v14M5 12h14"/></svg>',
|
||||
substract:
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/></svg>',
|
||||
'arrow-back':
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M20 12H5M11 6l-6 6 6 6"/></svg>',
|
||||
'arrow-up':
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20V5M6 11l6-6 6 6"/></svg>',
|
||||
'arrow-down':
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M12 4v15M6 13l6 6 6-6"/></svg>',
|
||||
'arrow-up-rounded':
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="M12 16V8M8.5 11.5 12 8l3.5 3.5"/></svg>',
|
||||
'arrow-secondary-back':
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="m14.5 6-6 6 6 6"/></svg>',
|
||||
'arrow-secondary-forward':
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="m9.5 6 6 6-6 6"/></svg>',
|
||||
'arrow-secondary-up':
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="m6 14.5 6-6 6 6"/></svg>',
|
||||
'arrow-secondary-down':
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="m6 9.5 6 6 6-6"/></svg>',
|
||||
'double-chevron-back':
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="m12 6-6 6 6 6M18 6l-6 6 6 6"/></svg>',
|
||||
error:
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="M12 7.5v5.5M12 16.5h.01"/></svg>',
|
||||
'info-rounded':
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="M12 11v5.5M12 7.5h.01"/></svg>',
|
||||
lock: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></svg>',
|
||||
more: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><circle cx="5" cy="12" r="1.25"/><circle cx="12" cy="12" r="1.25"/><circle cx="19" cy="12" r="1.25"/></svg>',
|
||||
'open-details':
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M14 4h6v6M20 4l-9 9M18 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1h5"/></svg>',
|
||||
'star-outline':
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="m12 3 2.6 5.3 5.9.9-4.3 4.1 1 5.8L12 16.4 6.8 19.1l1-5.8L3.5 9.2l5.9-.9Z"/></svg>',
|
||||
'star-primary':
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="m12 3 2.6 5.3 5.9.9-4.3 4.1 1 5.8L12 16.4 6.8 19.1l1-5.8L3.5 9.2l5.9-.9Z"/></svg>',
|
||||
start:
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M7 5v14l11-7Z"/></svg>',
|
||||
upload:
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M12 16V4M7 9l5-5 5 5M4 20h16"/></svg>',
|
||||
download:
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M12 4v12M7 11l5 5 5-5M4 20h16"/></svg>',
|
||||
'download-teaser':
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M12 4v12M7 11l5 5 5-5M4 20h16"/></svg>',
|
||||
'calendar-plus':
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="5" width="18" height="16" rx="2"/><path d="M3 10h18M8 3v4M16 3v4M12 13v5M9.5 15.5h5"/></svg>',
|
||||
bullet:
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="2.5"/></svg>',
|
||||
'time-zone':
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a14 14 0 0 1 0 18M12 3a14 14 0 0 0 0 18"/></svg>',
|
||||
'user-profile':
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="8" r="4"/><path d="M4 21a8 8 0 0 1 16 0"/></svg>',
|
||||
'user-profile-advisor':
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="8" r="4"/><path d="M4 21a8 8 0 0 1 16 0"/></svg>',
|
||||
'user-profile-company':
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M3 21V8l6-3v16M9 21h12V11l-6-2"/></svg>',
|
||||
whatsapp:
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a8 8 0 0 1-11.6 7.1L4 20.5l1.4-5.2A8 8 0 1 1 21 12Z"/></svg>',
|
||||
};
|
||||
|
||||
export function provideAppIcons(): EnvironmentProviders {
|
||||
return makeEnvironmentProviders([
|
||||
provideAppInitializer(() => {
|
||||
const registry = inject(MatIconRegistry);
|
||||
const sanitizer = inject(DomSanitizer);
|
||||
for (const [name, svg] of Object.entries(APP_ICONS)) {
|
||||
registry.addSvgIconLiteral(
|
||||
name,
|
||||
sanitizer.bypassSecurityTrustHtml(svg),
|
||||
);
|
||||
}
|
||||
}),
|
||||
]);
|
||||
}
|
||||
30
libs/web/shared/ui/src/lib/logo.ts
Normal file
30
libs/web/shared/ui/src/lib/logo.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { ChangeDetectionStrategy, Component, input } from '@angular/core';
|
||||
|
||||
/** Pireon mark (same asset as pireon.dev, served from `apps/web/public`). */
|
||||
@Component({
|
||||
selector: 'ts-logo',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
template: `
|
||||
<img
|
||||
src="logo-96.png"
|
||||
srcset="logo-96.png 96w, logo.png 256w"
|
||||
[attr.sizes]="size() + 'px'"
|
||||
alt=""
|
||||
[width]="size()"
|
||||
[height]="size()"
|
||||
decoding="async"
|
||||
/>
|
||||
`,
|
||||
styles: `
|
||||
:host {
|
||||
display: inline-flex;
|
||||
}
|
||||
img {
|
||||
display: block;
|
||||
object-fit: contain;
|
||||
}
|
||||
`,
|
||||
})
|
||||
export class LogoComponent {
|
||||
readonly size = input(24);
|
||||
}
|
||||
40
libs/web/shared/ui/src/lib/pi-strings.ts
Normal file
40
libs/web/shared/ui/src/lib/pi-strings.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* The few strings `@pi/ui` translates itself (field errors, close labels,
|
||||
* chart legends), provided synchronously instead of `providePiTranslate()`
|
||||
* (which fetches ./assets/i18n/*.json).
|
||||
*/
|
||||
import {
|
||||
inject,
|
||||
makeEnvironmentProviders,
|
||||
provideAppInitializer,
|
||||
type EnvironmentProviders,
|
||||
} from '@angular/core';
|
||||
import { provideTranslateService, TranslateService } from '@ngx-translate/core';
|
||||
|
||||
export function providePiStrings(): EnvironmentProviders {
|
||||
return makeEnvironmentProviders([
|
||||
provideTranslateService({ fallbackLang: 'es' }),
|
||||
provideAppInitializer(() => {
|
||||
const translate = inject(TranslateService);
|
||||
translate.setTranslation('es', {
|
||||
common: {
|
||||
close: 'Cerrar',
|
||||
edit: 'Editar',
|
||||
legend: 'Leyenda',
|
||||
min: 'Mín',
|
||||
max: 'Máx',
|
||||
confidentialInfo: 'Información confidencial',
|
||||
},
|
||||
// Signal Forms error kinds (pi fields show `error.message ?? error.kind`).
|
||||
required: 'Campo obligatorio',
|
||||
email: 'Email no válido',
|
||||
minLength: 'Demasiado corto',
|
||||
maxLength: 'Demasiado largo',
|
||||
pattern: 'Formato no válido',
|
||||
min: 'Valor demasiado bajo',
|
||||
max: 'Valor demasiado alto',
|
||||
});
|
||||
translate.use('es');
|
||||
}),
|
||||
]);
|
||||
}
|
||||
25
libs/web/shared/ui/src/lib/pi-ui.providers.ts
Normal file
25
libs/web/shared/ui/src/lib/pi-ui.providers.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import {
|
||||
inject,
|
||||
makeEnvironmentProviders,
|
||||
provideAppInitializer,
|
||||
type EnvironmentProviders,
|
||||
} from '@angular/core';
|
||||
import { provideAnimationsAsync } from '@angular/platform-browser/animations/async';
|
||||
import { PiThemeService } from '@pi/ui';
|
||||
import { AppearanceService } from './appearance';
|
||||
import { provideAppIcons } from './icons';
|
||||
import { providePiStrings } from './pi-strings';
|
||||
|
||||
/** Everything `@pi/ui` needs: animations, icons, strings, theme and dark mode. */
|
||||
export function providePiUi(): EnvironmentProviders {
|
||||
return makeEnvironmentProviders([
|
||||
// @pi/ui still uses @angular/animations (collapse/fade triggers), so this stays
|
||||
// despite its deprecation in Angular 20.2.
|
||||
provideAnimationsAsync(),
|
||||
provideAppIcons(),
|
||||
providePiStrings(),
|
||||
// `default` is the library's application shell (the landing uses `alternative`, its marketing one).
|
||||
provideAppInitializer(() => inject(PiThemeService).setTheme('default')),
|
||||
provideAppInitializer(() => inject(AppearanceService).restore()),
|
||||
]);
|
||||
}
|
||||
37
libs/web/shared/ui/src/lib/toast.service.ts
Normal file
37
libs/web/shared/ui/src/lib/toast.service.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { MatSnackBar } from '@angular/material/snack-bar';
|
||||
import { PiSnackBarComponent } from '@pi/ui';
|
||||
|
||||
type ToastType = 'success' | 'error' | 'info';
|
||||
|
||||
/** Feedback toasts with the library's `pi-snack-bar`. */
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class ToastService {
|
||||
private readonly snackBar = inject(MatSnackBar);
|
||||
|
||||
success(message: string): void {
|
||||
this.open(message, 'success', 'check-rounded', 3000);
|
||||
}
|
||||
|
||||
error(message: string): void {
|
||||
this.open(message, 'error', 'exclamation', 6000);
|
||||
}
|
||||
|
||||
info(message: string): void {
|
||||
this.open(message, 'info', 'info', 3000);
|
||||
}
|
||||
|
||||
private open(
|
||||
message: string,
|
||||
type: ToastType,
|
||||
icon: string,
|
||||
duration: number,
|
||||
): void {
|
||||
this.snackBar.openFromComponent(PiSnackBarComponent, {
|
||||
data: { message, type, icon, dismissible: true },
|
||||
duration,
|
||||
horizontalPosition: 'end',
|
||||
verticalPosition: 'bottom',
|
||||
});
|
||||
}
|
||||
}
|
||||
27
libs/web/shared/ui/tsconfig.json
Normal file
27
libs/web/shared/ui/tsconfig.json
Normal file
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"extends": "../../../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"isolatedModules": true,
|
||||
"target": "es2022",
|
||||
"strict": true,
|
||||
"noImplicitOverride": true,
|
||||
"noPropertyAccessFromIndexSignature": true,
|
||||
"noImplicitReturns": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"emitDecoratorMetadata": false,
|
||||
"module": "preserve"
|
||||
},
|
||||
"angularCompilerOptions": {
|
||||
"enableI18nLegacyMessageIdFormat": false,
|
||||
"strictInjectionParameters": true,
|
||||
"strictInputAccessModifiers": true,
|
||||
"strictTemplates": true
|
||||
},
|
||||
"files": [],
|
||||
"include": [],
|
||||
"references": [
|
||||
{
|
||||
"path": "./tsconfig.lib.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
12
libs/web/shared/ui/tsconfig.lib.json
Normal file
12
libs/web/shared/ui/tsconfig.lib.json
Normal file
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "../../../../dist/out-tsc",
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"inlineSources": true,
|
||||
"types": []
|
||||
},
|
||||
"include": ["src/**/*.ts"],
|
||||
"exclude": ["src/**/*.spec.ts", "src/**/*.test.ts"]
|
||||
}
|
||||
26
libs/web/tracker/application/README.md
Normal file
26
libs/web/tracker/application/README.md
Normal file
@@ -0,0 +1,26 @@
|
||||
# web-tracker-application
|
||||
|
||||
Estado del tracker (NgRx Signals con eventos) detrás de facades.
|
||||
|
||||
- **Import**: `@task-stream/web/tracker/application`
|
||||
- **Capa**: `application` · **Tags**: `scope:web-tracker`, `type:application`
|
||||
|
||||
## Contenido
|
||||
|
||||
- Facades (lo que se exporta): `ProjectsFacade` (raíz) y `ProjectFacade`, `BoardFacade`, `IssueFacade` (de ruta, con
|
||||
`provideProjectFacade()`, `provideBoardFacade()`, `provideIssueFacade()`). Tests en `facades/facades.spec.ts`.
|
||||
- Interno: stores `ProjectsStore`, `ProjectStore`, `BoardStore`, `IssueStore` y eventos por origen
|
||||
(`*PageEvents`, `*ApiEvents`, `*RealtimeEvents`).
|
||||
- `board.reducers.ts`: transformaciones puras del tablero (movimiento optimista, cambios en vivo por versión).
|
||||
- Puerto `Notifications`.
|
||||
|
||||
Patrón de eventos: [Cliente web](../../../../docs/04-cliente-web.md#42-estado-ngrx-signals-con-eventos).
|
||||
|
||||
## Comandos
|
||||
|
||||
```sh
|
||||
npx nx lint web-tracker-application
|
||||
npx nx test web-tracker-application # Vitest
|
||||
```
|
||||
|
||||
Reglas de dependencia entre capas: [Arquitectura](../../../../docs/02-arquitectura.md#21-capas-hexagonales).
|
||||
34
libs/web/tracker/application/eslint.config.mjs
Normal file
34
libs/web/tracker/application/eslint.config.mjs
Normal file
@@ -0,0 +1,34 @@
|
||||
import nx from '@nx/eslint-plugin';
|
||||
import baseConfig from '../../../../eslint.config.mjs';
|
||||
|
||||
export default [
|
||||
...nx.configs['flat/angular'],
|
||||
...nx.configs['flat/angular-template'],
|
||||
...baseConfig,
|
||||
{
|
||||
files: ['**/*.ts'],
|
||||
rules: {
|
||||
'@angular-eslint/directive-selector': [
|
||||
'error',
|
||||
{
|
||||
type: 'attribute',
|
||||
prefix: 'ts',
|
||||
style: 'camelCase',
|
||||
},
|
||||
],
|
||||
'@angular-eslint/component-selector': [
|
||||
'error',
|
||||
{
|
||||
type: 'element',
|
||||
prefix: 'ts',
|
||||
style: 'kebab-case',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['**/*.html'],
|
||||
// Override or add rules here
|
||||
rules: {},
|
||||
},
|
||||
];
|
||||
20
libs/web/tracker/application/project.json
Normal file
20
libs/web/tracker/application/project.json
Normal file
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"name": "web-tracker-application",
|
||||
"$schema": "../../../../node_modules/nx/schemas/project-schema.json",
|
||||
"sourceRoot": "libs/web/tracker/application/src",
|
||||
"prefix": "ts",
|
||||
"projectType": "library",
|
||||
"tags": ["scope:web-tracker", "type:application"],
|
||||
"targets": {
|
||||
"test": {
|
||||
"executor": "@nx/vitest:test",
|
||||
"outputs": ["{options.reportsDirectory}"],
|
||||
"options": {
|
||||
"reportsDirectory": "coverage/libs/web/tracker/application"
|
||||
}
|
||||
},
|
||||
"lint": {
|
||||
"executor": "@nx/eslint:lint"
|
||||
}
|
||||
}
|
||||
}
|
||||
5
libs/web/tracker/application/src/index.ts
Normal file
5
libs/web/tracker/application/src/index.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
export * from './lib/notifications';
|
||||
export * from './lib/facades/projects.facade';
|
||||
export * from './lib/facades/project.facade';
|
||||
export * from './lib/facades/board.facade';
|
||||
export * from './lib/facades/issue.facade';
|
||||
43
libs/web/tracker/application/src/lib/events/board.events.ts
Normal file
43
libs/web/tracker/application/src/lib/events/board.events.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import { type } from '@ngrx/signals';
|
||||
import { eventGroup } from '@ngrx/signals/events';
|
||||
import {
|
||||
BoardColumn,
|
||||
BoardFilter,
|
||||
CommandResult,
|
||||
CreateIssueInput,
|
||||
IssueChanged,
|
||||
IssueStatus,
|
||||
} from '@task-stream/web/tracker/domain';
|
||||
|
||||
export const boardPageEvents = eventGroup({
|
||||
source: 'Board Page',
|
||||
events: {
|
||||
opened: type<BoardFilter>(),
|
||||
filterChanged: type<BoardFilter>(),
|
||||
/** Optimistic: the card moves immediately and comes back if the API refuses. */
|
||||
issueMoved: type<{
|
||||
issueId: string;
|
||||
to: IssueStatus;
|
||||
reason?: string | null;
|
||||
}>(),
|
||||
issueCreateRequested: type<CreateIssueInput>(),
|
||||
},
|
||||
});
|
||||
|
||||
export const boardApiEvents = eventGroup({
|
||||
source: 'Board API',
|
||||
events: {
|
||||
loaded: type<BoardColumn[]>(),
|
||||
loadFailed: type<string>(),
|
||||
issueMoveFailed: type<string>(),
|
||||
issueCreated: type<CommandResult>(),
|
||||
issueCreateFailed: type<string>(),
|
||||
},
|
||||
});
|
||||
|
||||
export const boardRealtimeEvents = eventGroup({
|
||||
source: 'Board Realtime',
|
||||
events: {
|
||||
issueChanged: type<IssueChanged>(),
|
||||
},
|
||||
});
|
||||
57
libs/web/tracker/application/src/lib/events/issue.events.ts
Normal file
57
libs/web/tracker/application/src/lib/events/issue.events.ts
Normal file
@@ -0,0 +1,57 @@
|
||||
import { type } from '@ngrx/signals';
|
||||
import { eventGroup } from '@ngrx/signals/events';
|
||||
import {
|
||||
Activity,
|
||||
ChangeStatusInput,
|
||||
Comment,
|
||||
CommentChanged,
|
||||
Issue,
|
||||
LinkIssuesInput,
|
||||
UpdateIssueInput,
|
||||
} from '@task-stream/web/tracker/domain';
|
||||
|
||||
export const issuePageEvents = eventGroup({
|
||||
source: 'Issue Page',
|
||||
events: {
|
||||
opened: type<{ idOrKey: string }>(),
|
||||
statusChangeRequested: type<ChangeStatusInput>(),
|
||||
assignRequested: type<{ issueId: string; assigneeId: string | null }>(),
|
||||
updateRequested: type<UpdateIssueInput>(),
|
||||
linkRequested: type<LinkIssuesInput>(),
|
||||
/** Relate by the other ticket's key (e.g. BE-3), resolved to its id first. */
|
||||
linkByKeyRequested: type<{
|
||||
issueId: string;
|
||||
type: LinkIssuesInput['type'];
|
||||
targetKey: string;
|
||||
}>(),
|
||||
unlinkRequested: type<LinkIssuesInput>(),
|
||||
releaseChangeRequested: type<{
|
||||
issueId: string;
|
||||
releaseId: string | null;
|
||||
}>(),
|
||||
commentAddRequested: type<{ issueId: string; body: string }>(),
|
||||
commentEditRequested: type<{ commentId: string; body: string }>(),
|
||||
commentDeleteRequested: type<{ commentId: string }>(),
|
||||
},
|
||||
});
|
||||
|
||||
export const issueApiEvents = eventGroup({
|
||||
source: 'Issue API',
|
||||
events: {
|
||||
loaded: type<Issue>(),
|
||||
loadFailed: type<string>(),
|
||||
commentsLoaded: type<Comment[]>(),
|
||||
historyLoaded: type<Activity[]>(),
|
||||
commandSucceeded: type<string>(),
|
||||
commandFailed: type<string>(),
|
||||
},
|
||||
});
|
||||
|
||||
export const issueRealtimeEvents = eventGroup({
|
||||
source: 'Issue Realtime',
|
||||
events: {
|
||||
/** Something about this ticket changed: refetch it. */
|
||||
issueTouched: type<{ issueId: string; version: number }>(),
|
||||
commentChanged: type<CommentChanged>(),
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
import { type } from '@ngrx/signals';
|
||||
import { eventGroup } from '@ngrx/signals/events';
|
||||
import {
|
||||
Activity,
|
||||
CreateReleaseInput,
|
||||
MemberInput,
|
||||
Project,
|
||||
ProjectStats,
|
||||
Release,
|
||||
UserDirectoryEntry,
|
||||
} from '@task-stream/web/tracker/domain';
|
||||
|
||||
export const projectPageEvents = eventGroup({
|
||||
source: 'Project Page',
|
||||
events: {
|
||||
opened: type<{ idOrKey: string }>(),
|
||||
memberAddRequested: type<MemberInput>(),
|
||||
memberRoleChangeRequested: type<MemberInput>(),
|
||||
memberRemoveRequested: type<{ projectId: string; userId: string }>(),
|
||||
releaseCreateRequested: type<CreateReleaseInput>(),
|
||||
releasePublishRequested: type<{ releaseId: string; force: boolean }>(),
|
||||
releaseArchiveRequested: type<{ releaseId: string }>(),
|
||||
userSearchRequested: type<string>(),
|
||||
},
|
||||
});
|
||||
|
||||
export const projectApiEvents = eventGroup({
|
||||
source: 'Project API',
|
||||
events: {
|
||||
loaded: type<Project>(),
|
||||
loadFailed: type<string>(),
|
||||
statsLoaded: type<ProjectStats>(),
|
||||
releasesLoaded: type<Release[]>(),
|
||||
activityLoaded: type<Activity[]>(),
|
||||
commandSucceeded: type<string>(),
|
||||
commandFailed: type<string>(),
|
||||
usersFound: type<UserDirectoryEntry[]>(),
|
||||
},
|
||||
});
|
||||
|
||||
export const projectRealtimeEvents = eventGroup({
|
||||
source: 'Project Realtime',
|
||||
events: {
|
||||
projectChanged: type<Project>(),
|
||||
activityAdded: type<Activity>(),
|
||||
releaseChanged: type<Release>(),
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
import { type } from '@ngrx/signals';
|
||||
import { eventGroup } from '@ngrx/signals/events';
|
||||
import {
|
||||
CommandResult,
|
||||
CreateProjectInput,
|
||||
Project,
|
||||
} from '@task-stream/web/tracker/domain';
|
||||
|
||||
export const projectsPageEvents = eventGroup({
|
||||
source: 'Projects Page',
|
||||
events: {
|
||||
opened: type<void>(),
|
||||
createRequested: type<CreateProjectInput>(),
|
||||
},
|
||||
});
|
||||
|
||||
export const projectsApiEvents = eventGroup({
|
||||
source: 'Projects API',
|
||||
events: {
|
||||
loaded: type<Project[]>(),
|
||||
loadFailed: type<string>(),
|
||||
created: type<CommandResult>(),
|
||||
createFailed: type<string>(),
|
||||
},
|
||||
});
|
||||
|
||||
export const projectsRealtimeEvents = eventGroup({
|
||||
source: 'Projects Realtime',
|
||||
events: {
|
||||
/** Joined, left or changed one of my projects. */
|
||||
projectChanged: type<{ project: Project; stillMember: boolean }>(),
|
||||
},
|
||||
});
|
||||
45
libs/web/tracker/application/src/lib/facades/board.facade.ts
Normal file
45
libs/web/tracker/application/src/lib/facades/board.facade.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
import { inject, Injectable, Provider } from '@angular/core';
|
||||
import { injectDispatch } from '@ngrx/signals/events';
|
||||
import {
|
||||
BoardFilter,
|
||||
CreateIssueInput,
|
||||
IssueStatus,
|
||||
} from '@task-stream/web/tracker/domain';
|
||||
import { boardPageEvents } from '../events/board.events';
|
||||
import { BoardStore } from '../stores/board.store';
|
||||
|
||||
/** Kanban board of a project, live. */
|
||||
@Injectable()
|
||||
export class BoardFacade {
|
||||
private readonly store = inject(BoardStore);
|
||||
private readonly dispatch = injectDispatch(boardPageEvents);
|
||||
|
||||
readonly columns = this.store.columns;
|
||||
readonly filter = this.store.filter;
|
||||
/** Tickets on the board (all columns). */
|
||||
readonly total = this.store.total;
|
||||
readonly loading = this.store.loading;
|
||||
readonly creating = this.store.creating;
|
||||
readonly error = this.store.error;
|
||||
|
||||
/** Shows the board with this filter: opens it for a new project, refilters otherwise. */
|
||||
show(filter: BoardFilter): void {
|
||||
if (this.store.filter()?.projectId === filter.projectId)
|
||||
this.dispatch.filterChanged(filter);
|
||||
else this.dispatch.opened(filter);
|
||||
}
|
||||
|
||||
/** Optimistic: the card moves at once and comes back if the API refuses. */
|
||||
moveIssue(issueId: string, to: IssueStatus, reason?: string | null): void {
|
||||
this.dispatch.issueMoved({ issueId, to, reason });
|
||||
}
|
||||
|
||||
createIssue(input: CreateIssueInput): void {
|
||||
this.dispatch.issueCreateRequested(input);
|
||||
}
|
||||
}
|
||||
|
||||
/** Store + facade of the board, for the board route's component. */
|
||||
export function provideBoardFacade(): Provider[] {
|
||||
return [BoardStore, BoardFacade];
|
||||
}
|
||||
159
libs/web/tracker/application/src/lib/facades/facades.spec.ts
Normal file
159
libs/web/tracker/application/src/lib/facades/facades.spec.ts
Normal file
@@ -0,0 +1,159 @@
|
||||
import { Component, inject, signal } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { Events } from '@ngrx/signals/events';
|
||||
import { AuthFacade } from '@task-stream/web/identity/application';
|
||||
import {
|
||||
ActivityGateway,
|
||||
CommentsGateway,
|
||||
IssuesGateway,
|
||||
IssueStatus,
|
||||
Project,
|
||||
ProjectRole,
|
||||
ProjectsGateway,
|
||||
ReleasesGateway,
|
||||
TrackerRealtimeGateway,
|
||||
UsersGateway,
|
||||
} from '@task-stream/web/tracker/domain';
|
||||
import { NEVER, of } from 'rxjs';
|
||||
import { boardPageEvents } from '../events/board.events';
|
||||
import { projectPageEvents } from '../events/project.events';
|
||||
import { Notifications } from '../notifications';
|
||||
import { BoardFacade, provideBoardFacade } from './board.facade';
|
||||
import { IssueFacade, provideIssueFacade } from './issue.facade';
|
||||
import { ProjectFacade, provideProjectFacade } from './project.facade';
|
||||
|
||||
const ok = { id: 'x', key: null, aggregateVersion: 1 };
|
||||
const project = { id: 'p1', key: 'WEB', members: [] } as unknown as Project;
|
||||
const issue = { id: 'i1', key: 'WEB-1', links: [] };
|
||||
|
||||
/** Every command succeeds, every query answers once, nothing arrives in real time. */
|
||||
function gateways() {
|
||||
return {
|
||||
projects: {
|
||||
project: vi.fn(() => of(project)),
|
||||
stats: vi.fn(() => NEVER),
|
||||
addMember: vi.fn(() => of(ok)),
|
||||
},
|
||||
issues: {
|
||||
board: vi.fn(() => of([])),
|
||||
issue: vi.fn(() => of(issue)),
|
||||
changeStatus: vi.fn(() => of(ok)),
|
||||
},
|
||||
list: { list: vi.fn(() => of([])) },
|
||||
realtime: {
|
||||
issueChanges: () => NEVER,
|
||||
commentChanges: () => NEVER,
|
||||
activity: () => NEVER,
|
||||
releaseChanges: () => NEVER,
|
||||
projectChanges: () => NEVER,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Facades are scoped to a route component, like in the app. */
|
||||
@Component({
|
||||
template: '',
|
||||
providers: [
|
||||
provideProjectFacade(),
|
||||
provideBoardFacade(),
|
||||
provideIssueFacade(),
|
||||
],
|
||||
})
|
||||
class Host {
|
||||
readonly project = inject(ProjectFacade);
|
||||
readonly board = inject(BoardFacade);
|
||||
readonly issue = inject(IssueFacade);
|
||||
}
|
||||
|
||||
function setup() {
|
||||
const fakes = gateways();
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{ provide: ProjectsGateway, useValue: fakes.projects },
|
||||
{ provide: IssuesGateway, useValue: fakes.issues },
|
||||
{ provide: ReleasesGateway, useValue: fakes.list },
|
||||
{ provide: ActivityGateway, useValue: fakes.list },
|
||||
{ provide: CommentsGateway, useValue: fakes.list },
|
||||
{ provide: UsersGateway, useValue: { search: () => of([]) } },
|
||||
{ provide: TrackerRealtimeGateway, useValue: fakes.realtime },
|
||||
{
|
||||
provide: Notifications,
|
||||
useValue: { success: vi.fn(), error: vi.fn() },
|
||||
},
|
||||
{ provide: AuthFacade, useValue: { user: signal({ id: 'me' }) } },
|
||||
],
|
||||
});
|
||||
const host = TestBed.createComponent(Host).componentInstance;
|
||||
return { ...host, fakes };
|
||||
}
|
||||
|
||||
describe('BoardFacade', () => {
|
||||
it('opens the board for a new project and refilters the same one', () => {
|
||||
const { board, fakes } = setup();
|
||||
const seen: string[] = [];
|
||||
TestBed.inject(Events)
|
||||
.on(boardPageEvents.opened, boardPageEvents.filterChanged)
|
||||
.subscribe((event) => seen.push(event.type));
|
||||
|
||||
board.show({ projectId: 'p1' });
|
||||
board.show({ projectId: 'p1', assigneeId: 'u2' });
|
||||
board.show({ projectId: 'p2' });
|
||||
|
||||
expect(seen).toEqual([
|
||||
boardPageEvents.opened.type,
|
||||
boardPageEvents.filterChanged.type,
|
||||
boardPageEvents.opened.type,
|
||||
]);
|
||||
expect(fakes.issues.board).toHaveBeenLastCalledWith({ projectId: 'p2' });
|
||||
expect(board.filter()).toEqual({ projectId: 'p2' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('ProjectFacade', () => {
|
||||
it('ignores commands until a project is open, then sends its id', () => {
|
||||
const { project, fakes } = setup();
|
||||
|
||||
project.addMember('u2');
|
||||
expect(fakes.projects.addMember).not.toHaveBeenCalled();
|
||||
|
||||
project.open('WEB');
|
||||
expect(project.project()?.id).toBe('p1');
|
||||
|
||||
project.addMember('u2', ProjectRole.VIEWER);
|
||||
expect(fakes.projects.addMember).toHaveBeenCalledWith({
|
||||
projectId: 'p1',
|
||||
userId: 'u2',
|
||||
role: ProjectRole.VIEWER,
|
||||
});
|
||||
});
|
||||
|
||||
it('searches the directory from two characters', () => {
|
||||
const { project } = setup();
|
||||
const seen: string[] = [];
|
||||
TestBed.inject(Events)
|
||||
.on(projectPageEvents.userSearchRequested)
|
||||
.subscribe(({ payload }) => seen.push(payload));
|
||||
|
||||
project.searchUsers(' a ');
|
||||
project.searchUsers(' an ');
|
||||
|
||||
expect(seen).toEqual(['an']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('IssueFacade', () => {
|
||||
it('acts on the open ticket', () => {
|
||||
const { issue, fakes } = setup();
|
||||
|
||||
issue.changeStatus(IssueStatus.IN_PROGRESS);
|
||||
expect(fakes.issues.changeStatus).not.toHaveBeenCalled();
|
||||
|
||||
issue.open('WEB-1');
|
||||
issue.changeStatus(IssueStatus.QA_FAILED, 'Falla en Safari');
|
||||
expect(fakes.issues.changeStatus).toHaveBeenCalledWith({
|
||||
issueId: 'i1',
|
||||
status: IssueStatus.QA_FAILED,
|
||||
reason: 'Falla en Safari',
|
||||
});
|
||||
});
|
||||
});
|
||||
101
libs/web/tracker/application/src/lib/facades/issue.facade.ts
Normal file
101
libs/web/tracker/application/src/lib/facades/issue.facade.ts
Normal file
@@ -0,0 +1,101 @@
|
||||
import { inject, Injectable, Provider } from '@angular/core';
|
||||
import { injectDispatch } from '@ngrx/signals/events';
|
||||
import {
|
||||
IssueLink,
|
||||
IssueLinkType,
|
||||
IssueStatus,
|
||||
UpdateIssueInput,
|
||||
} from '@task-stream/web/tracker/domain';
|
||||
import { issuePageEvents } from '../events/issue.events';
|
||||
import { IssueStore } from '../stores/issue.store';
|
||||
|
||||
/**
|
||||
* One ticket for presenters: details, comments and history, live. Commands act
|
||||
* on the open ticket, so pages don't pass its id.
|
||||
*/
|
||||
@Injectable()
|
||||
export class IssueFacade {
|
||||
private readonly store = inject(IssueStore);
|
||||
private readonly dispatch = injectDispatch(issuePageEvents);
|
||||
|
||||
readonly issue = this.store.issue;
|
||||
readonly comments = this.store.comments;
|
||||
readonly history = this.store.history;
|
||||
readonly outwardLinks = this.store.outwardLinks;
|
||||
readonly inwardLinks = this.store.inwardLinks;
|
||||
readonly loading = this.store.loading;
|
||||
readonly error = this.store.error;
|
||||
/** Signed-in user's id (authors can edit their comments). */
|
||||
readonly me = this.store.me;
|
||||
|
||||
/** Loads the ticket (by id or key, e.g. BE-3) and follows its changes. */
|
||||
open(idOrKey: string): void {
|
||||
this.dispatch.opened({ idOrKey });
|
||||
}
|
||||
|
||||
/** QA_FAILED and CANCELLED need a reason. */
|
||||
changeStatus(status: IssueStatus, reason?: string | null): void {
|
||||
this.withIssue((issueId) =>
|
||||
this.dispatch.statusChangeRequested({ issueId, status, reason }),
|
||||
);
|
||||
}
|
||||
|
||||
assign(assigneeId: string | null): void {
|
||||
this.withIssue((issueId) =>
|
||||
this.dispatch.assignRequested({ issueId, assigneeId }),
|
||||
);
|
||||
}
|
||||
|
||||
update(changes: Omit<UpdateIssueInput, 'issueId'>): void {
|
||||
this.withIssue((issueId) =>
|
||||
this.dispatch.updateRequested({ issueId, ...changes }),
|
||||
);
|
||||
}
|
||||
|
||||
/** Relates this ticket with another one by its key (e.g. BE-3). */
|
||||
link(type: IssueLinkType, targetKey: string): void {
|
||||
this.withIssue((issueId) =>
|
||||
this.dispatch.linkByKeyRequested({ issueId, type, targetKey }),
|
||||
);
|
||||
}
|
||||
|
||||
unlink(link: IssueLink): void {
|
||||
this.withIssue((issueId) =>
|
||||
this.dispatch.unlinkRequested({
|
||||
issueId,
|
||||
type: link.type,
|
||||
targetIssueId: link.issueId,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
setRelease(releaseId: string | null): void {
|
||||
this.withIssue((issueId) =>
|
||||
this.dispatch.releaseChangeRequested({ issueId, releaseId }),
|
||||
);
|
||||
}
|
||||
|
||||
addComment(body: string): void {
|
||||
this.withIssue((issueId) =>
|
||||
this.dispatch.commentAddRequested({ issueId, body }),
|
||||
);
|
||||
}
|
||||
|
||||
editComment(commentId: string, body: string): void {
|
||||
this.dispatch.commentEditRequested({ commentId, body });
|
||||
}
|
||||
|
||||
deleteComment(commentId: string): void {
|
||||
this.dispatch.commentDeleteRequested({ commentId });
|
||||
}
|
||||
|
||||
private withIssue(command: (issueId: string) => void): void {
|
||||
const issueId = this.store.issue()?.id;
|
||||
if (issueId) command(issueId);
|
||||
}
|
||||
}
|
||||
|
||||
/** Store + facade of a ticket, for the issue route's component. */
|
||||
export function provideIssueFacade(): Provider[] {
|
||||
return [IssueStore, IssueFacade];
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { inject, Injectable, Provider } from '@angular/core';
|
||||
import { injectDispatch } from '@ngrx/signals/events';
|
||||
import {
|
||||
CreateReleaseInput,
|
||||
ProjectRole,
|
||||
} from '@task-stream/web/tracker/domain';
|
||||
import { projectPageEvents } from '../events/project.events';
|
||||
import { ProjectStore } from '../stores/project.store';
|
||||
|
||||
/**
|
||||
* The open project for presenters: details, members, releases, stats and live
|
||||
* activity. Commands act on the open project, so pages don't pass its id.
|
||||
*/
|
||||
@Injectable()
|
||||
export class ProjectFacade {
|
||||
private readonly store = inject(ProjectStore);
|
||||
private readonly dispatch = injectDispatch(projectPageEvents);
|
||||
|
||||
readonly project = this.store.project;
|
||||
readonly members = this.store.members;
|
||||
readonly stats = this.store.stats;
|
||||
readonly releases = this.store.releases;
|
||||
readonly activity = this.store.activity;
|
||||
/** Pireon directory results for `searchUsers()`. */
|
||||
readonly userResults = this.store.userResults;
|
||||
readonly loading = this.store.loading;
|
||||
readonly error = this.store.error;
|
||||
readonly myRole = this.store.myRole;
|
||||
/** Owner or admin. */
|
||||
readonly canManage = this.store.canManage;
|
||||
/** Any role but viewer. */
|
||||
readonly canContribute = this.store.canContribute;
|
||||
|
||||
/** Loads the project (by id or key) and follows its changes. */
|
||||
open(idOrKey: string): void {
|
||||
this.dispatch.opened({ idOrKey });
|
||||
}
|
||||
|
||||
/** Searches Pireon's directory (from 2 characters, debounced). */
|
||||
searchUsers(term: string): void {
|
||||
const query = term.trim();
|
||||
if (query.length >= 2) this.dispatch.userSearchRequested(query);
|
||||
}
|
||||
|
||||
addMember(userId: string, role: ProjectRole = ProjectRole.MEMBER): void {
|
||||
const projectId = this.projectId();
|
||||
if (projectId)
|
||||
this.dispatch.memberAddRequested({ projectId, userId, role });
|
||||
}
|
||||
|
||||
changeMemberRole(userId: string, role: ProjectRole): void {
|
||||
const projectId = this.projectId();
|
||||
if (projectId)
|
||||
this.dispatch.memberRoleChangeRequested({ projectId, userId, role });
|
||||
}
|
||||
|
||||
removeMember(userId: string): void {
|
||||
const projectId = this.projectId();
|
||||
if (projectId) this.dispatch.memberRemoveRequested({ projectId, userId });
|
||||
}
|
||||
|
||||
createRelease(release: Omit<CreateReleaseInput, 'projectId'>): void {
|
||||
const projectId = this.projectId();
|
||||
if (projectId)
|
||||
this.dispatch.releaseCreateRequested({ projectId, ...release });
|
||||
}
|
||||
|
||||
/** `force` publishes even with unfinished tickets. */
|
||||
publishRelease(releaseId: string, force = false): void {
|
||||
this.dispatch.releasePublishRequested({ releaseId, force });
|
||||
}
|
||||
|
||||
archiveRelease(releaseId: string): void {
|
||||
this.dispatch.releaseArchiveRequested({ releaseId });
|
||||
}
|
||||
|
||||
private projectId(): string | null {
|
||||
return this.store.project()?.id ?? null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Store + facade of the open project, for the project route's component. */
|
||||
export function provideProjectFacade(): Provider[] {
|
||||
return [ProjectStore, ProjectFacade];
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { injectDispatch } from '@ngrx/signals/events';
|
||||
import { CreateProjectInput } from '@task-stream/web/tracker/domain';
|
||||
import { projectsPageEvents } from '../events/projects.events';
|
||||
import { ProjectsStore } from '../stores/projects.store';
|
||||
|
||||
/** "My projects" for presenters: state as signals, intentions as methods. */
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class ProjectsFacade {
|
||||
private readonly store = inject(ProjectsStore);
|
||||
private readonly dispatch = injectDispatch(projectsPageEvents);
|
||||
|
||||
readonly projects = this.store.projects;
|
||||
/** By name. */
|
||||
readonly sorted = this.store.sorted;
|
||||
readonly loading = this.store.loading;
|
||||
readonly creating = this.store.creating;
|
||||
readonly error = this.store.error;
|
||||
|
||||
/** Loads the list and starts following membership changes. */
|
||||
load(): void {
|
||||
this.dispatch.opened();
|
||||
}
|
||||
|
||||
/** On success, notifies and navigates to the new project. */
|
||||
create(input: CreateProjectInput): void {
|
||||
this.dispatch.createRequested(input);
|
||||
}
|
||||
}
|
||||
25
libs/web/tracker/application/src/lib/notifications.ts
Normal file
25
libs/web/tracker/application/src/lib/notifications.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
/** Outbound port: tell the user how a command went (implemented with toasts by the app). */
|
||||
export abstract class Notifications {
|
||||
abstract success(message: string): void;
|
||||
abstract error(message: string): void;
|
||||
}
|
||||
|
||||
/** Message of a failed GraphQL/HTTP call, for the user. */
|
||||
export function describeError(error: unknown): string {
|
||||
if (
|
||||
error &&
|
||||
typeof error === 'object' &&
|
||||
'errors' in error &&
|
||||
Array.isArray((error as { errors: unknown[] }).errors)
|
||||
) {
|
||||
return (error as { errors: { message: string }[] }).errors
|
||||
.map((e) => e.message)
|
||||
.join('\n');
|
||||
}
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
/** The read model is eventually consistent: right after a command, a query may 404 for a few ms. */
|
||||
export function isNotFound(error: unknown): boolean {
|
||||
return /not found/i.test(describeError(error));
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import {
|
||||
BoardColumn,
|
||||
IssueStatus,
|
||||
IssueSummary,
|
||||
} from '@task-stream/web/tracker/domain';
|
||||
import { applyIssueChange, moveIssue } from './board.reducers';
|
||||
|
||||
const issue = (
|
||||
id: string,
|
||||
status: IssueStatus,
|
||||
version = 1,
|
||||
assignee: string | null = null,
|
||||
): IssueSummary =>
|
||||
({
|
||||
id,
|
||||
status,
|
||||
version,
|
||||
key: id,
|
||||
projectId: 'p',
|
||||
title: id,
|
||||
assignee: assignee ? { id: assignee, name: assignee } : null,
|
||||
release: null,
|
||||
area: null,
|
||||
labels: [],
|
||||
commentCount: 0,
|
||||
}) as unknown as IssueSummary;
|
||||
|
||||
const board = (): BoardColumn[] => [
|
||||
{
|
||||
status: IssueStatus.TODO,
|
||||
total: 1,
|
||||
issues: [issue('a', IssueStatus.TODO)],
|
||||
},
|
||||
{ status: IssueStatus.IN_PROGRESS, total: 0, issues: [] },
|
||||
];
|
||||
|
||||
describe('board reducers', () => {
|
||||
it('moves a card optimistically', () => {
|
||||
const next = moveIssue(board(), 'a', IssueStatus.IN_PROGRESS);
|
||||
expect(next[0]).toMatchObject({ total: 0, issues: [] });
|
||||
expect(next[1].issues[0]).toMatchObject({
|
||||
id: 'a',
|
||||
status: IssueStatus.IN_PROGRESS,
|
||||
});
|
||||
expect(next[1].total).toBe(1);
|
||||
});
|
||||
|
||||
it('applies newer realtime versions and ignores stale ones', () => {
|
||||
const moved = applyIssueChange(
|
||||
board(),
|
||||
issue('a', IssueStatus.IN_PROGRESS, 2),
|
||||
null,
|
||||
);
|
||||
expect(moved[1].issues.map((i) => i.id)).toEqual(['a']);
|
||||
|
||||
const stale = applyIssueChange(
|
||||
moved,
|
||||
issue('a', IssueStatus.TODO, 1),
|
||||
null,
|
||||
);
|
||||
expect(stale).toBe(moved);
|
||||
});
|
||||
|
||||
it('drops issues that no longer match the filter', () => {
|
||||
const next = applyIssueChange(
|
||||
board(),
|
||||
issue('a', IssueStatus.TODO, 2, 'bob'),
|
||||
{ projectId: 'p', assigneeId: 'ana' },
|
||||
);
|
||||
expect(next[0].issues).toEqual([]);
|
||||
});
|
||||
|
||||
it('adds new issues from other users', () => {
|
||||
const next = applyIssueChange(
|
||||
board(),
|
||||
issue('b', IssueStatus.TODO, 1),
|
||||
null,
|
||||
);
|
||||
expect(next[0].issues.map((i) => i.id)).toEqual(['b', 'a']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
import {
|
||||
BoardColumn,
|
||||
BoardFilter,
|
||||
IssueStatus,
|
||||
IssueSummary,
|
||||
} from '@task-stream/web/tracker/domain';
|
||||
|
||||
/** Pure board transformations (unit tested). */
|
||||
|
||||
export function findIssue(
|
||||
columns: BoardColumn[],
|
||||
issueId: string,
|
||||
): IssueSummary | undefined {
|
||||
for (const column of columns) {
|
||||
const issue = column.issues.find((i) => i.id === issueId);
|
||||
if (issue) return issue;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function matchesFilter(
|
||||
issue: IssueSummary,
|
||||
filter: BoardFilter | null,
|
||||
): boolean {
|
||||
if (!filter) return true;
|
||||
if (filter.assigneeId && issue.assignee?.id !== filter.assigneeId)
|
||||
return false;
|
||||
if (filter.releaseId && issue.release?.id !== filter.releaseId) return false;
|
||||
if (filter.area && issue.area !== filter.area) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Removes the issue wherever it is and puts `next` (if any) on top of its status column. */
|
||||
export function placeIssue(
|
||||
columns: BoardColumn[],
|
||||
issueId: string,
|
||||
next: IssueSummary | null,
|
||||
): BoardColumn[] {
|
||||
return columns.map((column) => {
|
||||
const had = column.issues.some((i) => i.id === issueId);
|
||||
let issues = had
|
||||
? column.issues.filter((i) => i.id !== issueId)
|
||||
: column.issues;
|
||||
let total = column.total - (had ? 1 : 0);
|
||||
if (next && next.status === column.status) {
|
||||
issues = [next, ...issues];
|
||||
total += 1;
|
||||
}
|
||||
return had || issues !== column.issues
|
||||
? { ...column, issues, total }
|
||||
: column;
|
||||
});
|
||||
}
|
||||
|
||||
/** Optimistic move. */
|
||||
export function moveIssue(
|
||||
columns: BoardColumn[],
|
||||
issueId: string,
|
||||
to: IssueStatus,
|
||||
): BoardColumn[] {
|
||||
const issue = findIssue(columns, issueId);
|
||||
return issue
|
||||
? placeIssue(columns, issueId, { ...issue, status: to })
|
||||
: columns;
|
||||
}
|
||||
|
||||
/** Merges a realtime change, ignoring stale versions and issues outside the filter. */
|
||||
export function applyIssueChange(
|
||||
columns: BoardColumn[],
|
||||
issue: IssueSummary,
|
||||
filter: BoardFilter | null,
|
||||
): BoardColumn[] {
|
||||
const current = findIssue(columns, issue.id);
|
||||
if (current && current.version > issue.version) return columns;
|
||||
return placeIssue(
|
||||
columns,
|
||||
issue.id,
|
||||
matchesFilter(issue, filter) ? issue : null,
|
||||
);
|
||||
}
|
||||
155
libs/web/tracker/application/src/lib/stores/board.store.ts
Normal file
155
libs/web/tracker/application/src/lib/stores/board.store.ts
Normal file
@@ -0,0 +1,155 @@
|
||||
import { computed, inject } from '@angular/core';
|
||||
import { mapResponse } from '@ngrx/operators';
|
||||
import { signalStore, withComputed, withState } from '@ngrx/signals';
|
||||
import {
|
||||
Events,
|
||||
on,
|
||||
withEventHandlers,
|
||||
withReducer,
|
||||
} from '@ngrx/signals/events';
|
||||
import {
|
||||
BoardColumn,
|
||||
BoardFilter,
|
||||
IssuesGateway,
|
||||
TrackerRealtimeGateway,
|
||||
} from '@task-stream/web/tracker/domain';
|
||||
import {
|
||||
distinctUntilChanged,
|
||||
exhaustMap,
|
||||
map,
|
||||
merge,
|
||||
mergeMap,
|
||||
switchMap,
|
||||
tap,
|
||||
} from 'rxjs';
|
||||
import {
|
||||
boardApiEvents,
|
||||
boardPageEvents,
|
||||
boardRealtimeEvents,
|
||||
} from '../events/board.events';
|
||||
import { describeError, Notifications } from '../notifications';
|
||||
import { applyIssueChange, moveIssue } from './board.reducers';
|
||||
|
||||
interface BoardState {
|
||||
filter: BoardFilter | null;
|
||||
columns: BoardColumn[];
|
||||
loading: boolean;
|
||||
creating: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
/** Kanban board of a project, live. Scoped to the board route. */
|
||||
export const BoardStore = signalStore(
|
||||
withState<BoardState>({
|
||||
filter: null,
|
||||
columns: [],
|
||||
loading: false,
|
||||
creating: false,
|
||||
error: null,
|
||||
}),
|
||||
withComputed(({ columns }) => ({
|
||||
total: computed(() => columns().reduce((sum, c) => sum + c.total, 0)),
|
||||
})),
|
||||
withReducer(
|
||||
on(
|
||||
boardPageEvents.opened,
|
||||
boardPageEvents.filterChanged,
|
||||
({ payload }) => ({ filter: payload, loading: true, error: null }),
|
||||
),
|
||||
on(boardApiEvents.loaded, ({ payload }) => ({
|
||||
columns: payload,
|
||||
loading: false,
|
||||
})),
|
||||
on(boardApiEvents.loadFailed, ({ payload }) => ({
|
||||
loading: false,
|
||||
error: payload,
|
||||
})),
|
||||
on(boardPageEvents.issueMoved, ({ payload }, state) => ({
|
||||
columns: moveIssue(state.columns, payload.issueId, payload.to),
|
||||
})),
|
||||
on(boardRealtimeEvents.issueChanged, ({ payload }, state) => ({
|
||||
columns: applyIssueChange(state.columns, payload.issue, state.filter),
|
||||
})),
|
||||
on(boardPageEvents.issueCreateRequested, () => ({ creating: true })),
|
||||
on(boardApiEvents.issueCreated, boardApiEvents.issueCreateFailed, () => ({
|
||||
creating: false,
|
||||
})),
|
||||
),
|
||||
withEventHandlers(
|
||||
(
|
||||
store,
|
||||
events = inject(Events),
|
||||
issues = inject(IssuesGateway),
|
||||
realtime = inject(TrackerRealtimeGateway),
|
||||
notifications = inject(Notifications),
|
||||
) => {
|
||||
const load = (filter: BoardFilter) =>
|
||||
issues.board(filter).pipe(
|
||||
mapResponse({
|
||||
next: (columns) => boardApiEvents.loaded(columns),
|
||||
error: (error) => boardApiEvents.loadFailed(describeError(error)),
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
load$: events
|
||||
.on(boardPageEvents.opened, boardPageEvents.filterChanged)
|
||||
.pipe(switchMap(({ payload }) => load(payload))),
|
||||
live$: events.on(boardPageEvents.opened).pipe(
|
||||
map(({ payload }) => payload.projectId),
|
||||
distinctUntilChanged(),
|
||||
switchMap((projectId) => realtime.issueChanges(projectId)),
|
||||
map((change) => boardRealtimeEvents.issueChanged(change)),
|
||||
),
|
||||
move$: events.on(boardPageEvents.issueMoved).pipe(
|
||||
mergeMap(({ payload }) =>
|
||||
issues
|
||||
.changeStatus({
|
||||
issueId: payload.issueId,
|
||||
status: payload.to,
|
||||
reason: payload.reason,
|
||||
})
|
||||
.pipe(
|
||||
mapResponse({
|
||||
next: () => null,
|
||||
error: (error) =>
|
||||
boardApiEvents.issueMoveFailed(describeError(error)),
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
/** The API refused the move: tell the user and put the card back. */
|
||||
rollback$: events.on(boardApiEvents.issueMoveFailed).pipe(
|
||||
tap(({ payload }) => notifications.error(payload)),
|
||||
switchMap(() => {
|
||||
const filter = store.filter();
|
||||
return filter ? load(filter) : [];
|
||||
}),
|
||||
),
|
||||
create$: events.on(boardPageEvents.issueCreateRequested).pipe(
|
||||
exhaustMap(({ payload }) =>
|
||||
issues.create(payload).pipe(
|
||||
mapResponse({
|
||||
next: (result) => boardApiEvents.issueCreated(result),
|
||||
error: (error) =>
|
||||
boardApiEvents.issueCreateFailed(describeError(error)),
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
feedback$: merge(
|
||||
events
|
||||
.on(boardApiEvents.issueCreated)
|
||||
.pipe(
|
||||
tap(({ payload }) =>
|
||||
notifications.success(`${payload.key} creado`),
|
||||
),
|
||||
),
|
||||
events
|
||||
.on(boardApiEvents.issueCreateFailed, boardApiEvents.loadFailed)
|
||||
.pipe(tap(({ payload }) => notifications.error(payload))),
|
||||
),
|
||||
};
|
||||
},
|
||||
),
|
||||
);
|
||||
21
libs/web/tracker/application/src/lib/stores/command.ts
Normal file
21
libs/web/tracker/application/src/lib/stores/command.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import { mapResponse } from '@ngrx/operators';
|
||||
import { EventInstance } from '@ngrx/signals/events';
|
||||
import { Observable } from 'rxjs';
|
||||
import { describeError } from '../notifications';
|
||||
|
||||
type Creator = (message: string) => EventInstance<string, string>;
|
||||
|
||||
/** Runs a command and turns its outcome into a succeeded/failed event. */
|
||||
export function runCommand<T>(
|
||||
command$: Observable<T>,
|
||||
successMessage: string,
|
||||
succeeded: Creator,
|
||||
failed: Creator,
|
||||
) {
|
||||
return command$.pipe(
|
||||
mapResponse({
|
||||
next: () => succeeded(successMessage),
|
||||
error: (error) => failed(describeError(error)),
|
||||
}),
|
||||
);
|
||||
}
|
||||
313
libs/web/tracker/application/src/lib/stores/issue.store.ts
Normal file
313
libs/web/tracker/application/src/lib/stores/issue.store.ts
Normal file
@@ -0,0 +1,313 @@
|
||||
import { computed, inject } from '@angular/core';
|
||||
import { mapResponse } from '@ngrx/operators';
|
||||
import { signalStore, withComputed, withState } from '@ngrx/signals';
|
||||
import {
|
||||
Events,
|
||||
on,
|
||||
withEventHandlers,
|
||||
withReducer,
|
||||
} from '@ngrx/signals/events';
|
||||
import { AuthFacade } from '@task-stream/web/identity/application';
|
||||
import {
|
||||
Activity,
|
||||
ActivityGateway,
|
||||
Comment,
|
||||
CommentsGateway,
|
||||
Issue,
|
||||
IssuesGateway,
|
||||
TrackerRealtimeGateway,
|
||||
} from '@task-stream/web/tracker/domain';
|
||||
import {
|
||||
debounceTime,
|
||||
filter,
|
||||
map,
|
||||
merge,
|
||||
mergeMap,
|
||||
retry,
|
||||
switchMap,
|
||||
tap,
|
||||
throwError,
|
||||
timer,
|
||||
} from 'rxjs';
|
||||
import {
|
||||
issueApiEvents,
|
||||
issuePageEvents,
|
||||
issueRealtimeEvents,
|
||||
} from '../events/issue.events';
|
||||
import { describeError, isNotFound, Notifications } from '../notifications';
|
||||
import { runCommand } from './command';
|
||||
|
||||
interface IssueState {
|
||||
issue: Issue | null;
|
||||
comments: Comment[];
|
||||
history: Activity[];
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
/** One ticket: details, comments and history, live. Scoped to the issue view. */
|
||||
export const IssueStore = signalStore(
|
||||
withState<IssueState>({
|
||||
issue: null,
|
||||
comments: [],
|
||||
history: [],
|
||||
loading: false,
|
||||
error: null,
|
||||
}),
|
||||
withComputed(({ issue }, auth = inject(AuthFacade)) => ({
|
||||
me: computed(() => auth.user()?.id ?? null),
|
||||
outwardLinks: computed(
|
||||
() => issue()?.links.filter((l) => l.direction === 'OUTWARD') ?? [],
|
||||
),
|
||||
inwardLinks: computed(
|
||||
() => issue()?.links.filter((l) => l.direction === 'INWARD') ?? [],
|
||||
),
|
||||
})),
|
||||
withReducer(
|
||||
on(issuePageEvents.opened, () => ({
|
||||
loading: true,
|
||||
error: null,
|
||||
issue: null,
|
||||
comments: [],
|
||||
history: [],
|
||||
})),
|
||||
on(issueApiEvents.loaded, ({ payload }) => ({
|
||||
issue: payload,
|
||||
loading: false,
|
||||
})),
|
||||
on(issueApiEvents.loadFailed, ({ payload }) => ({
|
||||
loading: false,
|
||||
error: payload,
|
||||
})),
|
||||
on(issueApiEvents.commentsLoaded, ({ payload }) => ({ comments: payload })),
|
||||
on(issueApiEvents.historyLoaded, ({ payload }) => ({ history: payload })),
|
||||
on(issueRealtimeEvents.commentChanged, ({ payload }, state) => {
|
||||
const others = state.comments.filter((c) => c.id !== payload.commentId);
|
||||
if (!payload.comment) return { comments: others };
|
||||
return {
|
||||
comments: [...others, payload.comment].sort((a, b) =>
|
||||
a.createdAt.localeCompare(b.createdAt),
|
||||
),
|
||||
};
|
||||
}),
|
||||
),
|
||||
withEventHandlers(
|
||||
(
|
||||
store,
|
||||
events = inject(Events),
|
||||
issues = inject(IssuesGateway),
|
||||
comments = inject(CommentsGateway),
|
||||
activity = inject(ActivityGateway),
|
||||
realtime = inject(TrackerRealtimeGateway),
|
||||
notifications = inject(Notifications),
|
||||
) => {
|
||||
const fetchIssue = (idOrKey: string) =>
|
||||
issues.issue(idOrKey).pipe(
|
||||
retry({
|
||||
count: 5,
|
||||
delay: (error) =>
|
||||
isNotFound(error) ? timer(300) : throwError(() => error),
|
||||
}),
|
||||
mapResponse({
|
||||
next: (issue) => issueApiEvents.loaded(issue),
|
||||
error: (error) => issueApiEvents.loadFailed(describeError(error)),
|
||||
}),
|
||||
);
|
||||
const loaded$ = events.on(issueApiEvents.loaded);
|
||||
const done = (message: string) =>
|
||||
issueApiEvents.commandSucceeded(message);
|
||||
const failed = issueApiEvents.commandFailed;
|
||||
|
||||
return {
|
||||
load$: events
|
||||
.on(issuePageEvents.opened)
|
||||
.pipe(switchMap(({ payload }) => fetchIssue(payload.idOrKey))),
|
||||
comments$: events.on(issuePageEvents.opened).pipe(
|
||||
switchMap(() => loaded$.pipe(map(({ payload }) => payload.id))),
|
||||
filter((id, index) => index === 0 || id !== store.issue()?.id),
|
||||
switchMap((issueId) =>
|
||||
comments
|
||||
.list(issueId)
|
||||
.pipe(map((list) => issueApiEvents.commentsLoaded(list))),
|
||||
),
|
||||
),
|
||||
history$: loaded$.pipe(
|
||||
debounceTime(100),
|
||||
switchMap(({ payload }) =>
|
||||
activity
|
||||
.list(payload.projectId, payload.id)
|
||||
.pipe(map((list) => issueApiEvents.historyLoaded(list))),
|
||||
),
|
||||
),
|
||||
/** Any change to this ticket by anyone: refetch the full details. */
|
||||
liveIssue$: events.on(issuePageEvents.opened).pipe(
|
||||
switchMap(() => loaded$.pipe(map(({ payload }) => payload))),
|
||||
filter(
|
||||
(issue, index) => index === 0 || issue.id !== store.issue()?.id,
|
||||
),
|
||||
switchMap((issue) =>
|
||||
realtime.issueChanges(issue.projectId).pipe(
|
||||
filter(
|
||||
(change) =>
|
||||
change.issue.id === issue.id &&
|
||||
change.version > (store.issue()?.version ?? 0),
|
||||
),
|
||||
map((change) =>
|
||||
issueRealtimeEvents.issueTouched({
|
||||
issueId: issue.id,
|
||||
version: change.version,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
refetch$: events.on(issueRealtimeEvents.issueTouched).pipe(
|
||||
debounceTime(150),
|
||||
switchMap(({ payload }) => fetchIssue(payload.issueId)),
|
||||
),
|
||||
liveComments$: events.on(issuePageEvents.opened).pipe(
|
||||
switchMap(() => loaded$.pipe(map(({ payload }) => payload.id))),
|
||||
filter((id, index) => index === 0 || id !== store.issue()?.id),
|
||||
switchMap((issueId) => realtime.commentChanges(issueId)),
|
||||
map((change) => issueRealtimeEvents.commentChanged(change)),
|
||||
),
|
||||
commands$: merge(
|
||||
events
|
||||
.on(issuePageEvents.statusChangeRequested)
|
||||
.pipe(
|
||||
mergeMap(({ payload }) =>
|
||||
runCommand(
|
||||
issues.changeStatus(payload),
|
||||
'Estado actualizado',
|
||||
done,
|
||||
failed,
|
||||
),
|
||||
),
|
||||
),
|
||||
events
|
||||
.on(issuePageEvents.assignRequested)
|
||||
.pipe(
|
||||
mergeMap(({ payload }) =>
|
||||
runCommand(
|
||||
issues.assign(payload.issueId, payload.assigneeId),
|
||||
payload.assigneeId ? 'Asignado' : 'Sin asignar',
|
||||
done,
|
||||
failed,
|
||||
),
|
||||
),
|
||||
),
|
||||
events
|
||||
.on(issuePageEvents.updateRequested)
|
||||
.pipe(
|
||||
mergeMap(({ payload }) =>
|
||||
runCommand(
|
||||
issues.update(payload),
|
||||
'Ticket actualizado',
|
||||
done,
|
||||
failed,
|
||||
),
|
||||
),
|
||||
),
|
||||
events
|
||||
.on(issuePageEvents.linkRequested)
|
||||
.pipe(
|
||||
mergeMap(({ payload }) =>
|
||||
runCommand(
|
||||
issues.link(payload),
|
||||
'Relación añadida',
|
||||
done,
|
||||
failed,
|
||||
),
|
||||
),
|
||||
),
|
||||
events.on(issuePageEvents.linkByKeyRequested).pipe(
|
||||
mergeMap(({ payload }) =>
|
||||
runCommand(
|
||||
issues.issue(payload.targetKey.trim().toUpperCase()).pipe(
|
||||
switchMap((target) =>
|
||||
issues.link({
|
||||
issueId: payload.issueId,
|
||||
type: payload.type,
|
||||
targetIssueId: target.id,
|
||||
}),
|
||||
),
|
||||
),
|
||||
`Relacionado con ${payload.targetKey.toUpperCase()}`,
|
||||
done,
|
||||
failed,
|
||||
),
|
||||
),
|
||||
),
|
||||
events
|
||||
.on(issuePageEvents.unlinkRequested)
|
||||
.pipe(
|
||||
mergeMap(({ payload }) =>
|
||||
runCommand(
|
||||
issues.unlink(payload),
|
||||
'Relación eliminada',
|
||||
done,
|
||||
failed,
|
||||
),
|
||||
),
|
||||
),
|
||||
events
|
||||
.on(issuePageEvents.releaseChangeRequested)
|
||||
.pipe(
|
||||
mergeMap(({ payload }) =>
|
||||
runCommand(
|
||||
issues.setRelease(payload.issueId, payload.releaseId),
|
||||
'Release actualizada',
|
||||
done,
|
||||
failed,
|
||||
),
|
||||
),
|
||||
),
|
||||
events
|
||||
.on(issuePageEvents.commentAddRequested)
|
||||
.pipe(
|
||||
mergeMap(({ payload }) =>
|
||||
runCommand(
|
||||
comments.add(payload.issueId, payload.body),
|
||||
'Comentario añadido',
|
||||
done,
|
||||
failed,
|
||||
),
|
||||
),
|
||||
),
|
||||
events
|
||||
.on(issuePageEvents.commentEditRequested)
|
||||
.pipe(
|
||||
mergeMap(({ payload }) =>
|
||||
runCommand(
|
||||
comments.edit(payload.commentId, payload.body),
|
||||
'Comentario editado',
|
||||
done,
|
||||
failed,
|
||||
),
|
||||
),
|
||||
),
|
||||
events
|
||||
.on(issuePageEvents.commentDeleteRequested)
|
||||
.pipe(
|
||||
mergeMap(({ payload }) =>
|
||||
runCommand(
|
||||
comments.remove(payload.commentId),
|
||||
'Comentario eliminado',
|
||||
done,
|
||||
failed,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
feedback$: merge(
|
||||
events
|
||||
.on(issueApiEvents.commandSucceeded)
|
||||
.pipe(tap(({ payload }) => notifications.success(payload))),
|
||||
events
|
||||
.on(issueApiEvents.commandFailed, issueApiEvents.loadFailed)
|
||||
.pipe(tap(({ payload }) => notifications.error(payload))),
|
||||
),
|
||||
};
|
||||
},
|
||||
),
|
||||
);
|
||||
304
libs/web/tracker/application/src/lib/stores/project.store.ts
Normal file
304
libs/web/tracker/application/src/lib/stores/project.store.ts
Normal file
@@ -0,0 +1,304 @@
|
||||
import { computed, inject } from '@angular/core';
|
||||
import { mapResponse } from '@ngrx/operators';
|
||||
import { signalStore, withComputed, withState } from '@ngrx/signals';
|
||||
import {
|
||||
Events,
|
||||
on,
|
||||
withEventHandlers,
|
||||
withReducer,
|
||||
} from '@ngrx/signals/events';
|
||||
import { AuthFacade } from '@task-stream/web/identity/application';
|
||||
import {
|
||||
Activity,
|
||||
ActivityGateway,
|
||||
Project,
|
||||
ProjectRole,
|
||||
ProjectsGateway,
|
||||
ProjectStats,
|
||||
Release,
|
||||
ReleasesGateway,
|
||||
TrackerRealtimeGateway,
|
||||
UserDirectoryEntry,
|
||||
UsersGateway,
|
||||
} from '@task-stream/web/tracker/domain';
|
||||
import {
|
||||
debounceTime,
|
||||
map,
|
||||
merge,
|
||||
mergeMap,
|
||||
retry,
|
||||
switchMap,
|
||||
tap,
|
||||
throwError,
|
||||
timer,
|
||||
} from 'rxjs';
|
||||
import {
|
||||
projectApiEvents,
|
||||
projectPageEvents,
|
||||
projectRealtimeEvents,
|
||||
} from '../events/project.events';
|
||||
import { describeError, isNotFound, Notifications } from '../notifications';
|
||||
import { runCommand } from './command';
|
||||
|
||||
interface ProjectState {
|
||||
project: Project | null;
|
||||
stats: ProjectStats | null;
|
||||
releases: Release[];
|
||||
activity: Activity[];
|
||||
userResults: UserDirectoryEntry[];
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
/** The open project: details, members, releases, stats and live activity. Scoped to the project route. */
|
||||
export const ProjectStore = signalStore(
|
||||
withState<ProjectState>({
|
||||
project: null,
|
||||
stats: null,
|
||||
releases: [],
|
||||
activity: [],
|
||||
userResults: [],
|
||||
loading: false,
|
||||
error: null,
|
||||
}),
|
||||
withComputed(({ project }, auth = inject(AuthFacade)) => {
|
||||
const myRole = computed(
|
||||
() =>
|
||||
project()?.members.find((m) => m.user.id === auth.user()?.id)?.role ??
|
||||
null,
|
||||
);
|
||||
return {
|
||||
myRole,
|
||||
canManage: computed(
|
||||
() => myRole() === ProjectRole.OWNER || myRole() === ProjectRole.ADMIN,
|
||||
),
|
||||
canContribute: computed(
|
||||
() => !!myRole() && myRole() !== ProjectRole.VIEWER,
|
||||
),
|
||||
members: computed(() => project()?.members ?? []),
|
||||
};
|
||||
}),
|
||||
withReducer(
|
||||
on(projectPageEvents.opened, () => ({
|
||||
loading: true,
|
||||
error: null,
|
||||
project: null,
|
||||
stats: null,
|
||||
releases: [],
|
||||
activity: [],
|
||||
})),
|
||||
on(
|
||||
projectApiEvents.loaded,
|
||||
projectRealtimeEvents.projectChanged,
|
||||
({ payload }) => ({ project: payload, loading: false }),
|
||||
),
|
||||
on(projectApiEvents.loadFailed, ({ payload }) => ({
|
||||
loading: false,
|
||||
error: payload,
|
||||
})),
|
||||
on(projectApiEvents.statsLoaded, ({ payload }) => ({ stats: payload })),
|
||||
on(projectApiEvents.releasesLoaded, ({ payload }) => ({
|
||||
releases: payload,
|
||||
})),
|
||||
on(projectApiEvents.activityLoaded, ({ payload }) => ({
|
||||
activity: payload,
|
||||
})),
|
||||
on(projectApiEvents.usersFound, ({ payload }) => ({
|
||||
userResults: payload,
|
||||
})),
|
||||
on(projectRealtimeEvents.activityAdded, ({ payload }, state) => ({
|
||||
activity: [
|
||||
payload,
|
||||
...state.activity.filter((a) => a.id !== payload.id),
|
||||
].slice(0, 100),
|
||||
})),
|
||||
),
|
||||
withEventHandlers(
|
||||
(
|
||||
store,
|
||||
events = inject(Events),
|
||||
projects = inject(ProjectsGateway),
|
||||
releases = inject(ReleasesGateway),
|
||||
activity = inject(ActivityGateway),
|
||||
realtime = inject(TrackerRealtimeGateway),
|
||||
notifications = inject(Notifications),
|
||||
users = inject(UsersGateway),
|
||||
) => {
|
||||
const loaded$ = events.on(projectApiEvents.loaded);
|
||||
const reloadReleases = (projectId: string) =>
|
||||
releases.list(projectId).pipe(
|
||||
mapResponse({
|
||||
next: (list) => projectApiEvents.releasesLoaded(list),
|
||||
error: (error) =>
|
||||
projectApiEvents.commandFailed(describeError(error)),
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
load$: events.on(projectPageEvents.opened).pipe(
|
||||
switchMap(({ payload }) =>
|
||||
projects.project(payload.idOrKey).pipe(
|
||||
// Just created: the read model may be a few ms behind.
|
||||
retry({
|
||||
count: 5,
|
||||
delay: (error) =>
|
||||
isNotFound(error) ? timer(300) : throwError(() => error),
|
||||
}),
|
||||
mapResponse({
|
||||
next: (project) => projectApiEvents.loaded(project),
|
||||
error: (error) =>
|
||||
projectApiEvents.loadFailed(describeError(error)),
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
details$: loaded$.pipe(
|
||||
switchMap(({ payload }) =>
|
||||
merge(
|
||||
projects
|
||||
.stats(payload.id)
|
||||
.pipe(map((stats) => projectApiEvents.statsLoaded(stats))),
|
||||
reloadReleases(payload.id),
|
||||
activity
|
||||
.list(payload.id)
|
||||
.pipe(map((list) => projectApiEvents.activityLoaded(list))),
|
||||
),
|
||||
),
|
||||
),
|
||||
live$: loaded$.pipe(
|
||||
switchMap(({ payload }) =>
|
||||
merge(
|
||||
realtime
|
||||
.projectChanges(payload.id)
|
||||
.pipe(map((p) => projectRealtimeEvents.projectChanged(p))),
|
||||
realtime
|
||||
.activity(payload.id)
|
||||
.pipe(map((a) => projectRealtimeEvents.activityAdded(a))),
|
||||
realtime
|
||||
.releaseChanges(payload.id)
|
||||
.pipe(map((r) => projectRealtimeEvents.releaseChanged(r))),
|
||||
),
|
||||
),
|
||||
),
|
||||
/** Activity means tickets moved: refresh the dashboard (debounced). */
|
||||
refreshStats$: events.on(projectRealtimeEvents.activityAdded).pipe(
|
||||
debounceTime(800),
|
||||
switchMap(() => {
|
||||
const id = store.project()?.id;
|
||||
return id
|
||||
? projects
|
||||
.stats(id)
|
||||
.pipe(map((stats) => projectApiEvents.statsLoaded(stats)))
|
||||
: [];
|
||||
}),
|
||||
),
|
||||
/** Progress is computed by the API: refetch the list when a release or its tickets change. */
|
||||
refreshReleases$: merge(
|
||||
events.on(projectRealtimeEvents.releaseChanged),
|
||||
events
|
||||
.on(projectRealtimeEvents.activityAdded)
|
||||
.pipe(debounceTime(800)),
|
||||
).pipe(
|
||||
switchMap(() => {
|
||||
const id = store.project()?.id;
|
||||
return id ? reloadReleases(id) : [];
|
||||
}),
|
||||
),
|
||||
/** Pireon directory search (to add members). */
|
||||
searchUsers$: events.on(projectPageEvents.userSearchRequested).pipe(
|
||||
debounceTime(250),
|
||||
switchMap(({ payload }) =>
|
||||
users.search(payload).pipe(
|
||||
mapResponse({
|
||||
next: (list) => projectApiEvents.usersFound(list),
|
||||
error: () => projectApiEvents.usersFound([]),
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
commands$: merge(
|
||||
events
|
||||
.on(projectPageEvents.memberAddRequested)
|
||||
.pipe(
|
||||
mergeMap(({ payload }) =>
|
||||
runCommand(
|
||||
projects.addMember(payload),
|
||||
'Miembro añadido',
|
||||
projectApiEvents.commandSucceeded,
|
||||
projectApiEvents.commandFailed,
|
||||
),
|
||||
),
|
||||
),
|
||||
events
|
||||
.on(projectPageEvents.memberRoleChangeRequested)
|
||||
.pipe(
|
||||
mergeMap(({ payload }) =>
|
||||
runCommand(
|
||||
projects.changeMemberRole(payload),
|
||||
'Rol actualizado',
|
||||
projectApiEvents.commandSucceeded,
|
||||
projectApiEvents.commandFailed,
|
||||
),
|
||||
),
|
||||
),
|
||||
events
|
||||
.on(projectPageEvents.memberRemoveRequested)
|
||||
.pipe(
|
||||
mergeMap(({ payload }) =>
|
||||
runCommand(
|
||||
projects.removeMember(payload.projectId, payload.userId),
|
||||
'Miembro eliminado',
|
||||
projectApiEvents.commandSucceeded,
|
||||
projectApiEvents.commandFailed,
|
||||
),
|
||||
),
|
||||
),
|
||||
events
|
||||
.on(projectPageEvents.releaseCreateRequested)
|
||||
.pipe(
|
||||
mergeMap(({ payload }) =>
|
||||
runCommand(
|
||||
releases.create(payload),
|
||||
`Release ${payload.name} creada`,
|
||||
projectApiEvents.commandSucceeded,
|
||||
projectApiEvents.commandFailed,
|
||||
),
|
||||
),
|
||||
),
|
||||
events
|
||||
.on(projectPageEvents.releasePublishRequested)
|
||||
.pipe(
|
||||
mergeMap(({ payload }) =>
|
||||
runCommand(
|
||||
releases.publish(payload.releaseId, payload.force),
|
||||
'Release publicada 🚀',
|
||||
projectApiEvents.commandSucceeded,
|
||||
projectApiEvents.commandFailed,
|
||||
),
|
||||
),
|
||||
),
|
||||
events
|
||||
.on(projectPageEvents.releaseArchiveRequested)
|
||||
.pipe(
|
||||
mergeMap(({ payload }) =>
|
||||
runCommand(
|
||||
releases.archive(payload.releaseId),
|
||||
'Release archivada',
|
||||
projectApiEvents.commandSucceeded,
|
||||
projectApiEvents.commandFailed,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
feedback$: merge(
|
||||
events
|
||||
.on(projectApiEvents.commandSucceeded)
|
||||
.pipe(tap(({ payload }) => notifications.success(payload))),
|
||||
events
|
||||
.on(projectApiEvents.commandFailed)
|
||||
.pipe(tap(({ payload }) => notifications.error(payload))),
|
||||
),
|
||||
};
|
||||
},
|
||||
),
|
||||
);
|
||||
122
libs/web/tracker/application/src/lib/stores/projects.store.ts
Normal file
122
libs/web/tracker/application/src/lib/stores/projects.store.ts
Normal file
@@ -0,0 +1,122 @@
|
||||
import { computed, inject } from '@angular/core';
|
||||
import { Router } from '@angular/router';
|
||||
import { mapResponse } from '@ngrx/operators';
|
||||
import { signalStore, withComputed, withState } from '@ngrx/signals';
|
||||
import {
|
||||
Events,
|
||||
on,
|
||||
withEventHandlers,
|
||||
withReducer,
|
||||
} from '@ngrx/signals/events';
|
||||
import { AuthFacade } from '@task-stream/web/identity/application';
|
||||
import {
|
||||
Project,
|
||||
ProjectsGateway,
|
||||
TrackerRealtimeGateway,
|
||||
} from '@task-stream/web/tracker/domain';
|
||||
import { exhaustMap, map, switchMap, tap } from 'rxjs';
|
||||
import {
|
||||
projectsApiEvents,
|
||||
projectsPageEvents,
|
||||
projectsRealtimeEvents,
|
||||
} from '../events/projects.events';
|
||||
import { describeError, Notifications } from '../notifications';
|
||||
|
||||
interface ProjectsState {
|
||||
projects: Project[];
|
||||
loading: boolean;
|
||||
creating: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
/** "My projects": the list plus live membership changes. */
|
||||
export const ProjectsStore = signalStore(
|
||||
{ providedIn: 'root' },
|
||||
withState<ProjectsState>({
|
||||
projects: [],
|
||||
loading: false,
|
||||
creating: false,
|
||||
error: null,
|
||||
}),
|
||||
withComputed(({ projects }) => ({
|
||||
sorted: computed(() =>
|
||||
[...projects()].sort((a, b) => a.name.localeCompare(b.name)),
|
||||
),
|
||||
})),
|
||||
withReducer(
|
||||
on(projectsPageEvents.opened, () => ({ loading: true, error: null })),
|
||||
on(projectsApiEvents.loaded, ({ payload }) => ({
|
||||
projects: payload,
|
||||
loading: false,
|
||||
})),
|
||||
on(projectsApiEvents.loadFailed, ({ payload }) => ({
|
||||
loading: false,
|
||||
error: payload,
|
||||
})),
|
||||
on(projectsPageEvents.createRequested, () => ({ creating: true })),
|
||||
on(projectsApiEvents.created, projectsApiEvents.createFailed, () => ({
|
||||
creating: false,
|
||||
})),
|
||||
on(projectsRealtimeEvents.projectChanged, ({ payload }, state) => {
|
||||
const others = state.projects.filter((p) => p.id !== payload.project.id);
|
||||
return {
|
||||
projects: payload.stillMember ? [...others, payload.project] : others,
|
||||
};
|
||||
}),
|
||||
),
|
||||
withEventHandlers(
|
||||
(
|
||||
_store,
|
||||
events = inject(Events),
|
||||
projects = inject(ProjectsGateway),
|
||||
realtime = inject(TrackerRealtimeGateway),
|
||||
notifications = inject(Notifications),
|
||||
router = inject(Router),
|
||||
auth = inject(AuthFacade),
|
||||
) => ({
|
||||
load$: events.on(projectsPageEvents.opened).pipe(
|
||||
switchMap(() =>
|
||||
projects.myProjects().pipe(
|
||||
mapResponse({
|
||||
next: (list) => projectsApiEvents.loaded(list),
|
||||
error: (error) =>
|
||||
projectsApiEvents.loadFailed(describeError(error)),
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
/** One live subscription for the whole session. */
|
||||
live$: events.on(projectsPageEvents.opened).pipe(
|
||||
exhaustMap(() => realtime.myProjectsChanges()),
|
||||
map((project) =>
|
||||
projectsRealtimeEvents.projectChanged({
|
||||
project,
|
||||
stillMember: project.members.some(
|
||||
(m) => m.user.id === auth.user()?.id,
|
||||
),
|
||||
}),
|
||||
),
|
||||
),
|
||||
create$: events.on(projectsPageEvents.createRequested).pipe(
|
||||
exhaustMap(({ payload }) =>
|
||||
projects.create(payload).pipe(
|
||||
mapResponse({
|
||||
next: (result) => projectsApiEvents.created(result),
|
||||
error: (error) =>
|
||||
projectsApiEvents.createFailed(describeError(error)),
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
createdFeedback$: events.on(projectsApiEvents.created).pipe(
|
||||
tap(({ payload }) => {
|
||||
notifications.success(`Proyecto ${payload.key} creado`);
|
||||
void router.navigate(['/p', payload.key]);
|
||||
}),
|
||||
),
|
||||
failureFeedback$: events
|
||||
.on(projectsApiEvents.createFailed, projectsApiEvents.loadFailed)
|
||||
.pipe(tap(({ payload }) => notifications.error(payload))),
|
||||
}),
|
||||
),
|
||||
);
|
||||
5
libs/web/tracker/application/src/test-setup.ts
Normal file
5
libs/web/tracker/application/src/test-setup.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
import '@angular/compiler';
|
||||
import '@analogjs/vitest-angular/setup-snapshots';
|
||||
import { setupTestBed } from '@analogjs/vitest-angular/setup-testbed';
|
||||
|
||||
setupTestBed();
|
||||
30
libs/web/tracker/application/tsconfig.json
Normal file
30
libs/web/tracker/application/tsconfig.json
Normal file
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"extends": "../../../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"isolatedModules": true,
|
||||
"target": "es2022",
|
||||
"strict": true,
|
||||
"noImplicitOverride": true,
|
||||
"noPropertyAccessFromIndexSignature": true,
|
||||
"noImplicitReturns": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"emitDecoratorMetadata": false,
|
||||
"module": "preserve"
|
||||
},
|
||||
"angularCompilerOptions": {
|
||||
"enableI18nLegacyMessageIdFormat": false,
|
||||
"strictInjectionParameters": true,
|
||||
"strictInputAccessModifiers": true,
|
||||
"strictTemplates": true
|
||||
},
|
||||
"files": [],
|
||||
"include": [],
|
||||
"references": [
|
||||
{
|
||||
"path": "./tsconfig.lib.json"
|
||||
},
|
||||
{
|
||||
"path": "./tsconfig.spec.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
26
libs/web/tracker/application/tsconfig.lib.json
Normal file
26
libs/web/tracker/application/tsconfig.lib.json
Normal file
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "../../../../dist/out-tsc",
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"inlineSources": true,
|
||||
"types": []
|
||||
},
|
||||
"include": ["src/**/*.ts"],
|
||||
"exclude": [
|
||||
"src/**/*.spec.ts",
|
||||
"src/**/*.test.ts",
|
||||
"vite.config.ts",
|
||||
"vite.config.mts",
|
||||
"vitest.config.ts",
|
||||
"vitest.config.mts",
|
||||
"src/**/*.test.tsx",
|
||||
"src/**/*.spec.tsx",
|
||||
"src/**/*.test.js",
|
||||
"src/**/*.spec.js",
|
||||
"src/**/*.test.jsx",
|
||||
"src/**/*.spec.jsx",
|
||||
"src/test-setup.ts"
|
||||
]
|
||||
}
|
||||
29
libs/web/tracker/application/tsconfig.spec.json
Normal file
29
libs/web/tracker/application/tsconfig.spec.json
Normal file
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "../../../../dist/out-tsc",
|
||||
"types": [
|
||||
"vitest/globals",
|
||||
"vitest/importMeta",
|
||||
"vite/client",
|
||||
"node",
|
||||
"vitest"
|
||||
]
|
||||
},
|
||||
"include": [
|
||||
"vite.config.ts",
|
||||
"vite.config.mts",
|
||||
"vitest.config.ts",
|
||||
"vitest.config.mts",
|
||||
"src/**/*.test.ts",
|
||||
"src/**/*.spec.ts",
|
||||
"src/**/*.test.tsx",
|
||||
"src/**/*.spec.tsx",
|
||||
"src/**/*.test.js",
|
||||
"src/**/*.spec.js",
|
||||
"src/**/*.test.jsx",
|
||||
"src/**/*.spec.jsx",
|
||||
"src/**/*.d.ts"
|
||||
],
|
||||
"files": ["src/test-setup.ts"]
|
||||
}
|
||||
29
libs/web/tracker/application/vite.config.mts
Normal file
29
libs/web/tracker/application/vite.config.mts
Normal file
@@ -0,0 +1,29 @@
|
||||
/// <reference types='vitest' />
|
||||
import { defineConfig } from 'vite';
|
||||
import angular from '@analogjs/vite-plugin-angular';
|
||||
import { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths.plugin';
|
||||
import { nxCopyAssetsPlugin } from '@nx/vite/plugins/nx-copy-assets.plugin';
|
||||
|
||||
export default defineConfig(() => ({
|
||||
root: import.meta.dirname,
|
||||
cacheDir: '../../../../node_modules/.vite/libs/web/tracker/application',
|
||||
plugins: [angular(), nxViteTsPaths(), nxCopyAssetsPlugin(['*.md'])],
|
||||
// Uncomment this if you are using workers.
|
||||
// worker: {
|
||||
// plugins: () => [ nxViteTsPaths() ],
|
||||
// },
|
||||
test: {
|
||||
name: 'web-tracker-application',
|
||||
watch: false,
|
||||
passWithNoTests: true,
|
||||
globals: true,
|
||||
environment: 'jsdom',
|
||||
include: ['{src,tests}/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],
|
||||
setupFiles: ['src/test-setup.ts'],
|
||||
reporters: ['default'],
|
||||
coverage: {
|
||||
reportsDirectory: '../../../../coverage/libs/web/tracker/application',
|
||||
provider: 'v8' as const,
|
||||
},
|
||||
},
|
||||
}));
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user