fix(app): keep Mermaid chart axes from overlapping and clipping (#9483)
* fix(app): render Mermaid diagrams in an unscaled offscreen staging container * fix(app): keep gantt charts at a fixed width in the Mermaid staging container Rendering into the oversized staging container gave gantt charts its 16384px width, because Mermaid sizes a gantt chart from the element it renders in. The host then fit that width into the message column and the chart drew a few pixels tall. Give gantt charts the 1200px width Mermaid uses when there is no container width, so they report the same size whatever frame the host gives the runtime. Co-authored-by: FluidXin <266379324+FluidXin@users.noreply.github.com> * fix(app): keep gantt charts as wide as the Mermaid frame Pinning gantt charts to 1200px shrank them on iOS and Android, where the measuring frame is as wide as the message column and gantt charts used to fill it. Use the frame's own width instead, which is what Mermaid read from the page before rendering moved into the staging container. Co-authored-by: FluidXin <266379324+FluidXin@users.noreply.github.com> --------- Co-authored-by: FluidXin <266379324+FluidXin@users.noreply.github.com> Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
This commit is contained in:
1 parent
065c487a90
commit
525ee7f222
4 files changed
+132
-3
No files matched your search
@@ -63,10 +63,25 @@ const html = `<!doctype html>
|
||||
#diagram svg {
|
||||
display: block;
|
||||
}
|
||||
/* Keep Mermaid's temporary render container unscaled when the host mounts this frame
|
||||
at 0x0 or 240x240 before the diagram's own dimensions are known. */
|
||||
#staging-clip {
|
||||
position: fixed;
|
||||
width: 0;
|
||||
height: 0;
|
||||
overflow: hidden;
|
||||
visibility: hidden;
|
||||
pointer-events: none;
|
||||
}
|
||||
#staging {
|
||||
width: 16384px;
|
||||
height: 16384px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="diagram"></div>
|
||||
<div id="staging-clip" aria-hidden="true"><div id="staging"></div></div>
|
||||
<script>${js}</script>
|
||||
</body>
|
||||
</html>`;
|
||||
|
||||
@@ -40,6 +40,9 @@ function initializeMermaid(colorScheme: "light" | "dark"): void {
|
||||
],
|
||||
flowchart: { htmlLabels: false },
|
||||
class: { htmlLabels: false },
|
||||
// A gantt chart takes the width of the element it renders in, which is the oversized staging
|
||||
// container. Keep it as wide as this frame, which on native is the message column.
|
||||
gantt: { useWidth: document.body.clientWidth },
|
||||
});
|
||||
}
|
||||
|
||||
@@ -97,7 +100,15 @@ function measureDiagram(host: HTMLElement, svg: SVGSVGElement | null): DiagramSi
|
||||
async function render(message: MermaidRuntimeRenderMessage): Promise<void> {
|
||||
try {
|
||||
initializeMermaid(message.colorScheme);
|
||||
const { svg } = await mermaid.render(`paseo-mermaid-${message.revision}`, message.source);
|
||||
const staging = document.getElementById("staging");
|
||||
if (!staging) {
|
||||
throw new Error("Missing Mermaid staging container");
|
||||
}
|
||||
const { svg } = await mermaid.render(
|
||||
`paseo-mermaid-${message.revision}`,
|
||||
message.source,
|
||||
staging,
|
||||
);
|
||||
if (message.revision !== latestRevision) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Generated by packages/app/src/components/markdown/fence/mermaid/build-runtime.mjs.
|
||||
// Do not edit by hand.
|
||||
|
||||
export const mermaidRuntimeHtml = "<!doctype html>\n<html>\n <head>\n <meta charset=\"utf-8\" />\n <meta\n http-equiv=\"Content-Security-Policy\"\n content=\"default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'none'; img-src data: blob:; font-src 'none'; media-src 'none'; object-src 'none'; frame-src 'none'; base-uri 'none'; form-action 'none'\"\n />\n <meta\n name=\"viewport\"\n content=\"width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover\"\n />\n <style>\n html,\n body {\n margin: 0;\n padding: 0;\n background: transparent;\n height: 100%;\n }\n /* The host sizes this frame to the diagram, so the diagram fills the frame. */\n #diagram {\n height: 100%;\n }\n #diagram svg {\n display: block;\n }\n </style>\n </head>\n <body>\n <div id=\"diagram\"></div>\n <script>if(typeof globalThis.structuredClone!==\"function\"){globalThis.structuredClone=function(v){return v===undefined?v:JSON.parse(JSON.stringify(v));};}\n\"use strict\";(()=>{var iFe=Object.create;var dM=Object.defineProperty;var aFe=Object.getOwnPropertyDescriptor;var sFe=Object.getOwnPropertyNames;var oFe=Object.getPrototypeOf,lFe=Object.prototype.hasOwnProperty;var q=(t,e,r)=>()=>{if(r)throw r[0];try{return t&&(e=t(t=0)),e}catch(n){throw r=[n],n}};var Po=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}},lr=(t,e)=>{for(var r in e)dM(t,r,{get:e[r],enumerable:!0})},cFe=(t,e,r,n)=>{if(e&&typeof e==\"object\"||typeof e==\"function\")for(let i of sFe(e))!lFe.call(t,i)&&i!==r&&dM(t,i,{get:()=>e[i],enumerable:!(n=aFe(e,i))||n.enumerable});return t};var eo=(t,e,r)=>(r=t!=null?iFe(oFe(t)):{},cFe(e||!t||!t.__esModule?dM(r,\"default\",{value:t,enumerable:!0}):r,t));var jK,v,Sd,Xt=q(()=>{jK=Object.defineProperty,v=(t,e)=>jK(t,\"name\",{value:e,configurable:!0}),Sd=(t,e)=>{for(var r in e)jK(t,r,{get:e[r],enumerable:!0})}});var gE=Po((fM,pM)=>{(function(t,e){typeof fM==\"object\"&&typeof pM<\"u\"?pM.exports=e():typeof define==\"function\"&&define.amd?define(e):(t=typeof globalThis<\"u\"?globalThis:t||self).dayjs=e()})(fM,(function(){\"use strict\";var t=1e3,e=6e4,r=36e5,n=\"millisecond\",i=\"second\",a=\"minute\",s=\"hour\",o=\"day\",l=\"week\",u=\"month\",h=\"quarter\",d=\"year\",f=\"date\",p=\"Invalid Date\",g=/^(\\d{4})[-/]?(\\d{1,2})?[-/]?(\\d{0,2})[Tt\\s]*(\\d{1,2})?:?(\\d{1,2})?:?(\\d{1,2})?[.:]?(\\d+)?$/,m=/\\[([^\\]]+)]|YYYY|YY|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,y={name:\"en\",weekdays:\"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday\".split(\"_\"),months:\"January_February_March_April_May_June_July_August_September_October_November_December\".split(\"_\"),ordinal:function(R){var _=[\"th\",\"st\",\"nd\",\"rd\"],D=R%100;return\"[\"+R+(_[(D-20)%10]||_[D]||_[0])+\"]\"}},x=function(R,_,D){var I=String(R);return!I||I.length>=_?R:\"\"+Array(_+1-I.length).join(D)+R},b={s:x,z:function(R){var _=-R.utcOffset(),D=Math.abs(_),I=Math.floor(D/60),O=D%60;return(_<=0?\"+\":\"-\")+x(I,2,\"0\")+\":\"+x(O,2,\"0\")},m:function R(_,D){if(_.date()<D.date())return-R(D,_);var I=12*(D.year()-_.year())+(D.month()-_.month()),O=_.clone().add(I,u),B=D-O<0,N=_.clone().add(I+(B?-1:1),u);return+(-(I+(D-O)/(B?O-N:N-O))||0)},a:function(R){return R<0?Math.ceil(R)||0:Math.floor(R)},p:function(R){return{M:u,y:d,w:l,d:o,D:f,h:s,m:a,s:i,ms:n,Q:h}[R]||String(R||\"\").toLowerCase().replace(/s$/,\"\")},u:function(R){return R===void 0}},T=\"en\",k={};k[T]=y;var C=\"$isDayjsObject\",w=function(R){return R instanceof M||!(!R||!R[C])},S=function R(_,D,I){var O;if(!_)return T;if(typeof _==\"string\"){var B=_.toLowerCase();k[B]&&(O=B),D&&(k[B]=D,O=B);var N=_.split(\"-\");if(!O&&N.length>1)return R(N[0])}else{var $=_.name;k[$]=_,O=$}return!I&&O&&(T=O),O||!I&&T},A=function(R,_){if(w(R))return R.clone();var D=typeof _==\"object\"?_:{};return D.date=R,D.args=arguments,new M(D)},L=b;L.l=S,L.i=w,L.w=function(R,_){return A(R,{locale:_.$L,utc:_.$u,x:_.$x,$offset:_.$offset})};var M=(function(){function R(D){this.$L=S(D.locale,null,!0),this.parse(D),this.$x=this.$x||D.x||{},this[C]=!0}var _=R.prototype;return _.parse=function(D){this.$d=(function(I){var O=I.date,B=I.utc;if(O===null)return new Date(NaN);if(L.u(O))return new Date;if(O instanceof Date)return new Date(O);if(typeof O==\"string\"&&!/Z$/i.test(O)){var N=O.match(g);if(N){var $=N[2]-1||0,G=(N[7]||\"0\").substring(0,3);return B?new Date(Date.UTC(N[1],$,N[3]||1,N[4]||0,N[5]||0,N[6]||0,G)):new Date(N[1],$,N[3]||1,N[4]||0,N[5]||0,N[6]||0,G)}}return new Date(O)})(D),this.init()},_.init=function(){var D=this.$d;this.$y=D.getFullYear(),this.$M=D.getMonth(),this.$D=D.getDate(),this.$W=D.getDay(),this.$H=D.getHours(),this.$m=D.getMinutes(),this.$s=D.getSeconds(),this.$ms=D.getMilliseconds()},_.$utils=function(){return L},_.isValid=function(){return this.$d.toString()!==p},_.isSamLine truncated
|
||||
export const mermaidRuntimeHtml = "<!doctype html>\n<html>\n <head>\n <meta charset=\"utf-8\" />\n <meta\n http-equiv=\"Content-Security-Policy\"\n content=\"default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'none'; img-src data: blob:; font-src 'none'; media-src 'none'; object-src 'none'; frame-src 'none'; base-uri 'none'; form-action 'none'\"\n />\n <meta\n name=\"viewport\"\n content=\"width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover\"\n />\n <style>\n html,\n body {\n margin: 0;\n padding: 0;\n background: transparent;\n height: 100%;\n }\n /* The host sizes this frame to the diagram, so the diagram fills the frame. */\n #diagram {\n height: 100%;\n }\n #diagram svg {\n display: block;\n }\n /* Keep Mermaid's temporary render container unscaled when the host mounts this frame\n at 0x0 or 240x240 before the diagram's own dimensions are known. */\n #staging-clip {\n position: fixed;\n width: 0;\n height: 0;\n overflow: hidden;\n visibility: hidden;\n pointer-events: none;\n }\n #staging {\n width: 16384px;\n height: 16384px;\n }\n </style>\n </head>\n <body>\n <div id=\"diagram\"></div>\n <div id=\"staging-clip\" aria-hidden=\"true\"><div id=\"staging\"></div></div>\n <script>if(typeof globalThis.structuredClone!==\"function\"){globalThis.structuredClone=function(v){return v===undefined?v:JSON.parse(JSON.stringify(v));};}\n\"use strict\";(()=>{var iFe=Object.create;var dM=Object.defineProperty;var aFe=Object.getOwnPropertyDescriptor;var sFe=Object.getOwnPropertyNames;var oFe=Object.getPrototypeOf,lFe=Object.prototype.hasOwnProperty;var q=(t,e,r)=>()=>{if(r)throw r[0];try{return t&&(e=t(t=0)),e}catch(n){throw r=[n],n}};var Po=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}},lr=(t,e)=>{for(var r in e)dM(t,r,{get:e[r],enumerable:!0})},cFe=(t,e,r,n)=>{if(e&&typeof e==\"object\"||typeof e==\"function\")for(let i of sFe(e))!lFe.call(t,i)&&i!==r&&dM(t,i,{get:()=>e[i],enumerable:!(n=aFe(e,i))||n.enumerable});return t};var eo=(t,e,r)=>(r=t!=null?iFe(oFe(t)):{},cFe(e||!t||!t.__esModule?dM(r,\"default\",{value:t,enumerable:!0}):r,t));var jK,v,Sd,Xt=q(()=>{jK=Object.defineProperty,v=(t,e)=>jK(t,\"name\",{value:e,configurable:!0}),Sd=(t,e)=>{for(var r in e)jK(t,r,{get:e[r],enumerable:!0})}});var gE=Po((fM,pM)=>{(function(t,e){typeof fM==\"object\"&&typeof pM<\"u\"?pM.exports=e():typeof define==\"function\"&&define.amd?define(e):(t=typeof globalThis<\"u\"?globalThis:t||self).dayjs=e()})(fM,(function(){\"use strict\";var t=1e3,e=6e4,r=36e5,n=\"millisecond\",i=\"second\",a=\"minute\",s=\"hour\",o=\"day\",l=\"week\",u=\"month\",h=\"quarter\",d=\"year\",f=\"date\",p=\"Invalid Date\",g=/^(\\d{4})[-/]?(\\d{1,2})?[-/]?(\\d{0,2})[Tt\\s]*(\\d{1,2})?:?(\\d{1,2})?:?(\\d{1,2})?[.:]?(\\d+)?$/,m=/\\[([^\\]]+)]|YYYY|YY|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,y={name:\"en\",weekdays:\"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday\".split(\"_\"),months:\"January_February_March_April_May_June_July_August_September_October_November_December\".split(\"_\"),ordinal:function(R){var _=[\"th\",\"st\",\"nd\",\"rd\"],D=R%100;return\"[\"+R+(_[(D-20)%10]||_[D]||_[0])+\"]\"}},x=function(R,_,D){var I=String(R);return!I||I.length>=_?R:\"\"+Array(_+1-I.length).join(D)+R},b={s:x,z:function(R){var _=-R.utcOffset(),D=Math.abs(_),I=Math.floor(D/60),O=D%60;return(_<=0?\"+\":\"-\")+x(I,2,\"0\")+\":\"+x(O,2,\"0\")},m:function R(_,D){if(_.date()<D.date())return-R(D,_);var I=12*(D.year()-_.year())+(D.month()-_.month()),O=_.clone().add(I,u),B=D-O<0,N=_.clone().add(I+(B?-1:1),u);return+(-(I+(D-O)/(B?O-N:N-O))||0)},a:function(R){return R<0?Math.ceil(R)||0:Math.floor(R)},p:function(R){return{M:u,y:d,w:l,d:o,D:f,h:s,m:a,s:i,ms:n,Q:h}[R]||String(R||\"\").toLowerCase().replace(/s$/,\"\")},u:function(R){return R===void 0}},T=\"en\",k={};k[T]=y;var C=\"$isDayjsObject\",w=function(R){return R instanceof M||!(!R||!R[C])},S=function R(_,D,I){var O;if(!_)return T;if(typeof _==\"string\"){var B=_.toLowerCase();k[B]&&(O=B),D&&(k[B]=D,O=B);var N=_.split(\"-\");if(!O&&N.length>1)return R(N[0])}else{var $=_.name;k[$]=_,O=$}return!I&&O&&(T=O),O||!I&&T},A=function(R,_){if(w(R))return R.clone();var D=typeof _==\"object\"?_:{};return D.date=R,D.args=arguments,new M(D)},L=b;L.l=S,L.i=w,L.w=function(R,_){return A(R,{locale:_.$L,utc:_.$u,x:_.$x,$offset:_.$offset})};var M=(function(){function R(D){this.$L=S(D.locale,null,!0),this.parse(D),this.$x=this.$x||D.x||{},this[C]=!0}var _=R.prototype;return _.parse=function(D){this.$d=(function(I){var O=I.date,B=I.utc;if(O===null)return new Date(NaN);if(L.u(O))return new Date;if(O instanceof Date)return new Date(O);if(typeof O==\"string\"&&!/Z$/i.test(O)){var N=O.match(Line truncated
|
||||
+104
-1
@@ -29,9 +29,15 @@ function waitForRuntimeMessage(
|
||||
});
|
||||
}
|
||||
|
||||
async function mountRuntime(size?: { width: number; height: number }): Promise<HTMLIFrameElement> {
|
||||
async function mountRuntime(
|
||||
size?: { width: number; height: number },
|
||||
options?: { allowSameOrigin?: boolean },
|
||||
): Promise<HTMLIFrameElement> {
|
||||
const frame = document.createElement("iframe");
|
||||
frame.sandbox.add("allow-scripts");
|
||||
if (options?.allowSameOrigin) {
|
||||
frame.sandbox.add("allow-same-origin");
|
||||
}
|
||||
if (size) {
|
||||
frame.style.width = `${size.width}px`;
|
||||
frame.style.height = `${size.height}px`;
|
||||
@@ -112,6 +118,103 @@ describe("Mermaid sandbox runtime", () => {
|
||||
expect(renderedSize(narrow)).toEqual(renderedSize(wide));
|
||||
});
|
||||
|
||||
/**
|
||||
* MermaidFenceHost renders the first revision inside a 240x240 measuring frame (or 0x0 before
|
||||
* ResizeObserver settles), then resizes the frame to the reported diagram size without
|
||||
* re-rendering. Diagrams such as xychart-beta set `width="100%"` and `viewBox="0 0 700 500"`
|
||||
* before measuring axis text with `getBoundingClientRect()`, so rendering directly in a narrow
|
||||
* frame shrinks measured glyph boxes and leaves the Y-axis title colliding with tick labels and
|
||||
* X-axis labels clipped at the bottom edge.
|
||||
*/
|
||||
it("preserves unscaled SVG layout when rendered inside a narrow or zero-sized frame", async () => {
|
||||
const source = [
|
||||
"xychart-beta",
|
||||
' title "Throughput by Stage (req/s)"',
|
||||
' x-axis ["v1-base", "v2-parse", "v3-batch", "v4-cache", "v5-simd", "v6-final"]',
|
||||
' y-axis "Throughput (req/s)" 92.5 --> 93.6',
|
||||
" bar [92.7, 92.8, 93.1, 93.2, 93.3, 93.5]",
|
||||
].join("\n");
|
||||
const zeroFrame = await mountRuntime({ height: 0, width: 0 }, { allowSameOrigin: true });
|
||||
const measuringFrame = await mountRuntime(
|
||||
{ height: 240, width: 240 },
|
||||
{ allowSameOrigin: true },
|
||||
);
|
||||
const fullFrame = await mountRuntime({ height: 500, width: 700 }, { allowSameOrigin: true });
|
||||
|
||||
await render(zeroFrame, { revision: 1, source });
|
||||
await render(measuringFrame, { revision: 1, source });
|
||||
await render(fullFrame, { revision: 1, source });
|
||||
|
||||
for (const frame of [zeroFrame, measuringFrame]) {
|
||||
frame.style.width = "700px";
|
||||
frame.style.height = "500px";
|
||||
const doc = frame.contentDocument;
|
||||
if (!doc) {
|
||||
throw new Error("Expected inspectable runtime document");
|
||||
}
|
||||
const svgRect = doc.querySelector("#diagram svg")?.getBoundingClientRect();
|
||||
const yTitleRect = doc.querySelector(".left-axis .title text")?.getBoundingClientRect();
|
||||
const yLabels = Array.from(doc.querySelectorAll(".left-axis .label text"));
|
||||
const xLabels = Array.from(doc.querySelectorAll(".bottom-axis .label text"));
|
||||
expect(svgRect).not.toBeUndefined();
|
||||
expect(yTitleRect).not.toBeUndefined();
|
||||
expect(yLabels.length).toBeGreaterThan(0);
|
||||
expect(xLabels.length).toBeGreaterThan(0);
|
||||
|
||||
for (const label of yLabels) {
|
||||
expect(yTitleRect!.right).toBeLessThan(label.getBoundingClientRect().left);
|
||||
}
|
||||
for (const label of xLabels) {
|
||||
expect(label.getBoundingClientRect().bottom).toBeLessThanOrEqual(svgRect!.bottom);
|
||||
}
|
||||
}
|
||||
|
||||
function axisOrigin(frame: HTMLIFrameElement): { leftAxisX: number; bottomAxisY: number } {
|
||||
const doc = frame.contentDocument;
|
||||
const leftPath = doc?.querySelector(".left-axis .axisl-line path")?.getAttribute("d") ?? "";
|
||||
const bottomPath =
|
||||
doc?.querySelector(".bottom-axis .axis-line path")?.getAttribute("d") ?? "";
|
||||
const leftMatch = leftPath.match(/^M\s+([\d.]+),/);
|
||||
const bottomMatch = bottomPath.match(/^M\s+[\d.]+,([\d.]+)/);
|
||||
if (!leftMatch || !bottomMatch) {
|
||||
throw new Error(`Unexpected axis paths: ${leftPath} | ${bottomPath}`);
|
||||
}
|
||||
return {
|
||||
leftAxisX: Number.parseFloat(leftMatch[1]),
|
||||
bottomAxisY: Number.parseFloat(bottomMatch[1]),
|
||||
};
|
||||
}
|
||||
|
||||
const fullOrigin = axisOrigin(fullFrame);
|
||||
for (const candidate of [measuringFrame, zeroFrame]) {
|
||||
const origin = axisOrigin(candidate);
|
||||
expect(origin.leftAxisX).toBeCloseTo(fullOrigin.leftAxisX, 3);
|
||||
expect(origin.bottomAxisY).toBeCloseTo(fullOrigin.bottomAxisY, 3);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* A gantt chart takes the width of the element Mermaid renders it in. Rendering inside the large
|
||||
* offscreen container must keep it as wide as the frame, which on native is the message column.
|
||||
*/
|
||||
it("renders a gantt chart as wide as the frame the host gives it", async () => {
|
||||
const source = [
|
||||
"gantt",
|
||||
" title Release plan",
|
||||
" dateFormat YYYY-MM-DD",
|
||||
" section Build",
|
||||
" Design :a1, 2024-01-01, 10d",
|
||||
" Implement :after a1, 20d",
|
||||
].join("\n");
|
||||
const widths = [];
|
||||
for (const width of [240, 350, 900]) {
|
||||
const frame = await mountRuntime({ height: 240, width });
|
||||
widths.push(renderedSize(await render(frame, { revision: 1, source })).width);
|
||||
}
|
||||
|
||||
expect(widths).toEqual([240, 350, 900]);
|
||||
});
|
||||
|
||||
it("coalesces queued input and never reports an obsolete result", async () => {
|
||||
const frame = await mountRuntime();
|
||||
const obsoleteSource = `flowchart TD\n${Array.from({ length: 250 }, (_, index) => `A${index} --> A${index + 1}`).join("\n")}`;
|
||||
|
||||
Reference in new issue
Block a user