thepaperpilot
a92f301044
Note: eventually I'll move the types into comments so this can be a plain .js file anyone can use
95 lines
4 KiB
TypeScript
95 lines
4 KiB
TypeScript
// TODO remove types and put them in comments so this can be a .js file
|
|
|
|
export function initGalaxy({
|
|
acceptedOrigins,
|
|
supportsSaving,
|
|
supportsSaveManager,
|
|
ignoreApiVersion,
|
|
onLoggedInChanged
|
|
}: {
|
|
acceptedOrigins?: string[];
|
|
supportsSaving?: boolean;
|
|
supportsSaveManager?: boolean;
|
|
ignoreApiVersion?: boolean;
|
|
onLoggedInChanged?: (loggedIn: boolean) => void;
|
|
}) {
|
|
return new Promise((accept, reject) => {
|
|
acceptedOrigins = acceptedOrigins ?? ["https://galaxy.click"];
|
|
if (acceptedOrigins.includes(window.origin)) {
|
|
// Callbacks to resolve promises
|
|
let saveListAccept: (value: SaveListResponse["list"]) => void,
|
|
saveListReject: (reason?: string) => void;
|
|
|
|
const galaxy = {
|
|
acceptedOrigins,
|
|
supportsSaving,
|
|
supportsSaveManager,
|
|
ignoreApiVersion,
|
|
onLoggedInChanged,
|
|
origin: window.origin,
|
|
apiVersion: 0,
|
|
loggedIn: false,
|
|
postMessage: function (
|
|
message: SupportsAction | SaveListAction | SaveAction | LoadAction
|
|
) {
|
|
window.top?.postMessage(message, galaxy.origin);
|
|
},
|
|
getSaveList: function () {
|
|
if (saveListAccept != null || saveListReject != null) {
|
|
console.warn("save_list action already in progress. Ignoring...");
|
|
return;
|
|
}
|
|
galaxy.postMessage({
|
|
action: "save_list"
|
|
});
|
|
return new Promise<SaveListResponse["list"]>((accept, reject) => {
|
|
saveListAccept = accept;
|
|
saveListReject = reject;
|
|
});
|
|
}
|
|
};
|
|
|
|
window.addEventListener("message", e => {
|
|
if (e.origin === galaxy.origin) {
|
|
console.log("Received message from Galaxy", e.data);
|
|
const data = e.data as GalaxyResponse;
|
|
|
|
switch (data.type) {
|
|
case "info": {
|
|
const { galaxy: isGalaxy, api_version, logged_in } = data;
|
|
// Ignoring isGalaxy check in case other accepted origins send it as false
|
|
if (api_version !== 1 && galaxy.ignoreApiVersion !== true) {
|
|
reject(`API version not recognized: ${api_version}`);
|
|
} else {
|
|
// Info responses may be sent again if the information gets updated
|
|
// Specifically, we care if logged_in gets changed
|
|
// We can use the api_version to determine if this is the first
|
|
// info response or a new one.
|
|
const firstInfoResponse = galaxy.apiVersion === 0;
|
|
galaxy.apiVersion = api_version;
|
|
galaxy.loggedIn = logged_in;
|
|
galaxy.origin = e.origin;
|
|
if (firstInfoResponse) {
|
|
accept(galaxy);
|
|
} else {
|
|
galaxy.onLoggedInChanged?.(logged_in);
|
|
}
|
|
}
|
|
break;
|
|
}
|
|
case "save_list": {
|
|
const { list, error, message } = data;
|
|
if (error) {
|
|
saveListReject(message);
|
|
} else {
|
|
saveListAccept(list);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
});
|
|
} else {
|
|
reject(`Project is not running on an accepted origin: ${window.origin}`);
|
|
}
|
|
});
|
|
}
|