@tenjuu99/blog 0.1.10 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/dir.js CHANGED
@@ -7,6 +7,7 @@ const pageDir = `${srcDir}/pages`
7
7
  const templateDir = `${srcDir}/template`
8
8
  const cssDir = `${srcDir}/css`
9
9
  const cacheDir = `${rootDir}/.cache`
10
+ const serverDir = `${srcDir}/server`
10
11
 
11
12
  export {
12
13
  rootDir,
@@ -16,4 +17,5 @@ export {
16
17
  templateDir,
17
18
  cssDir,
18
19
  cacheDir,
20
+ serverDir
19
21
  }
package/lib/pageData.js CHANGED
@@ -10,7 +10,7 @@ const parse = (content, name, ext) => {
10
10
  const regexp = new RegExp(/^(<!|-)--(?<variables>[\s\S]*?)--(-|>)/)
11
11
  const matched = content.match(regexp)
12
12
  const markdownReplaced = content.replace(regexp, '')
13
- const metaDataDefault = {
13
+ const metaDataDefault = Object.assign({
14
14
  name,
15
15
  title: name,
16
16
  url: `/${name}`,
@@ -22,14 +22,13 @@ const parse = (content, name, ext) => {
22
22
  lang: 'ja',
23
23
  site_name: config.site_name,
24
24
  url_base: config.url_base,
25
- gtag_id: config.gtag_id,
26
25
  markdown: markdownReplaced,
27
26
  relative_path: config.relative_path || '',
28
27
  template: 'default.html',
29
28
  ext: 'html',
30
29
  __output: `/${name}.html`,
31
30
  __filetype: ext,
32
- }
31
+ }, config)
33
32
  if (!matched) {
34
33
  return metaDataDefault
35
34
  }
package/lib/server.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import http from 'http'
2
2
  import url from 'url'
3
3
  import fs from 'node:fs'
4
- import { distDir } from './dir.js'
4
+ import { distDir, serverDir } from './dir.js'
5
5
  import { styleText } from 'node:util'
6
+ import handle from './tryServer.js'
6
7
 
7
8
  const contentType = (ext) => {
8
9
  switch (ext) {
@@ -31,11 +32,16 @@ const contentType = (ext) => {
31
32
  }
32
33
 
33
34
  const server = () => {
34
- return http.createServer((request, response) => {
35
+ return http.createServer(async (request, response) => {
36
+ request.setEncoding('utf8')
35
37
  const url = new URL(`http://${request.headers.host}${request.url}`)
36
38
  const isIndex = url.pathname.match(/(.+)?\/$/)
37
39
  let path = isIndex ? `${url.pathname}index.html` : decodeURIComponent(url.pathname)
38
40
  if (!path.includes('.')) {
41
+ const result = await handle(path, request, response)
42
+ if (result) {
43
+ return
44
+ }
39
45
  path += '.html'
40
46
  }
41
47
  if (!fs.existsSync(`${distDir}${path}`)) {
@@ -0,0 +1,58 @@
1
+ import http from 'http'
2
+ import { distDir, serverDir } from './dir.js'
3
+ import fs from 'node:fs'
4
+ import { styleText } from 'node:util'
5
+
6
+ let handlersAlreadyRegistered = false
7
+ const registeredHandlers = {}
8
+ const handlers = async (path) => {
9
+ if (handlersAlreadyRegistered) {
10
+ return registeredHandlers[path]
11
+ }
12
+ const serverFiles = fs.readdirSync(serverDir)
13
+ const loaded = await Promise.all(serverFiles.map(file => import(`${serverDir}/${file}`)))
14
+ loaded.forEach(s => registeredHandlers[s.path] = s)
15
+ handlersAlreadyRegistered = true
16
+ return registeredHandlers[path]
17
+ }
18
+
19
+ /**
20
+ * @param {string} path
21
+ * @param {http.IncomingMessage} req
22
+ * @param {http.ServerResponse} res
23
+ */
24
+ const tryServer = async (path, req, res) => {
25
+ const handler = await handlers(path)
26
+ const method = req.method.toLowerCase()
27
+ if (handler && handler[method]) {
28
+ console.log(styleText('blue', `[server ${method.toUpperCase()} ${path}]`))
29
+ try {
30
+ const response = await handler[method](req, res)
31
+ if (response) {
32
+ return response
33
+ }
34
+ } catch (e) {
35
+ console.log(e)
36
+ }
37
+ }
38
+ }
39
+
40
+ /**
41
+ * @param {string} path
42
+ * @param {http.IncomingMessage} request
43
+ * @param {http.ServerResponse} response
44
+ */
45
+ const getResponse = async (path , request, response) => {
46
+ const url = new URL(`http://${request.headers.host}${request.url}`)
47
+ const res = await tryServer(url.pathname, request, response)
48
+ if (res) {
49
+ if (res === true) {
50
+ return true
51
+ }
52
+ const { status, contentType, body } = res
53
+ response.writeHead(status, {'content-type': contentType })
54
+ return response.end(body)
55
+ }
56
+ }
57
+
58
+ export default getResponse
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tenjuu99/blog",
3
- "version": "0.1.10",
3
+ "version": "0.2.1",
4
4
  "description": "blog template",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -7,6 +7,7 @@
7
7
  }
8
8
 
9
9
  body {
10
+ background: #fff;
10
11
  display: flex;
11
12
  flex-direction: column;
12
13
  min-height: 100dvh !important;
@@ -0,0 +1,3 @@
1
+ ---
2
+ template: editor.html
3
+ ---
@@ -0,0 +1,38 @@
1
+ import { IncomingMessage, ServerResponse } from 'http'
2
+ import fs from 'node:fs/promises'
3
+ import { styleText } from 'node:util'
4
+
5
+ const config = (await import('../../lib/config.js')).default
6
+ const dir = (await import('../../lib/dir.js'))
7
+
8
+ export const path = '/editor'
9
+
10
+ /**
11
+ * @param {IncomingMessage} req
12
+ * @param {ServerResponse} res
13
+ */
14
+ export const post = async (req, res) => {
15
+ const chunks = []
16
+ req
17
+ .on('data', (chunk) => chunks.push(chunk))
18
+ .on('end', async () => {
19
+ const json = JSON.parse(chunks.join())
20
+ const file = json.inputFileName ? json.inputFileName : json.selectDataFile
21
+ if (!file) {
22
+ res.writeHead(400, { 'content-type': 'application/json' })
23
+ res.end(JSON.stringify({
24
+ 'message': 'ファイル名がありません'
25
+ }))
26
+ return
27
+ }
28
+ await fs.writeFile(`${dir.pageDir}/${file}`, json.content)
29
+ console.log(styleText('blue', '[editor/post] finished'))
30
+
31
+ const href = file.split('.')[0]
32
+ res.writeHead(200, { 'content-type': 'application/json' })
33
+ res.end(JSON.stringify({
34
+ 'href': `/${href}`
35
+ }))
36
+ })
37
+ return true
38
+ }
@@ -0,0 +1,29 @@
1
+ import { IncomingMessage, ServerResponse } from 'http'
2
+ import fs from 'node:fs'
3
+
4
+ const config = (await import('../../lib/config.js')).default
5
+ const pageDir = (await import('../../lib/dir.js')).pageDir
6
+
7
+ export const path = '/get_editor_target'
8
+
9
+ /**
10
+ * @param {IncomingMessage} req
11
+ * @param {ServerResponse} res
12
+ */
13
+ export const get = async (req, res) => {
14
+ const url = new URL(`${config.url_base}${req.url}`)
15
+ const target = url.searchParams.get('md')
16
+ if (!target) {
17
+ return
18
+ }
19
+ const file = `${pageDir}/${target}`
20
+ if (!fs.existsSync(`${file}`)) {
21
+ return false
22
+ }
23
+ const f = fs.readFileSync(`${file}`, 'utf8')
24
+ return {
25
+ status: 200,
26
+ contentType: 'application/json',
27
+ body: JSON.stringify({ content: f, filename: target }),
28
+ }
29
+ }
@@ -0,0 +1,28 @@
1
+ import { IncomingMessage, ServerResponse } from 'http'
2
+ import { styleText } from 'node:util'
3
+
4
+ const render = (await import('../../lib/render.js')).default
5
+ const makePageData = (await import('../../lib/pageData.js')).default
6
+
7
+ export const path = '/preview'
8
+
9
+ /**
10
+ * @param {IncomingMessage} req
11
+ * @param {ServerResponse} res
12
+ */
13
+ export const post = async (req, res) => {
14
+ const chunks = []
15
+ req
16
+ .on('data', (chunk) => chunks.push(chunk))
17
+ .on('end', async () => {
18
+ const json = JSON.parse(chunks.join())
19
+ const filename = json.inputFileName ? json.inputFileName : json.selectDataFile
20
+ const pageData = makePageData(filename, json.content)
21
+ const rendered = await render(pageData.template, pageData)
22
+ res.writeHead(200, { 'content-type': 'application/json' })
23
+ res.end(JSON.stringify({
24
+ 'preview': rendered
25
+ }))
26
+ })
27
+ return true
28
+ }
@@ -43,6 +43,11 @@
43
43
  {/if}
44
44
  {{MARKDOWN}}
45
45
  </article>
46
+ {if editor}
47
+ <div class="container">
48
+ <a href="/editor?md={{name}}.{{__filetype}}">編集する</a>
49
+ </div>
50
+ {/if}
46
51
 
47
52
  {include('template/prevNext.html')}
48
53
  </main>
@@ -0,0 +1,206 @@
1
+ <!DOCTYPE html>
2
+ <html lang="ja">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>{{SITE_NAME}}</title>
7
+ {include('template/css.html')}
8
+ <style>
9
+ body {
10
+ background: #fafafa;
11
+ }
12
+ main {
13
+ width: 90%;
14
+ padding: 15px;
15
+ height: 100%;
16
+ margin: 0 auto;
17
+ }
18
+ .textareaAndPreview {
19
+ display: flex;
20
+ margin: 10px 0;
21
+ border: 1px solid #666;
22
+ border-radius: 5px;
23
+ }
24
+ .textareaAndPreview>* {
25
+ flex-basis: 50%;
26
+ height: 80vh;
27
+ }
28
+ .editor {
29
+ display: flex;
30
+ flex-direction: column;
31
+ padding: 15px 0;
32
+ justify-content:center;
33
+ }
34
+ #editorTextArea {
35
+ resize: none;
36
+ background: #cccccc;
37
+ color: #333;
38
+ padding: 5px;
39
+ border-radius: 5px 0 0 5px;
40
+ border: 0;
41
+ }
42
+ form select {
43
+ padding: 5px;
44
+ margin-top: 5px;
45
+ border-radius: 5px;
46
+ }
47
+ #previewContent {
48
+ flex-basis: 100%;
49
+ height: 100%;
50
+ min-height: 90%;
51
+ display: block;
52
+ width: 100%;
53
+ }
54
+ #previewContent iframe {
55
+ width: 100%;
56
+ height: 100%;
57
+ border: none;
58
+ border-radius: 0 5px 5px 0;
59
+ pointer-events: none;
60
+ }
61
+ @media screen and (max-width: 600px) {
62
+ main {
63
+ width: 100%;
64
+ display: block;
65
+ }
66
+ .editor {
67
+ padding: 15px 0;
68
+ }
69
+ .preview {
70
+ display: none;
71
+ }
72
+ #editorTextArea {
73
+ flex-basis: 100%;
74
+ }
75
+ }
76
+ </style>
77
+
78
+ <link href="https://cdn.jsdelivr.net/npm/prismjs@v1.x/themes/prism.css" rel="stylesheet" />
79
+
80
+ <script src="https://cdn.jsdelivr.net/npm/prismjs@v1.x/components/prism-core.min.js"></script>
81
+ <script src="https://cdn.jsdelivr.net/npm/prismjs@v1.x/plugins/autoloader/prism-autoloader.min.js"></script>
82
+ </head>
83
+ <body>
84
+ <script>
85
+ const sleep = waitTime => new Promise( resolve => setTimeout(resolve, waitTime) );
86
+
87
+ const fetchData = (target) => {
88
+ return fetch(`/get_editor_target?md=${target}`)
89
+ .then(async res => {
90
+ const json = await res.json()
91
+ return json
92
+ })
93
+ }
94
+ const onloadFunction = async (e) => {
95
+ const form = document.querySelector('#editor')
96
+ const textarea = form.querySelector('#editorTextArea')
97
+ const select = form.querySelector('#selectDataFile')
98
+ const inputFileName = form.querySelector('#inputFileName')
99
+ const preview = document.querySelector('#previewContent')
100
+ const url = new URL(location)
101
+ const target = url.searchParams.get('md')
102
+ if (target) {
103
+ fetchData(target).then(json => {
104
+ textarea.value = json.content
105
+ select.value = json.filename
106
+ inputFileName.value = json.filename
107
+ inputFileName.setAttribute('disabled', true)
108
+ submit('/preview', form)
109
+ })
110
+ }
111
+ select.addEventListener('change', async (event) => {
112
+ if (select.value) {
113
+ const json = await fetchData(select.value)
114
+ textarea.value = json.content
115
+ inputFileName.value = json.filename
116
+ inputFileName.setAttribute('disabled', true)
117
+ url.searchParams.set('md', select.value)
118
+ submit('/preview', form)
119
+ } else {
120
+ inputFileName.value = ""
121
+ inputFileName.removeAttribute('disabled')
122
+ textarea.value = ''
123
+ url.searchParams.set('md', "")
124
+ const iframe = preview.querySelector('iframe')
125
+ if (iframe) {
126
+ iframe.srcdoc = ''
127
+ }
128
+ }
129
+ history.pushState({}, "", url)
130
+ })
131
+
132
+ const submit = (fetchUrl, form) => {
133
+ const formData = new FormData(form)
134
+ const obj = {}
135
+ formData.forEach((v, k) => {
136
+ obj[k] = v
137
+ })
138
+ fetch(fetchUrl, {
139
+ method: 'post',
140
+ body: JSON.stringify(obj)
141
+ }).then(async response => {
142
+ const json = await response.json()
143
+ if (!response.ok) {
144
+ alert(json.message)
145
+ return
146
+ }
147
+ if (json.href) {
148
+ await sleep(300)
149
+ location.href = json.href
150
+ }
151
+ if (json.preview) {
152
+ const iframe = document.createElement('iframe')
153
+ iframe.setAttribute('srcdoc', json.preview)
154
+ iframe.setAttribute('sandbox', '')
155
+ const old = preview.querySelector('iframe')
156
+ if (!old) {
157
+ preview.appendChild(iframe)
158
+ }
159
+ old.setAttribute('srcdoc', json.preview)
160
+ }
161
+ }).catch(e => {
162
+ console.log(e.message)
163
+ })
164
+ }
165
+ form.addEventListener('submit', (event) => {
166
+ event.preventDefault()
167
+ const fetchUrl = event.submitter.dataset.url
168
+ submit(fetchUrl, event.target)
169
+ })
170
+ }
171
+
172
+ document.addEventListener('DOMContentLoaded', (event) => {
173
+ onloadFunction(event)
174
+ })
175
+ </script>
176
+ <main>
177
+ <form action="/editor" class="editor" method="post" id="editor">
178
+ <input id="inputFileName" name="inputFileName" type="text" value="" placeholder="sample.md">
179
+ <select id="selectDataFile" name="selectDataFile">
180
+ <option value="">新規作成</option>
181
+ <script type="ssg">
182
+ return helper.readIndex().map(p => {
183
+ return `<option value="${p.name}.${p.__filetype}">${p.url}.${p.__filetype}</option>`
184
+ }).join("\n")
185
+ </script>
186
+ </select>
187
+ <div class="textareaAndPreview">
188
+ <textarea id="editorTextArea" name="content" cols="30" rows="10">
189
+ # H1
190
+
191
+ ここにマークダウンを入力してください。
192
+ </textarea>
193
+ <div class="preview">
194
+ <div id="previewContent"></div>
195
+ </div>
196
+ </div>
197
+ <input type="hidden" name="token" value="{{TOKEN}}">
198
+ <div>
199
+ <input type="submit" value="preview" data-url="/preview">
200
+ <input type="submit" value="編集" data-url="/editor">
201
+ <a href="/">戻る</a>
202
+ </div>
203
+ </form>
204
+ </main>
205
+ </body>
206
+ </html>