Skip to content

Commit

Permalink
feat: webview.iter for handling events
Browse files Browse the repository at this point in the history
  • Loading branch information
eliassjogreen committed Dec 2, 2020
1 parent da0b345 commit ce18528
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 20 deletions.
3 changes: 1 addition & 2 deletions deps.ts
@@ -1,3 +1,2 @@
export { deferred } from "https://deno.land/std@0.79.0/async/mod.ts";
export type { Deferred } from "https://deno.land/std@0.79.0/async/mod.ts";
export { delay } from "https://deno.land/std@0.79.0/async/mod.ts";
export { Plug } from "https://deno.land/x/plug@0.2.6/mod.ts";
15 changes: 3 additions & 12 deletions examples/external.ts
Expand Up @@ -14,15 +14,6 @@ const webview = new Webview(
{ url: `data:text/html,${encodeURIComponent(html)}` },
);

const interval = setInterval(() => {
const success = webview.loop();
const events = webview.step();

if (events.length > 0) {
console.log(events);
}

if (!success) {
clearInterval(interval);
}
}, 1000 / 60);
for await (const event of webview.iter()) {
webview.setTitle(event);
}
49 changes: 43 additions & 6 deletions webview.ts
@@ -1,4 +1,18 @@
import { sync, unwrap } from "./plugin.ts";
import { delay } from "./deps.ts";

function debounce<T extends unknown[], R>(
func: (...args: T) => Promise<R>,
time: number,
): (...args: T) => Promise<R> {
return async (...args) => {
const promise = func(...args);
const timer = delay(time);
const response = await promise;
await timer;
return response;
};
}

export interface WebviewParams {
title: string;
Expand Down Expand Up @@ -99,18 +113,14 @@ export class Webview {
}

/**
* Iterates over the event loop, returns once closed or terminated
* Iterates over the event loop until closed or terminated without
* handling events
*/
run(delta = 1000 / 60, block = false): Promise<void> {
return new Promise((resolve) => {
const interval = setInterval(() => {
const succ = this.loop(block);

// for (const event of this.step()) {
// // Make this into a async iterator?
// console.log(event);
// }

if (!succ) {
resolve();
clearInterval(interval);
Expand All @@ -119,6 +129,33 @@ export class Webview {
});
}

/**
* Iterates over the event loop, yielding external invoke events as strings and
* returning once closed or terminated
*/
async *iter(delta = 1000 / 60, block = false): AsyncIterableIterator<string> {
let finished = false;

const runner = debounce(async () => {
const succ = this.loop(block);
const evts = this.step();

if (!succ) {
finished = true;
}

return evts;
}, delta);

while (!finished) {
const events = await runner();

for (const event of events) {
yield event;
}
}
}

/**
* Sets the color of the title bar
*/
Expand Down

0 comments on commit ce18528

Please sign in to comment.