Skip to content

Mount a directory from the browser #1482

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

Merged
merged 2 commits into from
Jun 2, 2024
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
15 changes: 15 additions & 0 deletions packages/docs/site/docs/10-javascript-api/06-mount-data.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Mount data

## Mount a directory from the browser

You can mount a directory from the browser to Playground using the `window.showDirectoryPicker` API. Check the [Browser compatibility](https://developer.mozilla.org/en-US/docs/Web/API/Window/showDirectoryPicker#browser_compatibility) before using this API.

```javascript
window.showDirectoryPicker().then(function (directoryHandle) {
window.parent.postMessage({
type: 'mount-directory-handle',
directoryHandle,
mountpoint: '/wordpress/wp-content/uploads/markdown/',
});
});
```
24 changes: 23 additions & 1 deletion packages/playground/remote/src/lib/boot-playground-remote.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
exposeAPI,
consumeAPI,
setupPostMessageRelay,
SyncProgressCallback
SyncProgressCallback,
} from '@php-wasm/web';

import type { PlaygroundWorkerEndpoint } from './worker-thread';
Expand Down Expand Up @@ -221,6 +221,7 @@ export async function bootPlaygroundRemote() {
wpFrame,
getOrigin((await playground.absoluteUrl)!)
);
setupMountListener(playground);
if (withNetworking) {
await setupFetchNetworkTransport(workerApi);
}
Expand All @@ -242,6 +243,27 @@ function getOrigin(url: string) {
return new URL(url, 'https://example.com').origin;
}

function setupMountListener(playground: WebClientMixin) {
window.addEventListener('message', async (event) => {
if (typeof event.data !== 'object') {
return;
}
if (event.data.type !== 'mount-directory-handle') {
return;
}
if (typeof event.data.directoryHandle !== 'object') {
return;
}
if (!event.data.mountpoint) {
return;
}
await playground.bindOpfs({
opfs: event.data.directoryHandle,
mountpoint: event.data.mountpoint,
});
});
}

function parseVersion<T>(value: string | undefined | null, latest: T) {
if (!value || value === 'latest') {
return latest as string;
Expand Down
Loading