Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ You can use ClippyJS directly in the browser using CDN:
Install and import an agent:

```js
import { initAgent } from "clippyjs";
import { initAgent, loadExistingAgent } from "clippyjs";
import { Clippy } from "clippyjs/agents";

// Load and show the agent
Expand Down Expand Up @@ -106,6 +106,9 @@ agent.resume();

// Remove the agent from the DOM
agent.dispose();

// Recover a previously created agent instance
const sameAgent = loadExistingAgent(agent._el);
```

## Text-to-Speech
Expand Down
22 changes: 22 additions & 0 deletions src/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ import Queue from "./queue.ts";
import Animator from "./animator.ts";
import Balloon from "./balloon.ts";

const agentRegistry = new WeakMap<HTMLElement, Agent>();
const activeAgents = new Set<Agent>();

export interface AgentLoaders {
agent: () => Promise<{ default: any }>;
sound: () => Promise<{ default: any }>;
Expand Down Expand Up @@ -49,6 +52,8 @@ export default class Agent {
});

document.body.appendChild(this._el);
agentRegistry.set(this._el, this);
activeAgents.add(this);

this._animator = new Animator(this._el, mapUrl, data, sounds);
this._balloon = new Balloon(this._el);
Expand Down Expand Up @@ -700,6 +705,8 @@ export default class Agent {
this._animator.dispose();
this._balloon.dispose();
this._queue.dispose();
activeAgents.delete(this);
agentRegistry.delete(this._el);
this._el.remove();
}

Expand Down Expand Up @@ -729,6 +736,21 @@ export async function initAgent(loaders: AgentLoaders): Promise<Agent> {
return new Agent(map, data, sounds);
}

export function loadExistingAgent(element?: HTMLElement | null): Agent | undefined {
if (!element) {
return activeAgents.values().next().value;
}

let current: HTMLElement | null = element;
while (current) {
const agent = agentRegistry.get(current);
if (agent) {
return agent;
}
current = current.parentElement;
}
}

async function _loadSounds(loaders: AgentLoaders): Promise<Record<string, string>> {
const audio = document.createElement("audio");
const canPlayMp3 = !!audio.canPlayType && audio.canPlayType("audio/mp3") !== "";
Expand Down
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export { initAgent } from "./agent.ts";
export { initAgent, loadExistingAgent } from "./agent.ts";
Loading