Skip to content
Closed
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
221 changes: 221 additions & 0 deletions browser/data-browser/src/chunks/PluginRuns/CatalogApps.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,221 @@
import { useCallback, useEffect, useState } from 'react';
import { styled } from 'styled-components';
import toast from 'react-hot-toast';
import {
catalogAppState,
installCatalogApp,
readConnectionSubjects,
readInstalledCatalogApps,
updateCatalogApp,
useStore,
type CatalogApp,
type InstalledCatalogApp,
} from '@tomic/react';
import { Card } from '@components/Card';
import { Column, Row } from '@components/Row';
import { Button } from '@components/Button';
import { constructOpenURL } from '@helpers/navigation';
import { useNavigateWithTransition } from '@hooks/useNavigateWithTransition';
import { handOverAppKey } from '@chunks/AppPage/appAgent';
import type { CatalogEntry } from './pluginCatalog';

/** The catalog's app entries this visitor is offered, under the same gates as the rest of the page. */
export function visibleCatalogApps(
entries: CatalogEntry[],
options: { query: string; showExperimental: boolean; showApi: boolean },
): CatalogApp[] {
return entries
.filter(
entry =>
entry.app &&
entry.enabled &&
(!entry.experimental || options.showExperimental) &&
(!entry.requiresApiPlugins || options.showApi),
)
.map(entry => entry.app!)
.filter(app =>
[app.name, app.description ?? '', app.id]
.join(' ')
.toLocaleLowerCase()
.includes(options.query),
);
}

/**
* Drive apps offered by the plugin catalog (`app-module` entries): install
* one, open it, and move it to the catalog's version when that is newer.
*
* Installing downloads the module the entry names, refuses it unless its bytes
* match the entry's integrity hash, and makes an ordinary app from it — the
* same app, table, schema and identity the New menu makes. So nothing here is
* specific to any one app, and an installed app is edited, shared and deleted
* like any other.
*/
export function CatalogApps({
entries,
drive,
query,
showExperimental,
showApi,
}: {
entries: CatalogEntry[];
drive: string;
query: string;
showExperimental: boolean;
showApi: boolean;
}): React.JSX.Element | null {
const store = useStore();
const navigate = useNavigateWithTransition();
const [installed, setInstalled] = useState<InstalledCatalogApp[]>([]);
const [busy, setBusy] = useState<string>();

const refresh = useCallback(
() =>
readInstalledCatalogApps(store, drive, property =>
readConnectionSubjects(store, drive, property),
).then(setInstalled),
[store, drive],
);

useEffect(() => {
refresh().catch(() => setInstalled([]));
}, [refresh]);

const apps = visibleCatalogApps(entries, {
query,
showExperimental,
showApi,
});

if (apps.length === 0) return null;

const install = async (app: CatalogApp) => {
setBusy(app.id);

try {
const created = await installCatalogApp(store, { drive, app });

// As for an app from the New menu: it still works if this fails, but
// cannot write as itself while nobody is signed in.
try {
await handOverAppKey(store, {
drive,
app: created.app,
secret: created.secret,
});
} catch (error) {
store.notifyError(error);
}

navigate(constructOpenURL(created.app));
} catch (error) {
toast.error(String(error instanceof Error ? error.message : error));
} finally {
setBusy(undefined);
}
};

const update = async (app: CatalogApp, subject: string) => {
setBusy(app.id);

try {
await updateCatalogApp(store, { drive, subject, app });
await refresh();
toast.success(`${app.name} updated to ${app.version}`);
} catch (error) {
toast.error(String(error instanceof Error ? error.message : error));
} finally {
setBusy(undefined);
}
};

return (
<section aria-label='Drive apps'>
<Column gap='0.75rem'>
<h2>Drive apps</h2>
<p>
Apps that run in their own frame on this drive and keep their rows in
a table of their own. Each is a published version; installing checks
its code against the catalog before anything is saved.
</p>
<Grid>
{apps.map(app => {
const mine = installed.find(i => i.id === app.id);
const state = catalogAppState(app, mine);

return (
<Card key={app.id} data-catalog-app={app.id}>
<Column gap='1rem'>
<Row justify='space-between' center>
<Avatar aria-hidden>{app.emoji ?? '🧩'}</Avatar>
<Muted>
{mine
? `Installed ${mine.version ?? '(unknown version)'}`
: `Version ${app.version}`}
</Muted>
</Row>
<div>
<h3>{app.name}</h3>
{app.description && <Muted>{app.description}</Muted>}
</div>
<Row wrapItems gap='0.5rem'>
{state === 'install' ? (
<Button
disabled={busy !== undefined}
onClick={() => install(app)}
aria-label={`Install ${app.name}`}
>
{busy === app.id ? 'Installing…' : 'Install'}
</Button>
) : (
<Button
subtle
onClick={() =>
navigate(constructOpenURL(mine!.subject))
}
aria-label={`Open ${app.name}`}
>
Open
</Button>
)}
{state === 'update' && (
<Button
disabled={busy !== undefined}
onClick={() => update(app, mine!.subject)}
>
{busy === app.id
? 'Updating…'
: `Update to ${app.version}`}
</Button>
)}
</Row>
</Column>
</Card>
);
})}
</Grid>
</Column>
</section>
);
}

const Grid = styled.div`
display: grid;
grid-template-columns: repeat(auto-fill, minmax(min(100%, 19rem), 1fr));
gap: 1rem;
align-items: start;
`;
const Avatar = styled.div`
display: grid;
place-items: center;
width: 2.8rem;
height: 2.8rem;
border-radius: ${p => p.theme.radius};
background: ${p => p.theme.colors.bg2};
font-size: 1.3rem;
`;
const Muted = styled.p`
margin: 0;
color: ${p => p.theme.colors.textLight};
font-size: 0.9rem;
`;
21 changes: 21 additions & 0 deletions browser/data-browser/src/chunks/PluginRuns/pluginCatalog.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,27 @@ describe('parseCatalogEntries', () => {
).toEqual(['kept']);
});

it('reads an installable app, resolving its module against the catalog', () => {
const [entry] = parseCatalogEntries(
[
row({
'https://atomicdata.dev/properties/name': 'Fixture',
[`${P}version`]: '1.2.3',
[`${P}app-module`]: 'fixture/app/ui.js',
[`${P}app-module-integrity`]: 'sha384-AAAA',
}),
row({ [SHORTNAME]: 'no-app' }),
],
'https://plugins.test/integrations/catalog.json',
);
expect(entry.app).toMatchObject({
id: 'fixture-api',
version: '1.2.3',
module: 'https://plugins.test/integrations/fixture/app/ui.js',
integrity: 'sha384-AAAA',
});
});

it('returns nothing for a non-array catalog', () => {
expect(parseCatalogEntries({})).toEqual([]);
expect(parseCatalogEntries(null)).toEqual([]);
Expand Down
22 changes: 19 additions & 3 deletions browser/data-browser/src/chunks/PluginRuns/pluginCatalog.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useEffect, useState } from 'react';
import { parseCatalogApp, type CatalogApp } from '@tomic/react';
import { usePluginCatalogUrl } from '@helpers/pluginCatalogUrl';

const CATALOG_ENTRY_CLASS =
Expand All @@ -18,14 +19,19 @@ export interface CatalogEntry {
experimental: boolean;
enabled: boolean;
requiresApiPlugins: boolean;
/** Set when the entry is an installable drive app (`app-module`). */
app?: CatalogApp;
}

function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}

/** Malformed entries are skipped, so one bad row can't hide the rest. */
export function parseCatalogEntries(raw: unknown): CatalogEntry[] {
export function parseCatalogEntries(
raw: unknown,
catalogUrl?: string,
): CatalogEntry[] {
if (!Array.isArray(raw)) return [];

return raw.flatMap((resource): CatalogEntry[] => {
Expand All @@ -42,6 +48,9 @@ export function parseCatalogEntries(raw: unknown): CatalogEntry[] {
experimental: resource[EXPERIMENTAL_PROP] !== false,
enabled: resource[ENABLED_PROP] === true,
requiresApiPlugins: resource[REQUIRES_API_PLUGINS_PROP] === true,
// Resolved against the catalog it came from, so a catalog can name
// its modules relative to itself.
...(catalogUrl ? { app: parseCatalogApp(resource, catalogUrl) } : {}),
},
];
});
Expand Down Expand Up @@ -77,7 +86,7 @@ function fetchIntegrationCatalog(catalogUrl: string): Promise<CatalogEntry[]> {

return response.json();
})
.then(parseCatalogEntries)
.then(raw => parseCatalogEntries(raw, catalogUrl))
.then(entries => {
resolved.set(catalogUrl, entries);

Expand All @@ -97,6 +106,8 @@ export function useIntegrationCatalog(): {
entries: CatalogEntry[];
ready: boolean;
error?: string;
/** Where the entries came from. */
catalogUrl: string;
} {
const catalogUrl = usePluginCatalogUrl();
const [entries, setEntries] = useState(() => resolved.get(catalogUrl));
Expand All @@ -118,7 +129,12 @@ export function useIntegrationCatalog(): {
};
}, [catalogUrl]);

return { entries: entries ?? [], ready: entries !== undefined, error };
return {
entries: entries ?? [],
ready: entries !== undefined,
error,
catalogUrl,
};
}

/**
Expand Down
46 changes: 46 additions & 0 deletions browser/data-browser/src/locales/de.po
Original file line number Diff line number Diff line change
Expand Up @@ -1895,6 +1895,7 @@ msgstr ""

#: src/actions/resourceActions.tsx
#: src/chunks/DashboardPage/blocks/ViewBlock.tsx
#: src/chunks/PluginRuns/CatalogApps.tsx
#: src/chunks/TablePage/Issues/IssueRow.tsx
#: src/chunks/TablePage/Kanban/KanbanCard.tsx
#: src/routes/IntegrationStore.tsx
Expand Down Expand Up @@ -3013,6 +3014,7 @@ msgstr ""
msgid "Enter valid JSON..."
msgstr ""

#: src/chunks/PluginRuns/CatalogApps.tsx
#: src/views/Installation/InstallationPage.tsx
msgid "Install"
msgstr ""
Expand Down Expand Up @@ -8485,7 +8487,9 @@ msgstr ""
msgid "Previous version"
msgstr ""

#. 0: app.version
#. 0: status.state!.deployments.indexOf(entry.deployment) + 1
#: src/chunks/PluginRuns/CatalogApps.tsx
#: src/chunks/Website/WebsiteHosting.tsx
msgid "Version {0}"
msgstr ""
Expand Down Expand Up @@ -9424,3 +9428,45 @@ msgstr ""
#: src/chunks/AppPage/AppFrame.tsx
msgid "Connect an account"
msgstr ""

#. 0: app.name; 1: app.version
#: src/chunks/PluginRuns/CatalogApps.tsx
msgid "{0} updated to {1}"
msgstr ""

#. 0: mine.version ?? '(unknown version)'
#: src/chunks/PluginRuns/CatalogApps.tsx
msgid "Installed {0}"
msgstr ""

#: src/chunks/PluginRuns/CatalogApps.tsx
msgid "Installing…"
msgstr ""

#. 0: app.name
#: src/chunks/PluginRuns/CatalogApps.tsx
msgid "Install {0}"
msgstr ""

#. 0: app.name
#: src/chunks/PluginRuns/CatalogApps.tsx
msgid "Open {0}"
msgstr ""

#: src/chunks/PluginRuns/CatalogApps.tsx
msgid "Updating…"
msgstr ""

#. 0: app.version
#: src/chunks/PluginRuns/CatalogApps.tsx
msgid "Update to {0}"
msgstr ""

#: src/chunks/PluginRuns/CatalogApps.tsx
#: src/chunks/PluginRuns/CatalogApps.tsx
msgid "Drive apps"
msgstr ""

#: src/chunks/PluginRuns/CatalogApps.tsx
msgid "Apps that run in their own frame on this drive and keep their rows in a table of their own. Each is a published version; installing checks its code against the catalog before anything is saved."
msgstr ""
Loading
Loading