Skip to content

Commit

Permalink
refactor: work with new signal API
Browse files Browse the repository at this point in the history
  • Loading branch information
njfamirm authored and alimd committed Jan 30, 2023
1 parent 7d92bf3 commit d1565d2
Show file tree
Hide file tree
Showing 9 changed files with 55 additions and 91 deletions.
19 changes: 9 additions & 10 deletions demo/signal/index.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,23 @@
import {SignalInterface} from '@alwatr/signal';
import {eventListener, eventTrigger} from '@alwatr/signal';

const signal = new SignalInterface('easter-egg');
const buttonEventTrigger = eventTrigger.bind<{id: number}>('easter-egg');

signal.setProvider((param) => {
const newValue = param * 10;
console.info('2. signal provider called', {param, newValue});
return `You have ${newValue} egg`;
eventListener.subscribe<{id: number}>('easter-egg', (detail) => {
const newValue = detail.id * 10;
console.info('2. signal provider called', {detail, newValue});
});

document.getElementById('requestButton')?.addEventListener('click', async () => {
console.info('1. request with 1');
const value = await signal.request(1);
const value = await buttonEventTrigger.dispatch({id: 1});
console.info('3. new signal value', {value});
});

document.getElementById('requestButton2')?.addEventListener('click', async () => {
console.info('1. request with 1');
const value1 = await signal.request(1);
const value1 = buttonEventTrigger.dispatch({id: 2});
console.info('3. 2x request with 2,3');
const value2p = signal.request(2);
const value3p = signal.request(3);
const value2p = buttonEventTrigger.dispatch({id: 2});
const value3p = buttonEventTrigger.dispatch({id: 3});
console.info('4. new signal value', {value1, value2: await value2p, value3: await value3p});
});
6 changes: 3 additions & 3 deletions uniquely/flight-finder-pwa/src/component/job-add-form.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {AlwatrSmartElement, customElement, css, html} from '@alwatr/element';
import {l10n} from '@alwatr/i18n';
import {SignalInterface} from '@alwatr/signal';
import {message, localeConsumer, number} from '@alwatr/i18n';
import {eventTrigger} from '@alwatr/signal';

import {cityList} from '../city-list.js';
import ionNormalize from '../style/ionic.normalize.js';
Expand Down Expand Up @@ -48,7 +48,7 @@ export class JobAddForm extends AlwatrSmartElement {
`,
];

static jobAddSignal = new SignalInterface('job-add');
static jobAddSignal = eventTrigger.bind('job-add');
static cityListTemplate = Object.keys(cityList).map(
(city) => html`<ion-select-option value=${city}>${city} - ${cityList[city]}</ion-select-option>`,
);
Expand Down
24 changes: 8 additions & 16 deletions uniquely/flight-finder-pwa/src/component/job-item.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ import {
html,
nothing,
} from '@alwatr/element';
import {l10n} from '@alwatr/i18n';
import {SignalInterface} from '@alwatr/signal';
import {message, number} from '@alwatr/i18n';
import {eventTrigger} from '@alwatr/signal';

import {cityList} from '../city-list.js';
import ionNormalize from '../style/ionic.normalize.js';
Expand Down Expand Up @@ -96,15 +96,7 @@ export class JobItem extends AlwatrSmartElement {
@property({attribute: false, type: Object}) job?: Job;
@query('ion-item-sliding') private __ionItemSliding?: HTMLElement;

static jobDeleteSignal = new SignalInterface('job-delete');

override connectedCallback(): void {
super.connectedCallback();

l10n.resourceChangeSignal.addListener(() => {
this.requestUpdate();
});
}
static jobDeleteSignal = eventTrigger.bind('job-delete');

override render(): unknown {
if (this.job == null || this.job.detail == null) return nothing;
Expand Down Expand Up @@ -164,16 +156,16 @@ export class JobItem extends AlwatrSmartElement {
const lowestPrice = Math.min(...resultList.map((result) => result.price));
return html`
<div class="job__title">
<span>${l10n.formatNumber(resultList.length)}</span>
${l10n.localize('flight')}
<span>${number(resultList.length)}</span>
${message('flight')}
</div>
<div class="job__subtitle job__subtitle-founded">
<span class="job__subtitle-price ion-color-danger"> ${l10n.formatNumber(lowestPrice)} </span>
<span>${l10n.localize('config_currency')}</span>
<span class="job__subtitle-price ion-color-danger"> ${number(lowestPrice)} </span>
<span>${message('config_currency')}</span>
</div>
`;
}
return html` <ion-note>${l10n.localize('not_found')}</ion-note> `;
return html` <ion-note>${message('not_found')}</ion-note> `;
}
private __renderDescription(description: string): TemplateResult | typeof nothing {
if (description.trim() == '') return nothing;
Expand Down
17 changes: 7 additions & 10 deletions uniquely/flight-finder-pwa/src/component/page-flight-finder.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import {type TemplateResult, AlwatrSmartElement, map, customElement, query, css, html} from '@alwatr/element';
import {message, number} from '@alwatr/i18n';
import {SignalInterface} from '@alwatr/signal';
import {requestableContextConsumer} from '@alwatr/signal';
import {modalController} from '@ionic/core';

import ionNormalize from '../style/ionic.normalize.js';
import ionTheming from '../style/ionic.theming.js';

import type {AlwatrDocumentStorage} from '@alwatr/type';
import type {Job} from '@alwatr/type/flight-finder.js';

import './job-item.js';
Expand Down Expand Up @@ -51,8 +52,9 @@ export class PageFlightFinder extends AlwatrSmartElement {
`,
];

static jobDocumentStorageSignal = new SignalInterface('job-document-storage');
static jobAddSignal = new SignalInterface('job-add');
static jobDocumentStorageContextConsumer =
requestableContextConsumer.bind<AlwatrDocumentStorage<Job>, null>('job-document-storage');
// static jobAddEventTrigger = eventTrigger.bind<Job>('job-add');

private __jobList?: Array<Job>;
private __lastUpdate = 0;
Expand All @@ -74,12 +76,7 @@ export class PageFlightFinder extends AlwatrSmartElement {

override connectedCallback(): void {
super.connectedCallback();

l10n.resourceChangeSignal.addListener(() => {
this.requestUpdate();
});

PageFlightFinder.jobDocumentStorageSignal.addListener((jobList) => {
PageFlightFinder.jobDocumentStorageContextConsumer.subscribe((jobList) => {
this.__jobList = Object.values(jobList.data);
this.__lastUpdate = jobList.meta.lastUpdated;
this.requestUpdate();
Expand All @@ -91,7 +88,7 @@ export class PageFlightFinder extends AlwatrSmartElement {
return html`
<ion-header>
<ion-toolbar color="primary">
<ion-title>${l10n.localize('flight_finder')}</ion-title>
<ion-title>${message('flight_finder')}</ion-title>
</ion-toolbar>
</ion-header>
Expand Down
13 changes: 4 additions & 9 deletions uniquely/flight-finder-pwa/src/director/job-add.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,9 @@
import {type AlwatrServiceResponse, fetch} from '@alwatr/fetch';
import {SignalInterface} from '@alwatr/signal';

import {jobDocumentStorageSignal} from './job-document-storage.js';
import {showToastSignal} from './toast.js';
import {commandTrigger, eventListener, requestableContextConsumer} from '@alwatr/signal';

import type {Job} from '@alwatr/type/flight-finder.js';

export const jobAddSignal = new SignalInterface('job-add');

jobAddSignal.addListener(async (job) => {
eventListener.subscribe<Job>('job-add', async (job) => {
try {
const response = await fetch({
url: window.appConfig?.api ? window.appConfig.api + '/job' : '/job',
Expand All @@ -28,10 +23,10 @@ jobAddSignal.addListener(async (job) => {
}
}
catch (error) {
showToastSignal.dispatch({
commandTrigger.request('toast', {
message: 'عملیات با خطا رو به رو شد',
});
}

jobDocumentStorageSignal.request(null);
requestableContextConsumer.request('job-document-storage', null);
});
15 changes: 5 additions & 10 deletions uniquely/flight-finder-pwa/src/director/job-delete.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,13 @@
import {type AlwatrServiceResponse, fetch} from '@alwatr/fetch';
import {SignalInterface} from '@alwatr/signal';
import {commandTrigger, eventListener, requestableContextConsumer} from '@alwatr/signal';

import {jobDocumentStorageSignal} from './job-document-storage.js';
import {showToastSignal} from './toast.js';

export const jobDeleteSignal = new SignalInterface('job-delete');

jobDeleteSignal.addListener(async (id) => {
eventListener.subscribe<{id: string}>('job-delete', async (detail) => {
try {
const response = await fetch({
url: window.appConfig?.api ? window.appConfig.api + '/job' : '/job',
token: window.appConfig?.token,
method: 'DELETE',
queryParameters: {id},
queryParameters: {id: detail.id},
});

if (response.ok !== true) {
Expand All @@ -26,10 +21,10 @@ jobDeleteSignal.addListener(async (id) => {
}
}
catch (error) {
showToastSignal.dispatch({
commandTrigger.request('toast', {
message: 'عملیات با خطا رو به رو شد',
});
}

jobDocumentStorageSignal.request(null);
requestableContextConsumer.request('job-delete', null);
});
30 changes: 14 additions & 16 deletions uniquely/flight-finder-pwa/src/director/job-document-storage.ts
Original file line number Diff line number Diff line change
@@ -1,40 +1,38 @@
import {type CacheStrategy, serviceRequest} from '@alwatr/fetch';
import {createLogger} from '@alwatr/logger';
import {SignalInterface} from '@alwatr/signal';

import {showToastSignal} from './toast.js';
import {commandTrigger, requestableContextConsumer, requestableContextProvider} from '@alwatr/signal';

import type {AlwatrDocumentStorage} from '@alwatr/type';
import type {Job} from '@alwatr/type/flight-finder.js';

export const logger = createLogger('[director/job-document-storage]');
export const jobDocumentStorageSignal = new SignalInterface('job-document-storage');

async function requestJobStorage(cacheStrategy: CacheStrategy): Promise<void> {
async function requestJobStorage(cacheStrategy: CacheStrategy): Promise<AlwatrDocumentStorage<Job> | void> {
logger.logMethod('jobListProvider');

try {
jobDocumentStorageSignal.dispatch(
<AlwatrDocumentStorage<Job>> await serviceRequest({
url: window.appConfig?.api ? window.appConfig.api + '/job' : '/job',
token: window.appConfig?.token,
cache: 'no-cache',
cacheStrategy,
}),
);
return (<AlwatrDocumentStorage<Job>> await serviceRequest({
url: window.appConfig?.api ? window.appConfig.api + '/job' : '/job',
token: window.appConfig?.token,
cache: 'no-cache',
cacheStrategy,
}));
}
catch (error) {
if ((error as Error).message !== 'fetch_cache_not_found') {
logger.error('jobListProvider', 'fetch_failed', error);
showToastSignal.dispatch({
commandTrigger.request('toast', {
message: 'عملیات با خطا رو به رو شد',
});
return;
}
}
}

jobDocumentStorageSignal.setProvider(() => requestJobStorage('network_first'));
requestableContextProvider.setProvider<AlwatrDocumentStorage<Job>, null>('job-document-storage', () => {
return requestJobStorage('network_first');
});

requestJobStorage('cache_only').then(() => requestJobStorage('network_first'));

setInterval(() => jobDocumentStorageSignal.request(null), 60_000);
setInterval(() => requestableContextConsumer.request<null>('job-document-storage', null), 60_000);
8 changes: 4 additions & 4 deletions uniquely/flight-finder-pwa/src/director/toast.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import {SignalInterface} from '@alwatr/signal';
import {commandHandler} from '@alwatr/signal';
import {toastController} from '@ionic/core';

export const showToastSignal = new SignalInterface('toast');

showToastSignal.addListener(async (ToastOptions) => {
commandHandler.define<{message: string}, Record<string, never>>('toast', async (ToastOptions) => {
const toast = await toastController.create({
animated: true,
position: 'bottom',
Expand All @@ -12,4 +10,6 @@ showToastSignal.addListener(async (ToastOptions) => {
});

await toast.present();

return {};
});
14 changes: 1 addition & 13 deletions uniquely/flight-finder-pwa/src/type.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,8 @@
import type {AlwatrDocumentStorage} from '@alwatr/type';
import type {Job, JobDetail} from '@alwatr/type/flight-finder.js';
import type {ToastOptions} from '@ionic/core';
import type {JobDetail} from '@alwatr/type/flight-finder.js';

declare global {
// eslint-disable-next-line no-var
var appConfig: Record<string, string | undefined> | undefined;

interface AlwatrSignals {
readonly 'job-add': Pick<Job, 'detail'>;
readonly 'job-delete': string;
readonly 'job-document-storage': AlwatrDocumentStorage<Job>;
readonly toast: Partial<ToastOptions> & {message: string};
}
interface AlwatrRequestSignals {
readonly 'job-document-storage': null;
}
}

export type NewJobDetail = {
Expand Down

0 comments on commit d1565d2

Please sign in to comment.