Skip to content

Commit e504f45

Browse files
committed
[orga-build] add support to relative path to images
1 parent 6e178ee commit e504f45

File tree

4 files changed

+52
-13
lines changed

4 files changed

+52
-13
lines changed

.changeset/evil-numbers-send.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'orga-build': patch
3+
---
4+
5+
you can refer to image using relative path now

packages/orga-build/lib/esbuild/build.js

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import assert from 'node:assert'
88
import { DefaultLayout, $, match } from '../util.js'
99
import rawLoader from './raw-loader.js'
1010
import resolveReact from './resolve-react.js'
11+
import { visitParents } from 'unist-util-visit-parents'
1112

1213
/**
1314
* @param {import('../config.js').Config} options
@@ -80,8 +81,31 @@ export async function build({ outDir = 'dir', preBuild = [], postBuild = [] }) {
8081
}
8182
return link.path.value
8283
}
83-
}
84-
// reorgPlugins: [reorgLinks]
84+
},
85+
rehypePlugins: [
86+
() => (tree) => {
87+
/** @type {Record<string, string>} */
88+
const imports = {}
89+
visitParents(tree, { tagName: 'img' }, (node) => {
90+
node.type = 'jsx'
91+
const { src, target } = node.properties
92+
if (src.startsWith('http')) {
93+
return
94+
}
95+
const name = (imports[src] ??= `asset_${genId()}`)
96+
node.value = `<img src={${name}} target='${target}'/>`
97+
console.log(node)
98+
})
99+
100+
for (const [src, name] of Object.entries(imports)) {
101+
tree.children.unshift({
102+
type: 'jsx',
103+
value: `import ${name} from '${src}'`,
104+
children: []
105+
})
106+
}
107+
}
108+
]
85109
}),
86110
rawLoader,
87111
resolveReact
@@ -256,3 +280,9 @@ async function walk(dirPath, callback) {
256280
export async function clean(dir) {
257281
await fs.rm(dir, { recursive: true })
258282
}
283+
284+
function genId(length = 8) {
285+
const array = new Uint8Array(length)
286+
crypto.getRandomValues(array)
287+
return Array.from(array, (byte) => (byte % 36).toString(36)).join('')
288+
}

packages/orga-build/package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,8 @@
3232
"react": "^19.0.0",
3333
"react-dom": "^19.0.0",
3434
"rehype-katex": "^7.0.1",
35-
"serve-handler": "^6.1.6"
35+
"serve-handler": "^6.1.6",
36+
"unist-util-visit-parents": "^6.0.1"
3637
},
3738
"devDependencies": {
3839
"@orgajs/orgx": "workspace:^",

pnpm-lock.yaml

Lines changed: 13 additions & 10 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)