import { polygonHull } from 'd3';
import { num, text, choice, color, assert, parseJSON, numeric, source, pixels, canvas, png, json, plain, zip, svgDoc, svgResults, label, esc, colors } from './common.js';
const html = (title, body, css) => `<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; base-uri 'none'; form-action 'none'"><title>${esc(title)}</title><link rel="stylesheet" href="layout.css"><style>body{margin:24px;font:16px/1.6 system-ui;color:#203d32}*{box-sizing:border-box}${css}</style></head><body>${body}</body></html>`;
const preview = (body, height = 420) => svgResults(svgDoc(body, 720, height, '布局预览'), 'layout');
export const grid_layout = /*#__PURE__*/ (() => ({ fields: [text('columns', '各列比例(逗号分隔)', '1,2,1'), num('rows', '行数', 2, 1, 8), num('gap', '间距(px)', 16, 0, 48)], async run({ values: v }) {
  const columns = v.columns.split(',').map((n) => numeric(n)); assert(columns.length >= 1 && columns.length <= 8 && columns.every((n) => n >= .1 && n <= 20), '列数1–8,每列比例0.1–20。'); const total = columns.reduce((a, b) => a + b, 0), available = 680 - (columns.length - 1) * v.gap; assert(available > columns.length * 24, '间距太大。');
  let body = '', items = ''; for (let row = 0; row < v.rows; row++) { let x = 20; for (let col = 0; col < columns.length; col++) { const w = available * columns[col] / total, i = row * columns.length + col; body += `<rect x="${x}" y="${20 + row * (80 + v.gap)}" width="${w}" height="80" rx="6" fill="${colors[col]}"/>${label(i + 1, x + w / 2, 66 + row * (80 + v.gap), 'text-anchor="middle" fill="white"')}`; items += `<div class="item">${i + 1}</div>`; x += w + v.gap; } }
  const css = `.layout { display:grid; grid-template-columns:${columns.map((n) => n + 'fr').join(' ')}; gap:${v.gap}px; }\n.item { min-width:0; min-height:80px; padding:20px; background:#167d68; color:white; border-radius:6px; }\n@media(max-width:480px) { .layout { grid-template-columns:1fr; } }\n`;
  return [...await preview(body, 40 + v.rows * 80 + (v.rows - 1) * v.gap), plain(css, 'layout.css', 'text/css'), plain(html('CSS网格布局', `<main class="layout">${items}</main>`, ''), 'index.html', 'text/html')];
} }))();
export const flex_layout = /*#__PURE__*/ (() => ({ fields: [choice('direction', '方向', [['row', '横向'], ['column', '纵向']]), choice('justify', '主轴对齐', [['flex-start', '起点'], ['center', '居中'], ['space-between', '两端']]), num('items', '块数', 4, 1, 6), num('gap', '块间距', 16, 0, 32)], async run({ values: v }) {
  const row = v.direction === 'row', item = row ? 88 : 48, space = row ? 680 : 380, used = v.items * item + (v.items - 1) * v.gap; assert(used <= space, '项目和间距超出主轴空间,请减少块数或间距。'); const offset = v.justify === 'center' ? (space - used) / 2 : 0, gap = v.justify === 'space-between' && v.items > 1 ? (space - v.items * item) / (v.items - 1) : v.gap;
  const body = Array.from({ length: v.items }, (_, i) => { const x = row ? 20 + offset + i * (item + gap) : 220, y = row ? 160 : 20 + offset + i * (item + gap), w = row ? item : 280, h = row ? 100 : item; return `<rect x="${x}" y="${y}" width="${w}" height="${h}" rx="6" fill="${colors[i]}"/>${label(i + 1, x + w / 2, y + h / 2 + 5, 'text-anchor="middle" fill="white"')}`; }).join('');
  const css = `.layout { display:flex; flex-direction:${v.direction}; justify-content:${v.justify}; align-items:center; gap:${v.gap}px; width:min(680px,100%); min-height:380px; }\n.item { flex:none; width:${row ? 88 : 280}px; max-width:100%; height:${row ? 100 : 48}px; display:grid; place-items:center; background:#167d68; color:white; border-radius:6px; }\n@media(max-width:640px) { .layout { flex-direction:column; } }\n`;
  return [...await preview(body), plain(css, 'layout.css', 'text/css'), plain(html('Flex布局', `<main class="layout">${Array.from({ length: v.items }, (_, i) => `<div class="item">${i + 1}</div>`).join('')}</main>`, ''), 'index.html', 'text/html')];
} }))();
export const responsive_image = /*#__PURE__*/ (() => ({ fields: [text('widths', '目标宽度(逗号分隔,不放大)', '320,640,1280')], async run({ images, values: v }) {
  const input = source(images), requested = [...new Set(v.widths.split(',').map((n) => numeric(n)))].sort((a, b) => a - b); assert(requested.length >= 1 && requested.length <= 8 && requested.every((w) => Number.isInteger(w) && w >= 16 && w <= 4096), '最多8种宽度,范围16–4096整数。'); const widths = requested.filter((w) => w <= input.width); if (!widths.length) widths.push(input.width); const entries = [], sizes = []; let total = 0;
  for (const width of widths) { const height = Math.max(1, Math.round(input.height * width / input.width)); total += width * height; assert(total <= 24e6, '累计输出超过24MP。'); const node = canvas(width, height), ctx = node.getContext('2d'); ctx.imageSmoothingQuality = 'high'; ctx.drawImage(input, 0, 0, width, height); const name = `image-${width}.png`; entries.push(await png(node, name)); sizes.push({ name, width, height }); }
  const last = sizes.at(-1), markup = `<img src="${last.name}" srcset="${sizes.map((s) => `${s.name} ${s.width}w`).join(', ')}" sizes="(max-width: 720px) 100vw, 720px" width="${last.width}" height="${last.height}" alt="替换为图片内容说明" style="max-width:100%;height:auto">`;
  entries.push(plain(html('响应式图片', markup, ''), 'index.html', 'text/html'), plain('', 'layout.css', 'text/css'), json({ sizes, omittedUpscaleWidths: requested.filter((w) => w > input.width), note: 'sizes需按实际页面布局修改。' }, 'responsive.json'));
  return [await zip(entries, 'responsive-images.zip'), json({ sizes, markup }, 'responsive.json')];
} }))();
export const token_audit = /*#__PURE__*/ (() => ({ fields: [text('data', '设计变量JSON($type / $value)', '{"color":{"brand":{"$type":"color","$value":"#167d68"},"action":{"$type":"color","$value":"{color.brand}"}},"space":{"small":{"$type":"dimension","$value":"8px"}}}', true)], async run({ values: v }) {
  const data = parseJSON(v.data), tokens = new Map(), issues = []; function visit(node, path, inheritedType) { assert(node && typeof node === 'object' && !Array.isArray(node), '变量分组需为对象。'); const type = node.$type || inheritedType; if (Object.hasOwn(node, '$value')) { assert(path, '根节点须为分组。'); tokens.set(path, { type, value: node.$value }); } else for (const [key, child] of Object.entries(node)) if (!key.startsWith('$')) { assert(/^[a-zA-Z_][\w-]*$/.test(key), '变量名需用英文字母、数字、下划线或短横线。'); visit(child, path ? path + '.' + key : key, type); } } visit(data, '', undefined); assert(tokens.size && tokens.size <= 200, '需要1–200个变量。');
  const resolved = new Map(); function resolve(key, chain = []) { if (resolved.has(key)) return resolved.get(key); assert(tokens.has(key), `引用不存在:${key}`); assert(!chain.includes(key), `循环引用:${[...chain, key].join(' → ')}`); const token = tokens.get(key); let value = token.value; if (typeof value === 'string' && /^\{[^{}]+\}$/.test(value)) { const target = value.slice(1, -1); assert(!tokens.get(target)?.type || !token.type || tokens.get(target).type === token.type, `引用类型不一致:${key}`); value = resolve(target, [...chain, key]); }
    const valid = { color: () => typeof value === 'string' && CSS.supports('color', value) && !/var\(|currentcolor|inherit/i.test(value), dimension: () => typeof value === 'string' && /^-?\d+(?:\.\d+)?(?:px|rem|em|%|vw|vh)$/.test(value), duration: () => typeof value === 'string' && /^\d+(?:\.\d+)?m?s$/.test(value), number: () => typeof value === 'number' && Number.isFinite(value), boolean: () => typeof value === 'boolean', string: () => typeof value === 'string' };
    assert(valid[token.type], `不支持或缺少$type:${key}`); assert(valid[token.type](), `值与类型不符:${key}`); resolved.set(key, value); return value;
  }
  for (const key of tokens.keys()) try { resolve(key); } catch (error) { issues.push({ token: key, message: error.message }); }
  return [json({ valid: !issues.length, count: tokens.size, issues, resolved: Object.fromEntries(resolved), supportedTypes: ['color','dimension','duration','number','boolean','string'] }, 'token-audit.json')];
} }))();
export const css_units = /*#__PURE__*/ (() => ({ fields: [num('value', '长度数值', 32, -10000, 10000, .1), choice('unit', '输入单位', [['px', 'px'], ['rem', 'rem'], ['em', 'em'], ['vw', 'vw'], ['vh', 'vh']]), num('root', '根字号(px)', 16, 1, 100), num('parent', '元素字号(px)', 16, 1, 100), num('viewportWidth', '视口宽度(px)', 1440, 100, 10000), num('viewportHeight', '视口高度(px)', 900, 100, 10000)], async run({ values: v }) {
  const factors = { px: 1, rem: v.root, em: v.parent, vw: v.viewportWidth / 100, vh: v.viewportHeight / 100 }, px = v.value * factors[v.unit], results = Object.fromEntries(Object.entries(factors).map(([unit, factor]) => [unit, px / factor]));
  return [json({ input: `${v.value}${v.unit}`, reference: { rootFont: v.root, elementFont: v.parent, viewport: [v.viewportWidth, v.viewportHeight] }, results, note: 'em用于font-size时以父元素字号为基准,其他属性以本元素字号为基准。' }, 'units.json'), plain(Object.entries(results).map(([unit, n]) => `${+n.toFixed(8)}${unit}`).join('\n'), 'units.txt')];
} }))();
export const svg_filter = /*#__PURE__*/ (() => ({ fields: [choice('kind', '滤镜', [['blur', '高斯模糊'], ['shadow', '投影'], ['matrix', '颜色矩阵']]), num('blur', '模糊标准差', 5, 0, 30), num('offset', '投影偏移', 10, -40, 40), text('matrix', '4×5颜色矩阵(20个数)', '1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0', true), color('fill', '图形颜色', '#167d68')], async run({ values: v }) {
  const matrix = v.matrix.trim().split(/[\s,]+/).map((n) => numeric(n)); assert(matrix.length === 20 && matrix.every((n) => Math.abs(n) <= 10), '颜色矩阵需要20个数值,绝对值不超过10。'); const filter = v.kind === 'blur' ? `<feGaussianBlur stdDeviation="${v.blur}"/>` : v.kind === 'shadow' ? `<feDropShadow dx="${v.offset}" dy="${v.offset}" stdDeviation="${v.blur}" flood-color="#18392f" flood-opacity=".5"/>` : `<feColorMatrix type="matrix" values="${matrix.join(' ')}"/>`;
  const body = `<defs><filter id="effect" x="-100%" y="-100%" width="300%" height="300%" color-interpolation-filters="sRGB">${filter}</filter></defs><g filter="url(#effect)"><rect x="150" y="120" width="340" height="180" rx="24" fill="${v.fill}"/><circle cx="410" cy="150" r="45" fill="#e4b359"/></g>`;
  return [...await svgResults(svgDoc(body, 640, 420, 'SVG滤镜'), 'filter-example'), plain(`<filter id="effect" x="-100%" y="-100%" width="300%" height="300%" color-interpolation-filters="sRGB">${filter}</filter>`, 'filter-snippet.txt')];
} }))();
export const image_map = /*#__PURE__*/ (() => ({ fields: [text('regions', '矩形热点JSON', '[{"name":"区域一","x":8,"y":6,"width":24,"height":18,"href":"https://example.com"}]', true)], async run({ images, values: v }) {
  const input = source(images), regions = parseJSON(v.regions); assert(Array.isArray(regions) && regions.length >= 1 && regions.length <= 50, '需要1–50个矩形热点。'); const node = canvas(input.width, input.height), ctx = node.getContext('2d'); ctx.drawImage(input, 0, 0); let areas = '';
  for (const [i, r] of regions.entries()) { const [x, y, w, h] = ['x','y','width','height'].map((k) => numeric(r[k])); assert([x,y,w,h].every(Number.isInteger) && x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= input.width && y + h <= input.height, '热点坐标必须为整数且在图片内。'); assert(typeof r.name === 'string' && r.name.length <= 80 && typeof r.href === 'string' && r.href.length <= 1000, '热点需有名称和链接。'); assert(/^(https?:\/\/|mailto:|#[\w-])/i.test(r.href) && !/[\x00-\x20]/.test(r.href), '仅支持http、https、mailto或#锚点链接。');
    areas += `<area shape="rect" coords="${x},${y},${x + w},${y + h}" href="${esc(r.href)}" alt="${esc(r.name)}">`; ctx.strokeStyle = colors[i % colors.length]; ctx.lineWidth = 2; ctx.strokeRect(x + 1, y + 1, Math.max(0, w - 2), Math.max(0, h - 2));
  }
  const markup = `<p>图片按原尺寸显示,热点坐标与原图对应。</p><div style="overflow:auto"><img src="image.png" width="${input.width}" height="${input.height}" alt="热点图片" usemap="#hotspots"><map name="hotspots">${areas}</map></div>`;
  return [await png(node, 'hotspots-preview.png'), await zip([await png(input, 'image.png'), plain(html('图片热点', markup, ''), 'index.html', 'text/html'), plain('', 'layout.css', 'text/css'), json(regions, 'hotspots.json')], 'image-map.zip')];
} }))();
export const shape_outside = /*#__PURE__*/ (() => ({ fields: [num('threshold', 'Alpha阈值', 128, 1, 255), num('margin', '文字与轮廓间距(px)', 12, 0, 60)], async run({ images, values: v }) {
  const input = source(images), p = pixels(input), points = [];
  for (let y = 0; y < p.height; y++) { let left = p.width, right = -1; for (let x = 0; x < p.width; x++) if (p.data[(y * p.width + x) * 4 + 3] >= v.threshold) { left = Math.min(left, x); right = x; } if (right >= left) points.push([left, y], [right + 1, y], [left, y + 1], [right + 1, y + 1]); }
  const hull = polygonHull(points); assert(hull && hull.length <= 2000, '透明图没有可用轮廓或轮廓太复杂。'); const percent = hull.map(([x, y]) => [Number((x / p.width * 100).toFixed(4)), Number((y / p.height * 100).toFixed(4))]), polygon = `polygon(${percent.map(([x,y]) => `${x}% ${y}%`).join(', ')})`, css = `.float-image { float:left; width:min(45%,${p.width}px); height:auto; shape-outside:${polygon}; shape-margin:${v.margin}px; margin-right:${v.margin}px; }\narticle { display:flow-root; max-width:900px; }\n`;
  const body = `<article><img class="float-image" src="image.png" width="${p.width}" height="${p.height}" alt="轮廓图片"><p>${'这是一段用于检查文字绕排的示例内容,请替换为实际正文。'.repeat(18)}</p></article>`;
  return [plain(css, 'layout.css', 'text/css'), json({ points: percent, polygon, note: '取所有可见像素的凸包;凹口、孔洞和区域间空隙会被包入轮廓。' }, 'shape.json'), await zip([await png(input, 'image.png'), plain(css, 'layout.css', 'text/css'), plain(html('文字绕排', body, ''), 'index.html', 'text/html')], 'shape-outside.zip')];
} }))();