64 lines
2.3 KiB
TypeScript
64 lines
2.3 KiB
TypeScript
import type { Frame, WObject } from '@/lib/wysiwyg/schema'
|
|
|
|
export type Exported = { html: string; css: string; js: string }
|
|
|
|
function esc(s: string) {
|
|
return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')
|
|
}
|
|
|
|
function isImage(o: WObject): o is Extract<WObject, { type: 'image' }> { return o.type === 'image' }
|
|
function isText(o: WObject): o is Extract<WObject, { type: 'text' }> { return o.type === 'text' }
|
|
function isButton(o: WObject): o is Extract<WObject, { type: 'button' }> { return o.type === 'button' }
|
|
|
|
function renderObject(o: WObject): { html: string; css: string } {
|
|
const baseCss = `#${o.id}{position:absolute;left:${o.x}px;top:${o.y}px;width:${o.width}px;height:${o.height}px;transform:rotate(${o.rotate}deg)}`
|
|
if (isImage(o)) {
|
|
const html = `<img id="${o.id}" src="${esc(o.props.src)}" alt="${esc(o.props.alt || '')}" />`
|
|
return { html, css: baseCss }
|
|
}
|
|
if (isText(o)) {
|
|
const html = `<p id="${o.id}">${esc(o.props.text)}</p>`
|
|
return { html, css: baseCss + `;font-size:${o.props.fontSize}px;color:${o.props.color}` }
|
|
}
|
|
// button minimal
|
|
const label = isButton(o) ? o.props.label : 'Button'
|
|
const href = isButton(o) ? (o.props.href || '#') : '#'
|
|
const html = `<a id="${o.id}" href="${esc(href)}">${esc(label)}</a>`
|
|
return { html, css: baseCss }
|
|
}
|
|
|
|
export function exportFrame(frame: Frame): Exported {
|
|
const piecesHtml: string[] = []
|
|
const piecesCss: string[] = []
|
|
for (const layer of frame.layers) {
|
|
if (!layer.visible) continue
|
|
for (const o of layer.objects) {
|
|
const r = renderObject(o)
|
|
piecesHtml.push(r.html)
|
|
piecesCss.push(r.css)
|
|
}
|
|
}
|
|
const inner = `<div class="frame-scale"><div class="frame">${piecesHtml.join('')}</div></div>`
|
|
const css = [
|
|
`.frame{position:relative;width:${frame.width}px;height:${frame.height}px;background:${frame.background}}`,
|
|
`.frame-scale{transform-origin:0 0}`,
|
|
...piecesCss,
|
|
].join('\n')
|
|
const html = [
|
|
'<!doctype html>',
|
|
'<html lang="en">',
|
|
'<head>',
|
|
'<meta charset="utf-8" />',
|
|
'<meta name="viewport" content="width=device-width,initial-scale=1" />',
|
|
'<title>WYSIWYG Frame</title>',
|
|
'<link rel="stylesheet" href="styles.css" />',
|
|
'</head>',
|
|
'<body>',
|
|
inner,
|
|
'<script src="app.js"></script>',
|
|
'</body>',
|
|
'</html>',
|
|
].join('')
|
|
return { html, css, js: '' }
|
|
}
|