add fit to screen to exported svg

This commit is contained in:
Bernard Xie 2023-01-03 11:27:15 -08:00
parent e5e76372d6
commit 643aa13de9
No known key found for this signature in database
GPG key ID: 3C3E0036CE0F892C
4 changed files with 44 additions and 15 deletions

View file

@ -7,3 +7,4 @@
#### Bugfixes ⛑️
- Appendix seperator line no longer added to PNG export when appendix doesn't exist. [#582](https://github.com/terrastruct/d2/pull/582)
- Watch mode only fits to screen on initial load. [#582](https://github.com/terrastruct/d2/pull/582)

View file

@ -1096,6 +1096,9 @@ func embedFonts(buf *bytes.Buffer, fontFamily *d2fonts.FontFamily) {
buf.WriteString(`]]></style>`)
}
//go:embed fitToScreen.js
var fitToScreenScript string
// TODO minify output at end
func Render(diagram *d2target.Diagram, opts *RenderOpts) ([]byte, error) {
var sketchRunner *d2sketch.Runner
@ -1124,6 +1127,8 @@ func Render(diagram *d2target.Diagram, opts *RenderOpts) ([]byte, error) {
]]>
</style>`, styleCSS, styleCSS2))
buf.WriteString(fmt.Sprintf(`<script type="application/javascript"><![CDATA[%s]]></script>`, fitToScreenScript))
hasMarkdown := false
for _, s := range diagram.Shapes {
if s.Label != "" && s.Type == d2target.ShapeText {

View file

@ -0,0 +1,19 @@
window.addEventListener("DOMContentLoaded", () => {
const svgEl = document.querySelector("svg");
let width = parseInt(svgEl.getAttribute("width"), 10);
let height = parseInt(svgEl.getAttribute("height"), 10);
let ratio;
if (width > height) {
if (width > window.innerWidth) {
ratio = window.innerWidth / width;
}
} else if (height > window.innerHeight) {
ratio = window.innerHeight / height;
}
// Scale svg fit to zoom
if (ratio) {
// body padding is 8px
svgEl.setAttribute("width", width * ratio - 16);
svgEl.setAttribute("height", height * ratio - 16);
}
});

View file

@ -11,6 +11,7 @@ function init(reconnectDelay) {
const ws = new WebSocket(
`ws://${window.location.host}${window.location.pathname}watch`
);
let isInit = true;
ws.onopen = () => {
reconnectDelay = 1000;
console.info("watch websocket opened");
@ -32,6 +33,7 @@ function init(reconnectDelay) {
// out the width, height and viewbox out of the top level SVG tag and update those manually.
d2SVG.innerHTML = msg.svg;
if (isInit) {
const svgEl = d2SVG.querySelector("svg");
let width = parseInt(svgEl.getAttribute("width"), 10);
let height = parseInt(svgEl.getAttribute("height"), 10);
@ -49,6 +51,8 @@ function init(reconnectDelay) {
svgEl.setAttribute("width", width * ratio - 16);
svgEl.setAttribute("height", height * ratio - 16);
}
isInit = false;
}
d2ErrDiv.style.display = "none";
}