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

feature(website): Update Orbit integration to fetch local server #460

Merged
merged 1 commit into from
Sep 15, 2023
Merged
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
17 changes: 10 additions & 7 deletions website/src/client/components/EditorToolbar.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { StyleSheet, css } from 'aphrodite';
import * as React from 'react';

import { Experiment } from '../auth/authManager';
import { SaveStatus, SaveHistory, Viewer, SaveOptions, SDKVersion } from '../types';
import { useOrbit } from '../utils/orbit';
import EditorTitle from './EditorTitle';
import type { EditorModal } from './EditorViewProps';
import usePreferences from './Preferences/usePreferences';
Expand All @@ -24,11 +24,11 @@ type Props = {
isDownloading: boolean;
isResolving: boolean;
visibleModal: EditorModal | null;
experienceURL: string;
onSubmitMetadata: (details: { name: string; description: string }) => void;
onShowModal: (modal: EditorModal) => void;
onHideModal: () => void;
onDownloadCode: () => Promise<void>;
onOpenWithOrbit: () => void;
onPublishAsync: (options?: SaveOptions) => Promise<void>;
};

Expand All @@ -46,21 +46,21 @@ export default function EditorToolbar(props: Props) {
isDownloading,
isResolving,
visibleModal,
experienceURL,
onSubmitMetadata,
onShowModal,
onHideModal,
onDownloadCode,
onOpenWithOrbit,
onPublishAsync,
} = props;
const { theme } = preferences;

const isPublishing = saveStatus === 'publishing';
const isPublished = saveStatus === 'published';

const showOrbitButton =
viewer?.experiments?.find(({ experiment }) => experiment === Experiment.Orbit)?.enabled ??
false;
const { isEnabled: showOrbitButton, openWithExperienceURL: onOpenWithOrbit } = useOrbit({
experiments: viewer?.experiments,
});

return (
<ToolbarShell>
Expand Down Expand Up @@ -113,7 +113,10 @@ export default function EditorToolbar(props: Props) {
</svg>
</IconButton>
{showOrbitButton ? (
<IconButton responsive title="Open with Orbit" onClick={onOpenWithOrbit}>
<IconButton
responsive
title="Open with Orbit"
onClick={() => onOpenWithOrbit(experienceURL, () => onShowModal('install-orbit'))}>
<svg width="20" height="20" viewBox="0 0 16 16">
<path
stroke="none"
Expand Down
7 changes: 1 addition & 6 deletions website/src/client/components/EditorView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import Analytics from '../utils/Analytics';
import { isMobile } from '../utils/detectPlatform';
import { isScript, isJson, isTest } from '../utils/fileUtilities';
import lintFile from '../utils/lintFile';
import { openExpoOrbitWithExperienceURL } from '../utils/orbit';
import prettierCode from '../utils/prettierCode';
import AssetViewer from './AssetViewer';
import { withDependencyManager } from './DependencyManager';
Expand Down Expand Up @@ -443,17 +442,13 @@ class EditorView extends React.Component<Props, State> {
viewer={viewer}
isDownloading={isDownloading}
isResolving={isResolving}
experienceURL={experienceURL}
visibleModal={currentModal as EditorModal}
onShowModal={this._handleShowModal}
onHideModal={this._handleHideModal}
onSubmitMetadata={this.props.onSubmitMetadata}
onDownloadCode={this.props.onDownloadAsync}
onPublishAsync={onPublishAsync}
onOpenWithOrbit={() =>
openExpoOrbitWithExperienceURL(experienceURL, () =>
this._handleShowModal('install-orbit')
)
}
/>
<div className={css(styles.editorAreaOuterWrapper)}>
<div className={css(styles.editorAreaOuter)}>
Expand Down
4 changes: 4 additions & 0 deletions website/src/client/utils/detectPlatform.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ export function isIOS(userAgent: string) {
return /iPhone|iPad|iPod/i.test(userAgent);
}

export function isMacOS(userAgent: string) {
return /Mac OS/i.test(userAgent);
}

export function isMobile(
userAgent: string = typeof navigator !== 'undefined' ? navigator.userAgent : ''
) {
Expand Down
102 changes: 97 additions & 5 deletions website/src/client/utils/orbit.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,103 @@
import customProtocolCheck from 'custom-protocol-check';
import { useCallback, useEffect, useState } from 'react';

export function openExpoOrbitWithExperienceURL(experienceURL: string, onFail?: () => void) {
const url = experienceURL?.replace('exp://', 'expo-orbit://');
import { Experiment, UserData } from '../auth/authManager';
import { isMacOS } from './detectPlatform';

if (!url) {
return;
const ORBIT_SERVER_PORTS = [35783, 47909, 44171, 50799];

type BaseRouteResponse = {
ok: boolean;
};

type StatusRouteResponse = BaseRouteResponse & {
version: string;
};

interface BaseServerRoutes {
[route: string]: {
searchParams?: Record<string, string>;
response: BaseRouteResponse;
};
}

interface LocalServerRoutes extends BaseServerRoutes {
status: {
response: StatusRouteResponse;
};
open: {
response: BaseRouteResponse;
searchParams: { url: string };
};
}

async function fetchLocalOrbitServer<T extends keyof LocalServerRoutes>(
route: T,
searchParams: LocalServerRoutes[T]['searchParams'] = {}
): Promise<LocalServerRoutes[T]['response'] | undefined> {
let path = `orbit/${route}`;
if (searchParams) {
path += `?${new URLSearchParams(searchParams)}`;
}

customProtocolCheck(url, onFail);
for (const port of ORBIT_SERVER_PORTS) {
try {
const response = await fetch(`http://127.0.0.1:${port}/${path}`, {
cache: 'no-cache',
headers: { Accept: 'application/json' },
referrerPolicy: 'origin-when-cross-origin',
credentials: 'omit',
});
if (response.ok) {
return response.json();
}
} catch {}
}

return undefined;
}

interface UseOrbitParams {
experiments?: UserData['experiments'];
}

export function useOrbit({ experiments }: UseOrbitParams = {}) {
const [isRunning, setIsRunning] = useState(false);
const isRunningMacOS = isMacOS(navigator?.userAgent);

const hasEnabledOrbitExperiment =
experiments?.find(({ experiment }) => experiment === Experiment.Orbit)?.enabled ?? false;

const openWithExperienceURL = useCallback(
async (experienceURL: string, onFail?: () => void) => {
if (!experienceURL) {
return;
}

if (isRunning) {
const response = await fetchLocalOrbitServer('open', { url: experienceURL });
if (response?.ok) {
return;
}
}

customProtocolCheck(experienceURL.replace('exp://', 'expo-orbit://'), onFail);
},
[isRunning]
);

useEffect(() => {
if (isRunningMacOS) {
fetchLocalOrbitServer('status')
.then((r) => {
setIsRunning(!!r?.version);
})
.catch(() => {});
}
}, [isRunningMacOS]);

return {
isEnabled: hasEnabledOrbitExperiment || isRunning,
openWithExperienceURL,
};
}
Loading