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

feat(server): plugins can create islands #1472

Merged
merged 20 commits into from
Nov 22, 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
14 changes: 14 additions & 0 deletions docs/canary/concepts/plugins.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,3 +163,17 @@ For more examples see the [Concepts: Routing](/docs/concepts/routing) page.
To create a middleware you need to create a `MiddlewareHandler` function.

And to create a route you can create both a Handler and/or component.

A very basic example can be found
[here](https://github.com/denoland/fresh/blob/main/tests/fixture_plugin/utils/route-plugin.ts).

### Islands

You can create islands that get loaded and rendered like normal
[islands](/docs/concepts/islands).

You need to provide the location of your plugin and an array of island
filenames. The intent is to somewhat mimic the manifest file.

A very basic example can be found
[here](https://github.com/denoland/fresh/blob/main/tests/fixture_plugin/utils/route-plugin.ts).
1 change: 1 addition & 0 deletions src/server/deps.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// -- std --
export {
basename,
dirname,
extname,
fromFileUrl,
Expand Down
55 changes: 48 additions & 7 deletions src/server/fs_extract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
ErrorPageModule,
InternalFreshState,
Island,
IslandModule,
LayoutModule,
LayoutRoute,
MiddlewareHandler,
Expand All @@ -19,7 +20,15 @@ import {
} from "./types.ts";
import * as router from "./router.ts";
import DefaultErrorHandler from "./default_error_page.tsx";
import { extname, join, toFileUrl, typeByExtension, walk } from "./deps.ts";
import {
basename,
dirname,
extname,
join,
toFileUrl,
typeByExtension,
walk,
} from "./deps.ts";
import { BUILD_ID } from "./build_id.ts";
import { toBaseRoute } from "./compose.ts";

Expand Down Expand Up @@ -233,6 +242,28 @@ export async function extractRoutes(
}
}

const processedIslands: {
name: string;
path: string;
module: IslandModule;
}[] = [];

for (const plugin of config.plugins || []) {
if (!plugin.islands) continue;
const base = dirname(plugin.islands.baseLocation);
for (const name of plugin.islands.paths) {
const full = join(base, name);
const module = await import(full);
const fileNameWithExt = basename(full);
const fileName = fileNameWithExt.replace(extname(fileNameWithExt), "");
processedIslands.push({
name: sanitizeIslandName(fileName),
path: full,
module,
});
}
}

for (const [self, module] of Object.entries(manifest.islands)) {
const url = new URL(self, baseUrl).href;
if (!url.startsWith(baseUrl)) {
Expand All @@ -244,16 +275,26 @@ export async function extractRoutes(
}
const baseRoute = path.substring(0, path.length - extname(path).length);

for (const [exportName, exportedFunction] of Object.entries(module)) {
if (typeof exportedFunction !== "function") {
continue;
}
const name = sanitizeIslandName(baseRoute);
processedIslands.push({
name: sanitizeIslandName(baseRoute),
path: url,
module,
});
}

for (const processedIsland of processedIslands) {
for (
const [exportName, exportedFunction] of Object.entries(
processedIsland.module,
)
) {
if (typeof exportedFunction !== "function") continue;
const name = processedIsland.name;
const id = `${name}_${exportName}`.toLowerCase();
islands.push({
id,
name,
url,
url: processedIsland.path,
component: exportedFunction,
exportName,
});
Expand Down
2 changes: 2 additions & 0 deletions src/server/mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,15 @@ export type {
Plugin,
PluginAsyncRenderContext,
PluginAsyncRenderFunction,
PluginIslands,
PluginMiddleware,
PluginRenderContext,
PluginRenderFunction,
PluginRenderFunctionResult,
PluginRenderResult,
PluginRenderScripts,
PluginRenderStyleTag,
PluginRoute,
RenderFunction,
ResolvedFreshConfig,
RouteConfig,
Expand Down
7 changes: 7 additions & 0 deletions src/server/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -590,6 +590,8 @@ export interface Plugin<State = Record<string, unknown>> {
routes?: PluginRoute[];

middlewares?: PluginMiddleware<State>[];

islands?: PluginIslands;
}

export interface PluginRenderContext {
Expand Down Expand Up @@ -672,3 +674,8 @@ export interface PluginRoute {
// deno-lint-ignore no-explicit-any
handler?: Handler<any, any> | Handlers<any, any>;
}

export interface PluginIslands {
baseLocation: string;
paths: string[];
}
20 changes: 16 additions & 4 deletions tests/fixture_plugin/utils/route-plugin.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { MiddlewareHandlerContext, Plugin } from "$fresh/server.ts";
import { handler as testMiddleware } from "./sample_routes/_middleware.ts";
import { AppBuilder } from "./sample_routes/AppBuilder.tsx";
import IslandPluginComponent from "./sample_routes/PluginRouteWithIsland.tsx";
import { SimpleRoute } from "./sample_routes/simple-route.tsx";
export type { Options };

Expand Down Expand Up @@ -43,9 +44,20 @@ export default function routePlugin(
},
path: "lots-of-middleware",
}],
routes: [{
path: "/_app",
component: AppBuilder(options),
}, { path: "no-leading-slash-here", component: SimpleRoute }],
routes: [
{
path: "/_app",
component: AppBuilder(options),
},
{ path: "no-leading-slash-here", component: SimpleRoute },
{
path: "pluginroutewithisland",
component: IslandPluginComponent,
},
],
islands: {
baseLocation: import.meta.url,
paths: ["./sample_islands/IslandFromPlugin.tsx"],
},
};
}
10 changes: 10 additions & 0 deletions tests/fixture_plugin/utils/sample_islands/IslandFromPlugin.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { IS_BROWSER } from "../../../../src/runtime/utils.ts";

export default function IslandFromPlugin() {
const id = IS_BROWSER ? "csr_alt_folder" : "ssr_alt_folder";
return (
<div>
<p id={id}>{id}</p>
</div>
);
}
11 changes: 11 additions & 0 deletions tests/fixture_plugin/utils/sample_routes/PluginRouteWithIsland.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import Island from "../../islands/Island.tsx";
import IslandFromPlugin from "../sample_islands/IslandFromPlugin.tsx";

export default function IslandPluginComponent() {
return (
<div>
<Island />
<IslandFromPlugin />
</div>
);
}
28 changes: 28 additions & 0 deletions tests/plugin_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,34 @@ Deno.test("plugin route no leading slash", async () => {
);
});

Deno.test({
name: "plugin supports islands",
async fn(t) {
await withPageName(
"./tests/fixture_plugin/main.ts",
async (page, address) => {
async function idTest(id: string) {
const elem = await page.waitForSelector(`#${id}`);

const value = await elem?.evaluate((el) => el.textContent);
assert(value === `${id}`, `value ${value} not equal to id ${id}`);
}

await page.goto(`${address}/pluginroutewithisland`, {
waitUntil: "networkidle2",
});

await t.step("verify tags", async () => {
await idTest("csr");
await idTest("csr_alt_folder");
});
},
);
},
sanitizeOps: false,
sanitizeResources: false,
});

Deno.test({
name: "/with-island hydration",
async fn(t) {
Expand Down
Loading