better code: better component signature
Massimo Melina committed
Jun 5, 2024 at 09:44 UTC
e7737575e3a07f2988775c1e0040279c426465de
2 files changed
+9
-9
frontend/src/components.ts
+2
-2
@@ -71,12 +71,12 @@ export function CustomCode({ name, children, ...props }: { name: string, childre
71
props.def = children // not using 'default' because user can have unexpected error destructuring object
72
const ret = onlyTruthy(hfsEvent(name, props)
73
.map((x, key) => isValidElement(x) ? h(Fragment, { key }, x)
74
- : x === 0 || x && isPrimitive(x) ? h(Html, { key, code: String(x) })
74
+ : x === 0 || x && isPrimitive(x) ? h(Html, { key }, String(x))
75
: _.isArray(x) ? h(Fragment, { key }, ...x)
76
: null))
77
const html = getHFS().customHtml?.[name]
78
if (html?.trim?.())
79
- ret.push(h(Html, { key: 'x', code: html }))
79
+ ret.push(h(Html, { key: 'x' }, html))
80
return ret
81
}, [name, children, ...props ? Object.values(props) : []])
82
return result.length || !children ? h(Fragment, {}, result) : children
shared/md.ts
+7
-7
@@ -1,6 +1,6 @@
1
// This file is part of HFS - Copyright 2021-2023, Massimo Melina <a@rejetto.com> - License https://www.gnu.org/licenses/gpl-3.0.txt
2
3
-import { createElement as h, Fragment, HTMLAttributes, ReactNode } from 'react'
3
+import { createElement as h, Fragment, HTMLAttributes, ReactNode, useMemo } from 'react'
4
5
export const MD_TAGS = {
6
a: 'a',
@@ -9,6 +9,7 @@ export const MD_TAGS = {
9
'**': 'b',
10
}
11
type OnText = (s: string) => ReactNode
12
+// md-inspired formatting, very simplified
13
export function md(text: string | TemplateStringsArray, { linkTarget='_blank', onText=(x=>x) as OnText }={}) {
14
if (typeof text !== 'string')
15
text = text[0]
@@ -16,7 +17,7 @@ export function md(text: string | TemplateStringsArray, { linkTarget='_blank', o
17
m[4] ? h(MD_TAGS.a, { href: m[5], target: linkTarget }, onText(m[4]))
18
: m[3] ? h('br')
19
: m[1] ? h((MD_TAGS as any)[ m[1] ] || Fragment, {}, onText(m[2]))
19
- : h(Html, { code: m[6] }),
20
+ : h(Html, {}, m[6]),
21
onText)
22
}
23
@@ -33,9 +34,8 @@ export function replaceStringToReact(text: string, re: RegExp, cb: (match: RegEx
34
return h(Fragment, {}, ...res, onText(text.slice(last, Infinity)))
35
}
36
36
-export function Html({ code, ...rest }: { code:string } & HTMLAttributes<any>) {
37
- return !code ? null : h('span', { ...rest, ref(x) {
38
- if (x)
39
- x.replaceChildren(document.createRange().createContextualFragment(code))
40
- } })
37
+export function Html({ children, ...rest }: { children?: string } & HTMLAttributes<any>) {
38
+ return useMemo(() => !children ? null
39
+ : h('span', { ...rest, ref: x => x && x.replaceChildren(document.createRange().createContextualFragment(children)) }),
40
+ [children])
41
}