Skip to content

Commit

Permalink
chore: refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
phonzammi committed Jun 19, 2024
1 parent b7b71e1 commit 236fea9
Show file tree
Hide file tree
Showing 14 changed files with 172 additions and 147 deletions.
91 changes: 19 additions & 72 deletions vike-solid/+config.ts
Original file line number Diff line number Diff line change
@@ -1,43 +1,26 @@
export { config };
import type { Config } from "vike/types";
import { ssrEffect } from './renderer/ssrEffect.js'

import type { Config, ConfigEffect, PageContext } from "vike/types";
import type { Component } from "solid-js";
// This is required to make TypeScript load the global interfaces such as Vike.PageContext so that they're always loaded.
// We can assume that the user always imports this file over `import vikeSolid from 'vike-solid/config'`
import "./types/index.js"

// Depending on the value of `config.meta.ssr`, set other config options' `env`
// accordingly.
// See https://vike.dev/meta#:~:text=Modifying%20the%20environment%20of%20existing%20hooks
const toggleSsrRelatedConfig: ConfigEffect = ({
configDefinedAt,
configValue,
}) => {
if (typeof configValue !== "boolean") {
throw new Error(`${configDefinedAt} should be a boolean`);
}

return {
meta: {
// When the SSR flag is false, we want to render the page only in the
// browser. We achieve this by then making the `Page` implementation
// accessible only in the client's renderer.
Page: {
env: configValue
? { server: true, client: true } // default
: { client: true },
},
},
};
};
export default {
name: "vike-solid",
require: {
vike: '>=0.4.173'
},

const config = {
// @ts-ignore Remove this ts-ignore once Vike's new version is released.
name: 'vike-solid',
// https://vike.dev/onRenderHtml
onRenderHtml: "import:vike-solid/renderer/onRenderHtml:onRenderHtml",
// https://vike.dev/onRenderClient
onRenderClient: "import:vike-solid/renderer/onRenderClient:onRenderClient",
// https://vike.dev/clientRouting

// https://vike.dev/clientRouting
clientRouting: true,
hydrationCanBeAborted: true,

// https://vike.dev/meta
meta: {
Head: {
Expand All @@ -58,7 +41,7 @@ const config = {
},
ssr: {
env: { config: true },
effect: toggleSsrRelatedConfig,
effect: ssrEffect,
},
stream: {
env: { server: true },
Expand All @@ -67,45 +50,9 @@ const config = {
name: {
env: { config: true }
},
// Vike already defines the setting 'require', but we redundantly define it here for older Vike versions (otherwise older Vike versions will complain that 'require` is an unknown config). TODO/eventually: remove this once <=0.4.172 versions become rare (also because we use the `require` setting starting from `0.4.173`).
require: {
env: { config: true }
},
},
} satisfies Config;

// We purposely define the ConfigVikeSolid interface in this file: that way we ensure it's always applied whenever the user `import vikeSolid from 'vike-solid/config'`
// https://vike.dev/pageContext#typescript
declare global {
namespace Vike {
interface Config {
/** The page's root Solid component */
Page?: Component;
/** Solid element renderer and appended into <head></head> */
Head?: Component;
/** A component, usually common to several pages, that wraps the root component `Page` */
Layout?: Component;
title?: string | ((pageContext: PageContext) => string);
favicon?: string;
/**
* @default 'en'
*/
lang?: string;
/**
* If true, render mode is SSR or pre-rendering (aka SSG). In other words, the
* page's HTML will be rendered at build-time or request-time.
* If false, render mode is SPA. In other words, the page will only be
* rendered in the browser.
*
* See https://vike.dev/render-modes
*
* @default true
*
*/
ssr?: boolean;
/**
* Whether to stream the page's HTML. Requires Server-Side Rendering (`ssr: true`).
*
* @default false
*
*/
stream?: boolean;
}
}
}
} satisfies Config;
34 changes: 29 additions & 5 deletions vike-solid/hooks/usePageContext.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,35 @@
export { usePageContext };
export { PageContextProvider };

import { useContext } from "solid-js";
import { Context } from "../renderer/PageContextProvider.js";
import { createContext, useContext, type JSX } from "solid-js";
import { type Store } from "solid-js/store";
import type { PageContext } from "vike/types";
import { getGlobalObject } from "../utils/getGlobalObject.js";

/** Access the pageContext from any SolidJS component */
function usePageContext() {
const pageContext = useContext(Context);
const globalContext = getGlobalObject("PageContextProvider.ts", {
solidContext: createContext<Store<PageContext>>(undefined as never),
});

function PageContextProvider(props: {
pageContext: Store<PageContext>;
children: JSX.Element;
}) {
const { solidContext } = globalContext
return (
<solidContext.Provider value={props.pageContext}>
{props.children}
</solidContext.Provider>
);
}

/**
* Access `pageContext` from any Solid component.
*
* https://vike.dev/usePageContext
*/
function usePageContext(): PageContext {
const { solidContext } = globalContext
const pageContext = useContext(solidContext)
if (!pageContext)
throw new Error(
"<PageContextProvider> is needed for being able to use usePageContext()"
Expand Down
5 changes: 5 additions & 0 deletions vike-solid/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// TODO/next-major-release: remove this file/export
console.warn(
"[vike-solid][warning][deprecation] Replace `import vikeSolid from 'vike-solid'` with `import vikeSolid from 'vike-solid/config'` (typically in your /pages/+config.js)"
);
export { default } from "./+config.js";
5 changes: 0 additions & 5 deletions vike-solid/main.ts

This file was deleted.

8 changes: 4 additions & 4 deletions vike-solid/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
"vite": "^5.3.1"
},
"exports": {
".": "./dist/main.js",
".": "./dist/index.js",
"./config": "./dist/+config.js",
"./vite": "./dist/vite-plugin-vike-solid.js",
"./usePageContext": "./dist/hooks/usePageContext.js",
Expand All @@ -48,7 +48,7 @@
"typesVersions": {
"*": {
".": [
"dist/main.d.ts"
"dist/index.d.ts"
],
"config": [
"dist/+config.d.ts"
Expand All @@ -74,8 +74,8 @@
"dist/",
"client.d.ts"
],
"main": "dist/main.js",
"types": "dist/main.d.ts",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"repository": "github:vikejs/vike-solid",
"license": "MIT"
}
23 changes: 0 additions & 23 deletions vike-solid/renderer/PageContextProvider.tsx

This file was deleted.

3 changes: 1 addition & 2 deletions vike-solid/renderer/getPageElement.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import type { PageContext } from "vike/types";
import { PageContextProvider } from "./PageContextProvider.js";
import { usePageContext } from "../hooks/usePageContext.js";
import { usePageContext, PageContextProvider } from "../hooks/usePageContext.js";
import type { FlowComponent, JSX } from "solid-js";
import { createComponent, createComputed } from "solid-js";
import { Dynamic } from "solid-js/web";
Expand Down
2 changes: 1 addition & 1 deletion vike-solid/renderer/onRenderClient.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ const onRenderClient: OnRenderClientAsync = async (

setPageContext(pageContext);

const container = document.getElementById("page-view")!;
const container = document.getElementById("root")!;
if (container.innerHTML !== "" && pageContext.isHydration) {
// Hydration
dispose = hydrate(() => getPageElement(pageContextStore)!, container);
Expand Down
31 changes: 15 additions & 16 deletions vike-solid/renderer/onRenderHtml.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { dangerouslySkipEscape, escapeInject, stampPipe, version } from "vike/se
import { getHeadSetting } from "./getHeadSetting.js";
import { getPageElement } from "./getPageElement.js";
import type { OnRenderHtmlAsync } from "vike/types";
import { PageContextProvider } from "./PageContextProvider.js";
import { PageContextProvider } from "../hooks/usePageContext.js";

checkVikeVersion();

Expand All @@ -18,17 +18,17 @@ const onRenderHtml: OnRenderHtmlAsync = async (
const lang = getHeadSetting("lang", pageContext) || "en";

const titleTag = !title ? "" : escapeInject`<title>${title}</title>`;
const faviconTag = !favicon
? ""
: escapeInject`<link rel="icon" href="${favicon}" />`;
const faviconTag = !favicon ? "" : escapeInject`<link rel="icon" href="${favicon}" />`;

const Head = pageContext.config.Head || (() => <></>);
const headHtml = renderToString(() => (
const head = renderToString(() => (
<PageContextProvider pageContext={pageContext}>
<Head />
</PageContextProvider>
));

const headHtml = dangerouslySkipEscape(head)

type TPipe = (writable: { write: (v: string) => void }) => void;

let pageView: string | ReturnType<typeof dangerouslySkipEscape> | TPipe = "";
Expand All @@ -48,29 +48,28 @@ const onRenderHtml: OnRenderHtmlAsync = async (
<head>
<meta charset="UTF-8" />
${titleTag}
${dangerouslySkipEscape(headHtml)}
${headHtml}
${faviconTag}
${dangerouslySkipEscape(generateHydrationScript())}
</head>
<body>
<div id="page-view">${pageView}</div>
<div id="root">${pageView}</div>
</body>
<!-- built with https://github.com/vikejs/vike-solid -->
</html>`;

return documentHtml;
};

// We don't need this anymore starting from [email protected] which added the `require` setting.
// TODO/eventually: remove this once <=0.4.172 versions become rare.
function checkVikeVersion() {
if (version) {
const versionParts = version.split(".").map((s) => parseInt(s, 10)) as [
number,
number,
number
];
if (versionParts[0] > 0) return;
if (versionParts[1] > 4) return;
if (versionParts[2] >= 147) return;
const versionParts = version.split('.').map((s) => parseInt(s, 10)) as [number, number, number]
if (versionParts[0] > 0) return
if (versionParts[1] > 4) return
if (versionParts[2] >= 173) return
}
throw new Error("Update Vike to 0.4.147 or above");
// We can leave it 0.4.173 until we entirely remove checkVikeVersion() (because starting [email protected] we use the new `require` setting).
throw new Error('Update Vike to 0.4.173 or above')
}
21 changes: 21 additions & 0 deletions vike-solid/renderer/ssrEffect.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
export { ssrEffect }

import type { ConfigEffect } from 'vike/types'

function ssrEffect({ configDefinedAt, configValue }: Parameters<ConfigEffect>[0]): ReturnType<ConfigEffect> {
if (typeof configValue !== 'boolean') throw new Error(`${configDefinedAt} should be a boolean`)
return {
meta: {
Page: {
env: {
// Always load `Page` on the client-side.
client: true,
// When the SSR flag is false, we want to render the page only on the client-side.
// We achieve this by loading `Page` only on the client-side: when onRenderHtml()
// gets a `Page` value that is undefined it skip server-side rendering.
server: configValue !== false
}
}
}
}
}
4 changes: 2 additions & 2 deletions vike-solid/rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export default [
withSolid({
input: {
"renderer/onRenderHtml": "./renderer/onRenderHtml.tsx",
"main": "./main.ts",
"index": "./index.ts",
"+config": "./+config.ts",
"hooks/usePageContext": "./hooks/usePageContext.tsx",
"hooks/useData": "./hooks/useData.tsx",
Expand All @@ -26,7 +26,7 @@ export default [
}),
{
input: [
"./main.ts",
"./index.ts",
"./+config.ts",
"./hooks/usePageContext.tsx",
"./hooks/useData.tsx",
Expand Down
Loading

0 comments on commit 236fea9

Please sign in to comment.