Skip to content

Commit

Permalink
0.0.10 新增预览功能
Browse files Browse the repository at this point in the history
  • Loading branch information
2234839 committed Jan 3, 2024
1 parent af72c80 commit 4ad4f99
Show file tree
Hide file tree
Showing 12 changed files with 271 additions and 111 deletions.
5 changes: 3 additions & 2 deletions apps/frontend/package.json
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
{
"name": "frontend",
"private": true,
"version": "0.0.9",
"version": "0.0.10",
"type": "module",
"scripts": {
"dev": "vite",
"cli": "tsx ./src/cli.ts",
"cli_watch": "tsx watch ./src/cli.ts",
"build": "vite build",
"build": "vite build && pnpm build_lib",
"build_lib": "vite build --config vite.sw.config.ts",
"generate_dependency_graph": "depcruise src --include-only '^src' --output-type dot > ./assets/dep.dot",
"preview": "vite preview"
},
Expand Down
85 changes: 85 additions & 0 deletions apps/frontend/src/core/hono_server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { Hono } from 'hono'
import { currentConfig } from './config.ts'
import { get_doc_by_hpath } from './cache.ts'
import { htmlTemplate } from './htmlTemplate.ts'
import { renderHTML } from './render.ts'

export function createHonoApp() {
const app = new Hono()
app.use(async (_, next) => {
console.log('请求到达')
try {
await next()
} catch (error) {
console.log(error)
}
})
app.get('/', (c) => c.redirect('/index.html'))
app.get('/assets/*', async (c) => {
// TODO 处于安全考虑应该防范 file 跳出 assets
const file = c.req.path
const r = await fetch(`${currentConfig.value.apiPrefix}${file}`, {
headers: {
Authorization: `Token ${currentConfig.value.authorized}`,
},
method: 'GET',
})

if (!r.body) {
return c.text('Not Found', 404, { 'Content-Type': 'text/plain' })
}
return c.stream(
async (stream) => {
const reader = r.body!.getReader()
console.log(file)
while (true) {
const r = await reader.read()
if (r.done) {
stream.close()
break
} else {
stream.write(r.value)
}
}
},
200,
{
'content-type': r.headers.get('content-type')!,
},
)
})
app.get('*', async (c) => {
const path = decodeURIComponent(c.req.path)

const r = await renderHtmlByPath(path).catch((err) => {
console.log('err')

return err.message
})

if (r instanceof Error) throw r
return c.html(r)
})
return app
}

async function renderHtmlByPath(path: string): Promise<string | Error> {
const hpath = decodeURIComponent(path)
.replace(/\#(.*)?$/, '')
.replace(/\.html$/, '')
console.log(currentConfig.value)

const doc = await get_doc_by_hpath(hpath)

return await htmlTemplate(
{
title: doc.Properties?.title || '',
htmlContent: await renderHTML(doc),
level: path.split('/').length - 1 /** 最开头有一个 / */,
},
{
...currentConfig.value.cdn,
embedCode: currentConfig.value.embedCode,
},
)
}
51 changes: 51 additions & 0 deletions apps/frontend/src/pages/preview.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { defineComponent, ref, watchEffect } from 'vue'
import { useRoute } from 'vue-router'
import { configs } from '~/core/config.ts'
const preview = defineComponent({
setup() {
const route = useRoute()
const path = route.params.path as string
const iframeHref = ref<string | null>(null)
// firefox 不兼容
navigator.serviceWorker
.register(import.meta.env.PROD ? 'sw.js' : '/sw.ts', {
scope: '/',
})
.then(async (_r) => {
const configStatus = await (
await fetch('/preview/page/configs', {
body: JSON.stringify(configs),
method: 'POST',
mode: 'cors',
credentials: 'omit',
})
).json()
console.log('configStatus', configStatus)
iframeHref.value = `/preview/page/${path}`
})
.catch((e) => {
console.log(e)
})
const myElement = ref<HTMLIFrameElement | null>(null)
watchEffect(async () => {
if (!myElement.value) return
// const honoApp = createHonoApp()

// const r = honoApp.request(path) as Promise<Response>
// const html = await (await r).text()
// myElement.value.contentDocument!.body.innerHTML = html
})

return () => (
<>
<h4 style="color:#3c">预览界面</h4>
<iframe
ref={myElement}
src={iframeHref.value ?? ''}
style="width:100%;height:700px;border:none;"
></iframe>
</>
)
},
})
export default preview
12 changes: 10 additions & 2 deletions apps/frontend/src/pages/steps/step2_preview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,19 @@ export default defineComponent({
title={currentConfig.value.notebook.name ?? '未选中'}
description="请先选择一个笔记本"
>
{'可点击文件名预览效果'}
<Data_loading p={this.toRef(this.filetree)}>
<NScrollbar style="max-height: 120px" trigger="none">
<NScrollbar style="max-height: 220px" trigger="none">
<NList hoverable>
{this.filetree.data.files.map((item) => (
<NListItem>{item.name}</NListItem>
<NListItem>
<a
target="_blank"
href={`/#/preview/${item.name.replace(/.sy$/, '')}`}
>
{item.name}
</a>
</NListItem>
))}
</NList>
</NScrollbar>
Expand Down
2 changes: 1 addition & 1 deletion apps/frontend/src/pages/steps/steps.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export default defineComponent({
return () => (
<>
<Config_tab></Config_tab>
<NSteps vertical current={current.value} status={'process'}>
<NSteps vertical current={current.value} status={'process'} >
<NStep title="鉴权配置">
http apiPrefix:
<NInput
Expand Down
76 changes: 2 additions & 74 deletions apps/frontend/src/server.ts
Original file line number Diff line number Diff line change
@@ -1,62 +1,8 @@
import { serve } from '@hono/node-server'
import { Hono } from 'hono'
import { currentConfig } from './core/config.ts'
import { get_doc_by_hpath } from './core/cache.ts'
import { htmlTemplate } from './core/htmlTemplate.ts'
import { renderHTML } from './core/render.ts'
import { createHonoApp } from './core/hono_server.ts'

export function server(config = { port: 80, hostname: '0.0.0.0' }) {
const app = new Hono()
app.use(async (_, next) => {
try {
await next()
} catch (error) {
console.log(error)
}
})
app.get('/', (c) => c.redirect('/index.html'))
app.get('/assets/*', async (c) => {
// TODO 处于安全考虑应该防范 file 跳出 assets
const file = c.req.path
const r = await fetch(`${currentConfig.value.apiPrefix}${file}`, {
headers: {
Authorization: `Token ${currentConfig.value.authorized}`,
},
method: 'GET',
})

if (!r.body) {
return c.text('Not Found', 404, { 'Content-Type': 'text/plain' })
}
return c.stream(
async (stream) => {
const reader = r.body!.getReader()
console.log(file)
while (true) {
const r = await reader.read()
if (r.done) {
stream.close()
break
} else {
stream.write(r.value)
}
}
},
200,
{
'content-type': r.headers.get('content-type')!,
},
)
})
app.get('*', async (c) => {
const path = c.req.path
const r = await renderHtmlByPath(path).catch((err) => {
return err.message
})

if (r instanceof Error) throw r
return c.html(r)
})
const app = createHonoApp()
return new Promise((resolve, _reject) => {
serve(
{
Expand All @@ -71,21 +17,3 @@ export function server(config = { port: 80, hostname: '0.0.0.0' }) {
)
})
}

async function renderHtmlByPath(path: string): Promise<string | Error> {
const hpath = decodeURIComponent(path).replace(/\.html$/, '')

const doc = await get_doc_by_hpath(hpath)

return await htmlTemplate(
{
title: doc.Properties?.title || '',
htmlContent: await renderHTML(doc),
level: path.split('/').length - 1 /** 最开头有一个 / */,
},
{
...currentConfig.value.cdn,
embedCode: currentConfig.value.embedCode,
},
)
}
8 changes: 5 additions & 3 deletions apps/frontend/src/webpage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@ import { createApp } from 'vue'
import { createRouter, createWebHashHistory } from 'vue-router'
import App from '~/pages/App.tsx'
import steps from '~/pages/steps/steps.tsx'

const routes = [{ path: '/', component: steps }]
import preview from '~/pages/preview.tsx'

const router = createRouter({
history: createWebHashHistory(),
routes,
routes: [
{ path: '/', component: steps },
{ path: '/preview/:path', component: preview },
],
})

const app = createApp(App)
Expand Down
48 changes: 48 additions & 0 deletions apps/frontend/sw.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { storeDep } from '~/core/dependency.ts'
import '~/core/render.api.dep'
import { createHonoApp } from './src/core/hono_server.ts'
import { Hono } from 'hono'
import { loadConfigFile } from '~/core/config.ts'
import { setCache } from '~/core/cache.ts'
// 这个文件放在最外层是为了方便开发时调试,因为 sw 的 scop 规定

storeDep.getItem = getItem
storeDep.setItem = setItem
setCache(false)

export function setItem(key: string, _value: string) {
console.log(key)
}
export function getItem(_key: string): string | undefined {
return
}

const renderServer = createHonoApp()
const app = new Hono()

app.use('*', async (c, next) => {
await next()
})
// 从主线程接收配置文件
app.post('/preview/page/configs', async (c) => {
const r = await c.req.json()
console.log('接收配置文件完毕', r)
loadConfigFile(r)
return c.json({ ok: true })
})
app.get('/preview/page/*', async (c) => {
const url = c.req.path.substring('/preview/page'.length)
// 转发到渲染服务器
return renderServer.request(url)
})
app.notFound(async (c) => {
// 请求转发给真实服务器
return fetch(c.req.raw)
})
//
app.fire()
self.addEventListener('install', (event) => {
console.log('Service Worker installed:', event)
//@ts-ignore 跳过等待激活阶段,立即激活新的Service Worker
// self.skipWaiting()
})
2 changes: 1 addition & 1 deletion apps/frontend/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,5 +37,5 @@
"src/**/*.vue",
"public/dev/http.js",
"store/api_test.ts"
],
, "sw.ts" ],
}
25 changes: 0 additions & 25 deletions apps/frontend/vite.components.config.ts

This file was deleted.

Loading

0 comments on commit 4ad4f99

Please sign in to comment.