Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pointer Service (Full) #18

Open
wants to merge 6 commits into
base: step6
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 2 additions & 2 deletions index.ts
@@ -1,5 +1,5 @@
import './services/time'

import './services/time';
import './services/pointer';

// Adapted from https://www.learnrxjs.io/learn-rxjs/recipes/swipe-to-refresh
// Original code: https://stackblitz.com/edit/rxjs-refresh
61 changes: 61 additions & 0 deletions services/pointer.ts
@@ -0,0 +1,61 @@
import { createService } from '@rxfx/service';
import { fromEvent } from 'rxjs';
import { map, takeUntil } from 'rxjs/operators';
import { bus } from './bus';
import { setRefreshPos, resetRefresh } from './DOM';

const MOBILE = { DOWN: 'touchstart', UP: 'touchend', MOVE: 'touchmove' };
const DESKTOP = { DOWN: 'mousedown', UP: 'mouseup', MOVE: 'mousemove' };

export const POINTER_EVENTS =
'ontouchstart' in document.documentElement ? MOBILE : DESKTOP;

const mouseYsUntilUp = fromEvent(document, POINTER_EVENTS.MOVE).pipe(
map((ev: MouseEvent) => ev.clientY),
takeUntil(fromEvent(document, POINTER_EVENTS.UP))
);

export const pointerService = createService<'up' | 'down', number, Error>(
'pointer',
bus,
(event) => {
if (event === 'down') {
return mouseYsUntilUp;
}
}
);

/////////////////// UI updates /////////////////
pointerService.responses.subscribe((r) => setRefreshPos(r.payload));
bus
.query(pointerService.actions.complete.match)
.subscribe(() => resetRefresh());

/////////////////// DOM Event Harvesting /////////////////

// DOM listener setup + teardown
const sendDown = (e: Event) => {
e.preventDefault();
pointerService.request('down');
};
const sendUp = (e: Event) => {
e.preventDefault();
pointerService.request('up');
};

export const connectDOMEventsToPointerService = () => {
document.addEventListener(POINTER_EVENTS.DOWN, sendDown);
document.addEventListener(POINTER_EVENTS.UP, sendUp);
};
export const disconnectDOMEventsFromPointerService = () => {
document.removeEventListener(POINTER_EVENTS.DOWN, sendDown);
document.removeEventListener(POINTER_EVENTS.UP, sendUp);
};
connectDOMEventsToPointerService();

// Example:
// pointerService.request('test');
// puts these events on the bus
// {type: "pointer/request", payload: "test", meta: {…}}
// {type: "pointer/started", payload: undefined}
// {type: "pointer/complete", payload: undefined}