Skip to content

Commit

Permalink
fix: router has now fully static site support, fix navigation
Browse files Browse the repository at this point in the history
  • Loading branch information
itsjavi committed Aug 8, 2023
1 parent bd5397c commit 2893e37
Show file tree
Hide file tree
Showing 13 changed files with 86 additions and 55 deletions.
3 changes: 2 additions & 1 deletion packages/examples/react/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
"scripts": {
"build": "vite build",
"dev": "vite --port=7707",
"preview": "vite preview",
"preview": "vite build && vite preview",
"preview-static": "vite build && open http://localhost:8080 && npx -y http-server ./dist",
"storylite": "open http://localhost:7707 && vite --port=7707"
},
"dependencies": {
Expand Down
6 changes: 6 additions & 0 deletions packages/storylite/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# @storylite/storylite

## 0.1.2

### Patch Changes

- fix: router has now fully static site support. fix navigation.

## 0.1.1

### Patch Changes
Expand Down
2 changes: 1 addition & 1 deletion packages/storylite/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@storylite/storylite",
"version": "0.1.1",
"version": "0.1.2",
"description": "A lightweight alternative to StoryBook, built on top of Vite⚡️",
"license": "MIT",
"type": "module",
Expand Down
48 changes: 17 additions & 31 deletions packages/storylite/src/components/Story.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,14 @@ import { ElementIds, StoryComponent, StoryMeta, StoryModule } from '@/types'

import Toolbar from './Toolbar'

export function Story({ story, exportName }: { story: string; exportName: string }): JSX.Element {
export function Story({ story, exportName }: { story: string; exportName?: string }): JSX.Element {
const notFound = (
<StorySandbox story={story}>
<StorySandbox story={story} exportName={exportName}>
<h3>
Story not found:{' '}
<var>
{story}.{exportName}
{story}
{exportName ? `.${exportName}` : '.?'}
</var>
</h3>
</StorySandbox>
Expand All @@ -24,8 +25,15 @@ export function Story({ story, exportName }: { story: string; exportName: string
return notFound
}

if (exportName.match(/^[A-Z]/) && typeof storyMapData.module[exportName] === 'function') {
const StorySandboxWrapper = createStorySandboxWrapper(story, exportName, storyMapData.module)
const defaultExportName = Object.keys(storyMapData.module).filter(key => key !== 'default')[0]
const _exportName = exportName ?? defaultExportName

if (!_exportName) {
return notFound
}

if (_exportName.match(/^[A-Z]/) && typeof storyMapData.module[_exportName] === 'function') {
const StorySandboxWrapper = createStorySandboxWrapper(story, _exportName, storyMapData.module)

return <StorySandboxWrapper />
}
Expand All @@ -45,19 +53,12 @@ function createStorySandboxWrapper(
}

const components: [string, StoryComponent][] = []
// const componentNames = getStoryComponentNames(storyExport)
const metadata = storyExport.default || {}

// for (const key of componentNames) {
// components.push([key, storyExport[key]])
// }

components.push([exportName, storyExport[exportName]])

const StoryWrapper = () => {
const stories = components.map(([, Comp], i) => {
// const title = Comp.storyTitle || Comp.displayName || compName

return (
<section key={i} className={'Section'}>
<Comp />
Expand All @@ -66,7 +67,7 @@ function createStorySandboxWrapper(
})

return (
<StorySandbox story={story} metadata={metadata}>
<StorySandbox story={story} exportName={exportName} metadata={metadata}>
{stories}
</StorySandbox>
)
Expand All @@ -77,10 +78,12 @@ function createStorySandboxWrapper(

export function StorySandbox({
story,
exportName,
metadata,
children,
}: {
story: string
exportName?: string
metadata?: StoryMeta
children?: React.ReactNode
}) {
Expand All @@ -92,7 +95,7 @@ export function StorySandbox({
return (
<div className={`${'Story'} ${isStandalone ? 'StandaloneStory' : ``}`}>
<header className={'Header'} style={toolbarStyles}>
<Toolbar story={story} storyMeta={metadata} />
<Toolbar story={story} exportName={exportName} storyMeta={metadata} />
</header>
<div id={ElementIds.StoryCanvas} className={'Canvas'}>
{children === undefined && <p>Loading story...</p>}
Expand All @@ -101,20 +104,3 @@ export function StorySandbox({
</div>
)
}

// function getStoryComponentNames(storyExport: any): string[] {
// if (!storyExport) {
// return []
// }
//
// const exports = Object.getOwnPropertyNames(storyExport)
// const componentNames: string[] = []
//
// for (const key of exports) {
// if (key.match(/^[A-Z]/) && typeof storyExport[key] === 'function') {
// componentNames.push(key)
// }
// }
//
// return componentNames
// }
2 changes: 1 addition & 1 deletion packages/storylite/src/components/StoryFrame.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ type StoryFrameProps = {

export default function StoryFrame({ story, exportName }: StoryFrameProps) {
const iframeSrc =
story === undefined ? '/sandbox/dashboard' : `/sandbox/stories/${story}/${exportName || ''}`
story === undefined ? '/#/sandbox/dashboard' : `/#/sandbox/stories/${story}/${exportName || ''}`

return (
<iframe title="StoryFrame" id={ElementIds.Iframe} className={'StoryFrame'} src={iframeSrc} />
Expand Down
6 changes: 3 additions & 3 deletions packages/storylite/src/components/Toolbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ import OutlineAddon from './addons/OutlineAddon'
import ResponsiveAddon from './addons/ResponsiveAddon'
import SidebarAddon from './addons/SidebarAddon'

type AddonToolbarProps = { story?: string; storyMeta?: StoryMeta }
type AddonToolbarProps = { story?: string; exportName?: string; storyMeta?: StoryMeta }

export default function Toolbar({ story }: AddonToolbarProps) {
export default function Toolbar({ story, exportName }: AddonToolbarProps) {
const [searchParams] = useSearchParams()
const isStandalone = searchParams.has('standalone')

Expand All @@ -27,7 +27,7 @@ export default function Toolbar({ story }: AddonToolbarProps) {
</section>
<section>
<FullScreenAddon />
<OpenStoryAddon story={story} />
<OpenStoryAddon story={story} exportName={exportName} />
</section>
</div>
)
Expand Down
10 changes: 8 additions & 2 deletions packages/storylite/src/components/addons/OpenStoryAddon.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,21 @@ import { ExternalLink } from 'lucide-react'

import ToolbarBtn from '../ToolbarBtn'

export default function OpenStoryAddon({ story }: { story?: string }) {
export default function OpenStoryAddon({
story,
exportName,
}: {
story?: string
exportName?: string
}) {
if (!story) {
return null
}

return (
<ToolbarBtn
title={`Open story in a new tab`}
href={`/sandbox/stories/${story}?standalone`}
href={`/#/sandbox/stories/${story}${exportName ? '/' + exportName : ''}?standalone`}
target="_blank"
>
{<ExternalLink />}
Expand Down
13 changes: 12 additions & 1 deletion packages/storylite/src/components/addons/ResponsiveAddon.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ function ResponsiveAddon() {
const parentIframe = window.parent.document.getElementById(ElementIds.Iframe)

if (!parentIframe) {
throw new Error(`#${ElementIds.Iframe} iframe element not found on window.parent.document`)
console.warn(`#${ElementIds.Iframe} iframe element not found on window.parent.document`)

return
}

parentIframe.style.width = newWidth
Expand All @@ -41,6 +43,15 @@ function ResponsiveAddon() {
}
}, [addonValue])

if (!window.parent.document) {
return null
}

const parentIframe = window.parent.document.getElementById(ElementIds.Iframe)
if (!parentIframe) {
return null
}

return (
<ToolbarBtn
title={`Switch between full-width and 320px`}
Expand Down
5 changes: 5 additions & 0 deletions packages/storylite/src/components/addons/SidebarAddon.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ function SidebarAddon() {
return null
}

const parentIframe = window.parent.document.getElementById(ElementIds.Iframe)
if (!parentIframe) {
return null
}

const _handleToggle = () => {
const parentDoc = window.parent.document
const sidebar = parentDoc.getElementById(ElementIds.Sidebar)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import React from 'react'
import { useParams } from 'react-router-dom'

import { Story } from '@/components/Story'
Expand All @@ -8,7 +7,7 @@ import SandboxLayout from '../../../../layouts/SandboxLayout'
export default function StoryPage() {
const { story, export_name } = useParams()

if (!story || !export_name) {
if (!story) {
return <div>Error: story or export_name is empty</div>
}

Expand Down
17 changes: 17 additions & 0 deletions packages/storylite/src/pages/sandbox/stories/$story/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { useParams } from 'react-router-dom'

import { Story } from '@/components/Story'

import SandboxLayout from '../../../../layouts/SandboxLayout'

export default function StoryPage() {
const { story } = useParams()

if (!story) {
return <div>Error: story is empty</div>
}

return <Story story={story} />
}

export const Layout = SandboxLayout
4 changes: 1 addition & 3 deletions packages/storylite/src/plugins/storylitePlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,11 +89,9 @@ const storylitePlugin = (userConfig?: StoryLiteUserConfig): Plugin => {
return storyMap;
};
console.log('import.meta.glob', '/${storyliteConfig.stories}');
const storyMap = createStoryMap(import.meta.glob('/${storyliteConfig.stories}', {eager: true}));
console.dir(Array.from(storyMap.entries()));
console.log('Stories: ', Array.from(storyMap.keys()));
export default storyMap
`
Expand Down
22 changes: 12 additions & 10 deletions packages/storylite/src/router.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,11 @@
import React from 'react'
import {
ActionFunction,
createBrowserRouter,
LoaderFunction,
RouterProvider,
} from 'react-router-dom'
import { ActionFunction, createHashRouter, LoaderFunction, RouterProvider } from 'react-router-dom'

import MainLayout from './layouts/MainLayout'
import Error404, { Layout as ErrorLayout } from './pages/404'
import * as IndexPage from './pages/index'
import * as SandboxDashboardPage from './pages/sandbox/dashboard'
import * as SandboxStoryIndex from './pages/sandbox/stories/$story'
import * as SandboxExportedStory from './pages/sandbox/stories/$story/$export_name'
import * as ExportedStory from './pages/stories/$story/$export_name'

Expand All @@ -34,13 +30,14 @@ type RouteType = {
// const pages = import.meta.glob('./pages/**/*.tsx', { eager: true }) as Record<string, PageType>
const pages: Record<string, PageType> = {
'./pages/sandbox/stories/$story/$export_name.tsx': SandboxExportedStory,
'./pages/sandbox/stories/$story/index.tsx': SandboxStoryIndex,
'./pages/sandbox/dashboard.tsx': SandboxDashboardPage,
'./pages/stories/$story/$export_name.tsx': ExportedStory,
'./pages/index.tsx': IndexPage,
'./pages/404.tsx': {
default: Error404,
Layout: ErrorLayout,
},
'./pages/index.tsx': IndexPage,
}

const routes: RouteType[] = []
Expand All @@ -56,7 +53,7 @@ for (const path of Object.keys(pages)) {
}

const normalizedPathName = fileName.includes('$')
? fileName.replace(/\$/g, ':')
? fileName.replace(/\$/g, ':').replace(/\/index/, '')
: fileName.replace(/\/index/, '')

routes.push({
Expand All @@ -79,11 +76,16 @@ if (routes.length === 0) {
routes.push({
path: '*',
status: 404,
Component: Error404,
Component: () => <>Noooo</>,
Layout: ErrorLayout,
})

const router = createBrowserRouter(
console.log(
'Routes: ',
routes.map(({ path }) => path),
)

const router = createHashRouter(
routes.map(({ Component, Layout, ErrorBoundary, ...rest }) => ({
...rest,
element: Layout ? (
Expand Down

0 comments on commit 2893e37

Please sign in to comment.