qmk-userspace/json2svg.php

111 lines
2.6 KiB
PHP

<?php
const UNIT = 50;
const GAP = 3;
$infoFile = "../../keyboards/lily58/rev1/info.json";
$info = json_decode(file_get_contents($infoFile));
$positions = $info->layouts->LAYOUT->layout;
// Determine total width and height.
$width = $height = 0;
foreach ($positions as $pos) {
$w = (($pos->w ?? 1) + GAP) * UNIT;
$h = (($pos->h ?? 1) + GAP) * UNIT;
$x = $pos->x * UNIT;
$y = $pos->y * UNIT;
if (($x + $w) > $width) {
$width = $x + $w;
}
if (($y + $h) > $height) {
$height = $y + $h;
}
}
$configuratorJson = "dnzm.json";
$layout = json_decode(file_get_contents($configuratorJson));
$layers = [];
foreach ($layout->layers as $layerIndex => $layer) {
$offset = $layerIndex * $height;
$elements = [];
foreach ($layer as $keyIndex => $key) {
if ($key === "KC_NO") {
$key = "";
} elseif ($key === "KC_TRANS") {
$key = "-";
}
if (str_starts_with($key, "KC_")) {
$key = [str_replace("KC_", "", $key)];
} elseif (str_contains($key, "(")) {
$key = explode("(", $key);
$key[0] .= "(";
} else {
$key = [$key];
}
$pos =& $positions[$keyIndex];
$w = ($pos->w ?? 1) * UNIT;
$h = ($pos->h ?? 1) * UNIT;
$x = $pos->x * (UNIT + GAP);
$y = $pos->y * (UNIT + GAP);
$tx = $x + GAP;
$ty = $y + 3 * GAP;
$key = implode("\n", array_map(fn(string $line) => "<tspan x=\"{$tx}\" dy=\"10\">{$line}</tspan>", $key));
$elements[] = <<<ELEMENT
<g id="layer_{$layerIndex}_key_{$keyIndex}">
<rect class="key" x="{$x}" y="{$y}" width="{$w}" height="{$h}" />
<text class="key-label" x="{$tx}" y="{$ty}">
{$key}
</text>
</g>
ELEMENT;
}
$elements = implode("\n", $elements);
$layers[] = <<<LAYER
<g class="layer" id="layer_{$layerIndex}" transform="translate(0,{$offset})">
<text class="layer-header" x="10" y="10">Layer {$layerIndex}</text>
<g class="layer-keys">
$elements
</g>
</g>
LAYER;
}
$layers = implode("\n", $layers);
/*echo '<?xml version="1.0" standalone="no" ?>'*/
?>
<svg xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 <?= $width ?> <?= count($layout->layers) * ($height + 20) ?>">
<style>
.key {
fill: white;
stroke: #444;
rx: 2pt;
ry: 2pt;
}
text {
font-size: 7pt;
text-align: left;
/*text-anchor: middle;*/
/*dominant-baseline: middle;*/
}
.layer-header {
font-size: 10pt;
font-weight: bold;
}
</style>
<?= $layers ?>
</svg>