Skip to content

Commit

Permalink
simplify routes further
Browse files Browse the repository at this point in the history
  • Loading branch information
jacob-8 committed Oct 18, 2023
1 parent d7124da commit fcb6f8c
Show file tree
Hide file tree
Showing 19 changed files with 117 additions and 155 deletions.
1 change: 1 addition & 0 deletions eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export default antfu(
'**/.svelte-kit**',
'**/package/**',
'**/src/routes/kitbook/**',
'**/src/lib/routes/+layout.ts',
],
},
)
Expand Down
3 changes: 1 addition & 2 deletions packages/kitbook/src/lib/layout/Layout.svelte
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
<script lang="ts">
import '@kitbook/mdsvex-shiki-twoslash/shiki-twoslash.css'
import '../styles/main.css'
import { settings } from 'virtual:kitbook-settings'
import Header from './sidebar/Header.svelte'
import Sidebar from './sidebar/Sidebar.svelte'
import { putPagesIntoFolders } from './parseModules/putPagesIntoFolders'
Expand All @@ -10,7 +9,7 @@
import { page } from '$app/stores'
// import InstrumentPanel from './instrument-panel/InstrumentPanel.svelte';
const { title, description, expandTree, githubURL } = settings || {}
const { title, description, expandTree, githubURL } = $page.data.settings
$: ({ kitbookPath, activePath } = findKitbookPath($page.url.pathname))
let showSidebar = false
Expand Down
38 changes: 28 additions & 10 deletions packages/kitbook/src/lib/layout/layoutLoad.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,41 @@
import type { GroupedPageMap } from "kitbook";
import type { GroupedPageMap, KitbookSettings } from 'kitbook'
import { pagesStore } from '../modules/hmrUpdatedModules'

// import { derived } from 'svelte/store'

/**
* The default modules glob import used by Kitbook is this
* ```js
* const modules = import.meta.glob(['/src/**\/*.{md,svx,svelte,variants.ts}', '/README.md']);
* ```
* `{md,svx}` = Kitbook Story Files
*
*
* `{svelte,variants.ts}` = Automatically create a default Story for each component w/ variants automatically being populated by colocated files `*.variants.ts` files (Foo.svelte and Foo.variants.ts; +page.svelte and _page.variants.ts)
*/
export function layoutLoad({ pages }:
{
pages: GroupedPageMap,
}) {
export function layoutLoad({ pages: initialPages, settings, variantsTemplate }:
{
pages: GroupedPageMap
settings: KitbookSettings
variantsTemplate: string
}) {
return async () => {
if (!Object.keys(pages).length) throw new Error('No pages found. Did you import layoutLoad into your Kitbook layout.ts file and you have at least a README.md or one +page.svelte, +layout.svelte, *.svelte, *.md, or *.svx file in your project?')
if (!Object.keys(initialPages).length)
throw new Error('No pages found. Did you import layoutLoad into your Kitbook layout.ts file and you have at least a README.md or one +page.svelte, +layout.svelte, *.svelte, *.md, or *.svx file in your project?')

// console.log({ initialPages })
// const pages = derived(pagesStore, ($pagesStore, set) => {
// console.log({ $pagesStore })
// if (Object.keys($pagesStore).length) {
// console.log('setting pages')
// set($pagesStore)
// }
// }, initialPages)

return {
pages,
};
pages: initialPages,
pagesStore,
settings,
variantsTemplate,
}
}
}
}
16 changes: 10 additions & 6 deletions packages/kitbook/src/lib/open/openFiles.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
import { settings } from 'virtual:kitbook-settings'
import { variants as variantsTemplate } from 'virtual:kitbook-templates'
import { get } from 'svelte/store'
import { removeQuotesFromSerializedFunctions, serialize } from './serialize'
import { page } from '$app/stores'

// import { generateCode, parseModule } from 'magicast'

export function openComponent(filename: string) {
const { data } = get(page)
const file_loc = `${filename}:1:1`
fetch(`${settings.viewer.__internal.viteBase}/__open-in-editor?file=${encodeURIComponent(file_loc)}`)
fetch(`${data.settings.viewer.__internal.viteBase}/__open-in-editor?file=${encodeURIComponent(file_loc)}`)
}

export function openVariantsWithoutProps(path: string) {
const modifiedTemplate = variantsTemplate.replace('Template.svelte', path.split('/').pop())
const { data } = get(page)
const modifiedTemplate = data.variantsTemplate.replace('Template.svelte', path.split('/').pop())
const variantsPath = path.replace('.svelte', '.variants.ts')
ensureFileExists(variantsPath, modifiedTemplate)
}
Expand All @@ -25,7 +27,8 @@ export function openVariants(filename: string, variantsFilename: string, compone
// module.exports.variants[0].props = serializedState
// const { code } = generateCode(module)

const code = variantsTemplate.replace('props: {}', `props: ${JSON.stringify(serializedState, null, 2)}`)
const { data } = get(page)
const code = data.variantsTemplate.replace('props: {}', `props: ${JSON.stringify(serializedState, null, 2)}`)
const modifiedTemplate = removeQuotesFromSerializedFunctions(code.replace('Template.svelte', filename.split('/').pop()))
ensureFileExists(variantsFilename, modifiedTemplate)
}
Expand Down Expand Up @@ -57,6 +60,7 @@ function ensureFileExists(filename: string, template: string) {
if (import.meta.hot) {
import.meta.hot.on('kitbook:open-file', ({ filename }) => {
const file_loc = `${filename}:1:1`
fetch(`${settings.viewer.__internal.viteBase}/__open-in-editor?file=${encodeURIComponent(file_loc)}`)
const { data } = get(page)
fetch(`${data.settings.viewer.__internal.viteBase}/__open-in-editor?file=${encodeURIComponent(file_loc)}`)
})
}
6 changes: 3 additions & 3 deletions packages/kitbook/src/lib/pages/MainPage.svelte
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
<script lang="ts">
import '../styles/kb-prose.css'
import type { GroupedPage, GroupedPageMap, LoadedModules, VariantsModule } from 'kitbook'
import type { GroupedPage, GroupedPageMap, KitbookSettings, LoadedModules, VariantsModule } from 'kitbook'
import { Button } from 'svelte-pieces'
import { settings } from 'virtual:kitbook-settings'
import EditInGithub from '../components/EditInGithub.svelte'
import { pagesStore } from '../modules/hmrUpdatedModules'
import { openComponent, openSvx, openVariantsWithoutProps } from '../open/openFiles'
Expand All @@ -11,14 +10,15 @@
import { dev } from '$app/environment'
export let data: {
settings?: KitbookSettings
pages?: GroupedPageMap
page?: GroupedPage
pageKey?: string
loadedModules?: LoadedModules
error?: string
} = { loadedModules: {} }
const { viewports, languages, githubURL } = settings
const { viewports, languages, githubURL } = data.settings
$: pageFromUpdatingStore = $pagesStore?.[data.pageKey]
let variantsModule: VariantsModule
Expand Down
81 changes: 31 additions & 50 deletions packages/kitbook/src/lib/pages/SandboxPage.svelte
Original file line number Diff line number Diff line change
@@ -1,77 +1,58 @@
<script lang="ts">
import { type SvelteComponent, getContext, setContext } from 'svelte'
import { type SvelteComponent, setContext } from 'svelte'
import type { Writable } from 'svelte/store'
import type { GroupedPage, GroupedPageMap, LoadedModules, Variant } from '../kitbook-types'
import ErrorBoundary from '../components/errorBoundary/ErrorBoundary.js'
export let data: {
pages: GroupedPageMap
pagesStore: Writable<GroupedPageMap>
page: GroupedPage
pageKey: string
loadedModules: LoadedModules
storyId: string
variant?: Variant<SvelteComponent>
variantIdx?: string // string is better because it works as an index also and doesn't give false negative on '0'
editedProps?: Record<string, any>
// error?: string;
}
let { variant } = data
const pagesStore = getContext<Writable<GroupedPageMap>>('pages-store')
let { variant, pagesStore } = data
$: page = $pagesStore[data.pageKey]
$: if (page?.loadVariants?.loadModule && data.variantIdx) {
page.loadVariants.loadModule().then((module) => {
variant = module?.variants[data.variantIdx] || {}
}).catch((error) => {
console.error(error)
})
page.loadVariants
.loadModule()
.then((module) => {
variant = module?.variants[data.variantIdx] || {}
})
.catch((error) => {
console.error(error)
})
}
const isStory = !!data.storyId
if (isStory) {
// `Story` components check the `sandboxId` context to know whether to show when in the sandbox - this is passed to the sandbox originally using the `storyId` query param in iframe url
setContext<string>('sandboxId', data.storyId)
setContext<Record<string, any>>('sandboxProps', data.editedProps || {})
}
for (const { key, context } of data.variant?.contexts || [])
setContext(key, context)
for (const { key, context } of data.variant?.contexts || []) setContext(key, context)
</script>

<div class="absolute inset-0 overflow-auto">
{#if isStory}
<div id="sandbox" style="display: contents;">
<svelte:component this={data.loadedModules.svx} />
<ErrorBoundary onError={console.error}>
<div slot="before">
{#if Object.keys(variant.props).length === 0}
<b>Kitbook tip</b>: Your component may need props passed in. Create a "{data.page
?.name}.variants.ts" file with at least variant. In the future Kitbook will try to
automatically supply default props, but until then they must be supplied manually.
{/if}
</div>
{:else}
<ErrorBoundary onError={console.error}>
<div slot="before">
{#if Object.keys(variant.props).length === 0}
<b>Kitbook tip</b>: Your component may need props passed in. Create a "{data.page?.name}.variants.ts" file with at least variant. In the future Kitbook will try to
automatically supply default props, but until then they must be supplied manually.
{#if variant?.slots}
{@const defaultSlotContent = variant.slots.default}
<svelte:component this={data.loadedModules.component} {...variant.props}>
{#if typeof defaultSlotContent === 'string'}
{@html defaultSlotContent}
{:else}
<svelte:component this={defaultSlotContent} />
{/if}
</div>
{#if variant?.slots}
{@const defaultSlotContent = variant.slots.default}
<svelte:component this={data.loadedModules.component} {...variant.props}>
{#if typeof defaultSlotContent === 'string'}
{@html defaultSlotContent}
{:else}
<svelte:component this={defaultSlotContent} />
{/if}
</svelte:component>
{:else}
<svelte:component this={data.loadedModules.component} {...variant.props} />
{/if}
</ErrorBoundary>
{/if}
</svelte:component>
{:else}
<svelte:component this={data.loadedModules.component} {...variant.props} />
{/if}
</ErrorBoundary>
</div>

<style>
#sandbox > :global(:not(.show-in-sandbox)) {
display: none;
}
</style>
12 changes: 6 additions & 6 deletions packages/kitbook/src/lib/pages/sandboxPageLoad.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,18 @@ export async function sandboxPageLoad({ params, parent, url }) {
const page: GroupedPage = pages[pageKey]
const loadedModules: LoadedModules = {}

const storyId = url.searchParams.get('storyId') as string
// const storyId = url.searchParams.get('storyId') as string
const variantIdx = url.searchParams.get('variantIdx')

if (storyId)
loadedModules.svx = (await page.loadSvx.loadModule() as any).default as typeof SvelteComponent
else
loadedModules.component = (await page.loadComponent.loadModule() as any).default as typeof SvelteComponent
// if (storyId)
// loadedModules.svx = (await page.loadSvx.loadModule() as any).default as typeof SvelteComponent
// else
loadedModules.component = (await page.loadComponent.loadModule() as any).default as typeof SvelteComponent

let variant: Variant<SvelteComponent>
if (variantIdx)
variant = (await page.loadVariants.loadModule()).variants[variantIdx] || {}

const editedProps: Record<string, any> = JSON.parse(decode(url.searchParams.get('props')) || null)
return { page, pageKey, loadedModules, storyId, variant, variantIdx, editedProps }
return { page, pageKey, loadedModules, variant, variantIdx, editedProps }
}
10 changes: 4 additions & 6 deletions packages/kitbook/src/lib/plugins/vite/constants.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
export enum VirtualModules {
KITBOOK_MODULES = 'virtual:kitbook-modules',
KITBOOK_SETTINGS = 'virtual:kitbook-settings',
KITBOOK_TEMPLATES = 'virtual:kitbook-templates',
}
export const DEFAULT_IMPORT_MODULE_GLOBS = [
'/src/**/*.{md,svx,svelte,variants.ts}',
'/README.md',
]

export const DEFAULT_IMPORT_MODULE_GLOBS = ['/src/**/*.{md,svx,svelte,variants.ts}', '/README.md']
export const DEFAULT_VIEWPORTS = [
{ name: 'mobile', width: 375, height: 667 },
{ name: 'tablet', width: 768, height: 800 }, // height should probably be 1024, but until the iframe can automatically decrease height to fit content let's do this
Expand Down
4 changes: 2 additions & 2 deletions packages/kitbook/src/lib/plugins/vite/initKitbook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const red = '\x1B[31m'
const bold = '\x1B[1m'
const reset = '\x1B[0m'

const LATEST_VERSION_WITH_ROUTES_UPDATE = '[email protected].48^'
const LATEST_VERSION_WITH_ROUTES_UPDATE = '[email protected].50^'
const FILE_WITH_NOTICE = '[...file]/+page.svelte'

export function initKitbook({ routesDirectory, kitbookRoute }: KitbookSettings) {
Expand All @@ -36,7 +36,7 @@ export function initKitbook({ routesDirectory, kitbookRoute }: KitbookSettings)
const src = 'node_modules/kitbook/dist/routes'
const destination = kitbookDirectory
fs.cpSync(src, destination, { recursive: true, filter: excludeDocFiles })
console.log(`${bold}${green}[Kitbook] Added Kitbook route files to ${kitbookDirectory}. Don't edit these. They will be automatically updated by Kitbook in future versions when needed.\n${reset}`)
console.info(`${bold}${green}[Kitbook] Added Kitbook route files to ${kitbookDirectory}. Don't edit these. They will be automatically updated by Kitbook in future versions when needed.\n${reset}`)
}
catch (e) {
console.error(`${bold}${red}[Kitbook] Error copying in needed routes: ${e}\n${reset}`)
Expand Down
23 changes: 12 additions & 11 deletions packages/kitbook/src/lib/plugins/vite/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@ import type { Plugin } from 'vite'
import type { KitbookSettings } from '../../kitbook-types'
import { initKitbook } from './initKitbook.js'
import { modifyViteConfigForKitbook } from './modifyViteConfigForKitbook.js'
import { DEFAULT_IMPORT_MODULE_GLOBS, DEFAULT_KITBOOK_ROUTE, DEFAULT_ROUTES_DIR, DEFAULT_VIEWPORTS, VirtualModules } from './constants.js'
import { DEFAULT_IMPORT_MODULE_GLOBS, DEFAULT_KITBOOK_ROUTE, DEFAULT_ROUTES_DIR, DEFAULT_VIEWPORTS } from './constants.js'
import { writeModuleGlobsIntoVirtualModuleCode } from './writeModuleGlobsIntoVirtualModuleCode.js'
import { kitbookViewer } from './viewer/index.js'
import { DEFAULT_VIEWER_OPTIONS } from './viewer/options.js'

const LOAD_MODULES_ID = 'virtual:kitbook'

/**
* Vite plugin to add a Kitbook to SvelteKit projects. Will automatically add Kitbook routes to `src/routes/kitbook` unless you update the `routesDirectory` and `kitbookRoute` settings.
*/
Expand Down Expand Up @@ -41,23 +43,22 @@ export function kitbook(userSettings: Partial<KitbookSettings> = {}): Plugin[] {
config: modifyViteConfigForKitbook,

resolveId(id) {
if (Object.values(VirtualModules).includes(id as VirtualModules))
return addVirtualFilePrefix(id)
if (id === LOAD_MODULES_ID)
return addVirtualFilePrefix(LOAD_MODULES_ID)
},

load(id) {
if (id === addVirtualFilePrefix(VirtualModules.KITBOOK_SETTINGS))
return `export const settings = ${JSON.stringify(settings)}`

if (id === addVirtualFilePrefix(VirtualModules.KITBOOK_MODULES)) {
if (id === addVirtualFilePrefix(LOAD_MODULES_ID)) {
const _dirname = dirname(fileURLToPath(import.meta.url))
const filepath = resolve(_dirname, './virtual/importModules.js')
const content = readFileSync(filepath, 'utf-8')
return writeModuleGlobsIntoVirtualModuleCode(content, settings.importModuleGlobs || DEFAULT_IMPORT_MODULE_GLOBS)
}
const pageModulesCode = writeModuleGlobsIntoVirtualModuleCode(content, settings.importModuleGlobs || DEFAULT_IMPORT_MODULE_GLOBS)

if (id === addVirtualFilePrefix(VirtualModules.KITBOOK_TEMPLATES))
return `export const variants = \`${getVariantsTemplate()}\``
return `${pageModulesCode}
export const settings = ${JSON.stringify(settings)}
export const variantsTemplate = \`${getVariantsTemplate()}\`
`
}
},
}

Expand Down
16 changes: 3 additions & 13 deletions packages/kitbook/src/lib/plugins/vite/virtual/virtual-module.d.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,7 @@
declare module 'virtual:kitbook-modules' {
import type { GroupedPageMap } from 'kitbook'
declare module 'virtual:kitbook' {
import type { GroupedPageMap, KitbookSettings, Variant } from 'kitbook'

export const pages: GroupedPageMap
}

declare module 'virtual:kitbook-settings' {
import type { KitbookSettings } from 'kitbook'

export const settings: KitbookSettings
}

declare module 'virtual:kitbook-templates' {
import type { KitbookSettings } from 'kitbook'

export const variants: string
export const variantsTemplate: string
}
8 changes: 0 additions & 8 deletions packages/kitbook/src/lib/routes/+layout.svelte

This file was deleted.

5 changes: 3 additions & 2 deletions packages/kitbook/src/lib/routes/+layout.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// @ts-ignore - virtual import
import { pages, settings, variantsTemplate } from 'virtual:kitbook'
import { layoutLoad } from 'kitbook'
import { pages } from 'virtual:kitbook-modules'
import type { LayoutLoad } from './$types'

export const load = layoutLoad({ pages }) satisfies LayoutLoad
export const load = layoutLoad({ pages, settings, variantsTemplate }) satisfies LayoutLoad
Loading

2 comments on commit fcb6f8c

@vercel
Copy link

@vercel vercel bot commented on fcb6f8c Oct 18, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

kitbook – ./packages/kitbook

kitbook-git-main-polylingual.vercel.app
kitbook.vercel.app
kitbook-polylingual.vercel.app

@vercel
Copy link

@vercel vercel bot commented on fcb6f8c Oct 18, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

kitbook-template – ./packages/template

kitbook-template-git-main-polylingual.vercel.app
kitbook-template-polylingual.vercel.app
kitbook-template.vercel.app

Please sign in to comment.