@lark-apaas/coding-registry-buildless 0.1.28 → 0.1.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -166,6 +166,162 @@ if (!window.__miaodaMirror) {
166
166
  });
167
167
  }
168
168
 
169
+ // ── Download policy singleton ──────────────────────────────────────────────
170
+ // Shared by every buildless script on the page (first one to load defines
171
+ // it). Inlined per script (same convention as __miaodaMirror) so copy-in
172
+ // artifacts never break from a missing helper <script>. Keep every inlined
173
+ // copy identical.
174
+ if (!window.__miaodaDownloadPolicy) {
175
+ const REQ_TYPE = 'miaoda:preview:download-policy-request';
176
+ const RES_TYPE = 'miaoda:preview:download-policy';
177
+ const TIMEOUT_MS = 200;
178
+ const listeners = new Set();
179
+ let state = null; // null (unprobed) | 'unknown' | boolean
180
+ let inflight = null;
181
+ let cancelInflight = null;
182
+ let retried = false;
183
+ let seq = 0;
184
+
185
+ const notify = () => {
186
+ for (const fn of Array.from(listeners)) {
187
+ try {
188
+ fn(state);
189
+ } catch {}
190
+ }
191
+ };
192
+
193
+ const queryOnce = () => {
194
+ if (typeof state === 'boolean') return Promise.resolve(state);
195
+ if (inflight) return inflight;
196
+ let parentWin = null;
197
+ try {
198
+ parentWin = window.parent;
199
+ } catch {
200
+ parentWin = null;
201
+ }
202
+ if (!parentWin || parentWin === window) {
203
+ state = false;
204
+ notify();
205
+ return Promise.resolve(false);
206
+ }
207
+ const requestId = `dp-${++seq}-${Math.random().toString(36).slice(2, 8)}`;
208
+ inflight = new Promise((resolve) => {
209
+ let settled = false;
210
+ let timer = null;
211
+ const cleanup = () => {
212
+ if (timer !== null) {
213
+ clearTimeout(timer);
214
+ timer = null;
215
+ }
216
+ window.removeEventListener('message', onMessage);
217
+ inflight = null;
218
+ cancelInflight = null;
219
+ };
220
+ const finish = (value) => {
221
+ if (settled) return;
222
+ settled = true;
223
+ cleanup();
224
+ state = value;
225
+ notify();
226
+ resolve(value);
227
+ };
228
+ const onMessage = (e) => {
229
+ if (e.source !== parentWin) return;
230
+ const d = e.data;
231
+ if (!d || d.type !== RES_TYPE || d.requestId !== requestId) return;
232
+ if (typeof d.blockedBySandbox !== 'boolean') return;
233
+ finish(d.blockedBySandbox);
234
+ };
235
+ cancelInflight = () => {
236
+ if (settled) return;
237
+ settled = true;
238
+ cleanup();
239
+ resolve('unknown');
240
+ };
241
+ window.addEventListener('message', onMessage);
242
+ timer = setTimeout(() => finish('unknown'), TIMEOUT_MS);
243
+ try {
244
+ parentWin.postMessage({ type: REQ_TYPE, requestId }, '*');
245
+ } catch {
246
+ finish('unknown');
247
+ }
248
+ });
249
+ return inflight;
250
+ };
251
+
252
+ window.__miaodaDownloadPolicy = {
253
+ prime() {
254
+ if (state !== null) return Promise.resolve(state);
255
+ return queryOnce();
256
+ },
257
+ isBlocked() {
258
+ return state === true;
259
+ },
260
+ subscribe(fn) {
261
+ listeners.add(fn);
262
+ return () => {
263
+ listeners.delete(fn);
264
+ };
265
+ },
266
+ async check() {
267
+ if (typeof state === 'boolean') return state;
268
+ if (inflight) return inflight;
269
+ if (state === 'unknown' && retried) return 'unknown';
270
+ if (state === 'unknown') retried = true;
271
+ return queryOnce();
272
+ },
273
+ reset() {
274
+ if (cancelInflight) cancelInflight();
275
+ state = null;
276
+ inflight = null;
277
+ retried = false;
278
+ notify();
279
+ },
280
+ };
281
+ }
282
+ void window.__miaodaDownloadPolicy.prime();
283
+ const DC_DOWNLOAD_BLOCKED_TIP = '互联网公开时不可下载,请切换分享范围';
284
+ function dcAlignTooltip(btn) {
285
+ if (!btn || btn.getAttribute('data-download-blocked') !== 'true') return;
286
+ const rect = btn.getBoundingClientRect();
287
+ const vw = window.innerWidth || document.documentElement.clientWidth || 0;
288
+ const vh = window.innerHeight || document.documentElement.clientHeight || 0;
289
+ if (!vw || !rect.width) return;
290
+ const margin = 8;
291
+ const maxW = Math.min(260, Math.max(60, vw - margin * 2));
292
+ const wrap = maxW < 252;
293
+ const estW = Math.min(maxW, 252);
294
+ const center = rect.left + rect.width / 2;
295
+ let left = center - estW / 2;
296
+ if (left < margin) left = margin;
297
+ if (left + estW > vw - margin) left = Math.max(margin, vw - margin - estW);
298
+ const shift = Math.round(left - (center - estW / 2));
299
+ btn.style.setProperty('--tt-shift', `${shift}px`);
300
+ btn.style.setProperty('--tt-max-w', `${Math.floor(maxW)}px`);
301
+ if (wrap) btn.setAttribute('data-tooltip-wrap', 'true');
302
+ else btn.removeAttribute('data-tooltip-wrap');
303
+ const tipLen = (btn.getAttribute('data-tooltip') || DC_DOWNLOAD_BLOCKED_TIP).length || 18;
304
+ const innerW = Math.max(24, maxW - 20);
305
+ const estLines = wrap
306
+ ? Math.max(1, Math.ceil(tipLen / Math.max(1, Math.floor(innerW / 12))))
307
+ : 1;
308
+ let tooltipH = Math.ceil(estLines * 17 + 12);
309
+ try {
310
+ const measuredH = parseFloat(getComputedStyle(btn, '::after').height);
311
+ if (Number.isFinite(measuredH) && measuredH > 0) {
312
+ tooltipH = Math.max(tooltipH, Math.ceil(measuredH));
313
+ }
314
+ } catch {}
315
+ const neededH = tooltipH + 8;
316
+ const spaceAbove = rect.top - margin;
317
+ const spaceBelow = vh ? vh - rect.bottom - margin : Infinity;
318
+ if (spaceAbove < neededH && spaceBelow >= spaceAbove) {
319
+ btn.setAttribute('data-tooltip-placement', 'bottom');
320
+ } else {
321
+ btn.removeAttribute('data-tooltip-placement');
322
+ }
323
+ }
324
+
169
325
  // One-time CSS injection (classes are dc-prefixed so they don't collide with
170
326
  // the hosted design's own styles).
171
327
  if (typeof document !== 'undefined' && !document.getElementById('dc-styles')) {
@@ -266,8 +422,29 @@ if (typeof document !== 'undefined' && !document.getElementById('dc-styles')) {
266
422
  ' border-radius:6px;font-family:inherit;font-size:14px;font-weight:400;line-height:24px;',
267
423
  ' color:#1F2329;cursor:pointer;text-align:left;transition:background .12s;white-space:nowrap}',
268
424
  '.dc-menu button:hover{background:rgba(31,35,41,0.05)}',
425
+ '.dc-menu button[data-download-blocked="true"]{position:relative;color:#8F959E;cursor:not-allowed}',
426
+ '.dc-menu button[data-download-blocked="true"]:hover{background:transparent}',
427
+ '.dc-menu button[data-download-blocked="true"]:hover::before,.dc-menu button[data-download-blocked="true"]:focus-visible::before{',
428
+ ' content:"";position:absolute;bottom:calc(100% + 3px);left:50%;transform:translateX(-50%);z-index:30;',
429
+ ' border:5px solid transparent;border-top-color:#1F2329;border-bottom:0;pointer-events:none}',
430
+ '.dc-menu button[data-download-blocked="true"]:hover::after,.dc-menu button[data-download-blocked="true"]:focus-visible::after{',
431
+ ' content:attr(data-tooltip);position:absolute;bottom:calc(100% + 8px);left:50%;transform:translateX(calc(-50% + var(--tt-shift,0px)));z-index:30;',
432
+ ' width:max-content;max-width:var(--tt-max-w,260px);box-sizing:border-box;padding:6px 10px;border-radius:6px;background:#1F2329;color:#fff;',
433
+ ' font-family:inherit;font-size:12px;font-weight:400;line-height:1.4;white-space:nowrap;',
434
+ ' box-shadow:0 4px 12px rgba(0,0,0,.18);pointer-events:none}',
435
+ '.dc-menu button[data-download-blocked="true"][data-tooltip-wrap="true"]:hover::after,',
436
+ '.dc-menu button[data-download-blocked="true"][data-tooltip-wrap="true"]:focus-visible::after{white-space:normal}',
437
+ '.dc-menu button[data-download-blocked="true"][data-tooltip-placement="bottom"]:hover::before,',
438
+ '.dc-menu button[data-download-blocked="true"][data-tooltip-placement="bottom"]:focus-visible::before{',
439
+ ' bottom:auto;top:calc(100% + 3px);border-top:0;border-bottom:5px solid #1F2329}',
440
+ '.dc-menu button[data-download-blocked="true"][data-tooltip-placement="bottom"]:hover::after,',
441
+ '.dc-menu button[data-download-blocked="true"][data-tooltip-placement="bottom"]:focus-visible::after{',
442
+ ' bottom:auto;top:calc(100% + 8px)}',
269
443
  '.dc-menu hr{border:0;border-top:1px solid rgba(0,0,0,.08);margin:4px 2px}',
270
444
  '.dc-menu .dc-danger{color:#F54A45}',
445
+ '.dc-export-status:not(:empty){position:absolute;top:calc(16px + env(safe-area-inset-top,0px));left:50%;transform:translateX(-50%);z-index:101;',
446
+ 'width:max-content;max-width:calc(100% - 32px);box-sizing:border-box;pointer-events:none;background:#fff;color:#1F2329;',
447
+ 'padding:10px 16px;border-radius:12px;font-size:14px;line-height:1.4;box-shadow:0 4px 16px rgba(31,35,41,.12)}',
271
448
  // Chrome (titles / labels / buttons) counter-scales against the viewport
272
449
  // zoom so it stays a constant on-screen size. --dc-inv-zoom is set by
273
450
  // DCViewport on every transform update and inherits to all descendants —
@@ -376,6 +553,12 @@ function miaodaWriteFile(path, content, writeContext) {
376
553
 
377
554
  function DesignCanvas({ children, minScale, maxScale, style }) {
378
555
  const [state, setState] = React.useState({ sections: {}, focus: null });
556
+ const [exportStatus, setExportStatus] = React.useState(null);
557
+ React.useEffect(() => {
558
+ if (!exportStatus) return;
559
+ const timer = setTimeout(() => setExportStatus(null), 3500);
560
+ return () => clearTimeout(timer);
561
+ }, [exportStatus]);
379
562
  const [registeredSections, setRegisteredSections] = React.useState(() => new Map());
380
563
  const registeredSectionsRef = React.useRef(registeredSections);
381
564
  registeredSectionsRef.current = registeredSections;
@@ -539,6 +722,7 @@ function DesignCanvas({ children, minScale, maxScale, style }) {
539
722
  registerSection,
540
723
  getSectionNavigation,
541
724
  focusedSection,
725
+ showExportStatus: (message) => setExportStatus({ message }),
542
726
  section: (id) => state.sections[id] || DC_EMPTY_SECTION,
543
727
  patchSection: (id, p) => setState((s) => ({
544
728
  ...s,
@@ -570,7 +754,9 @@ function DesignCanvas({ children, minScale, maxScale, style }) {
570
754
 
571
755
  return (
572
756
  <DCCtx.Provider value={api}>
573
- <DCViewport minScale={minScale} maxScale={maxScale} style={style}>{ready && worldChildren}</DCViewport>
757
+ <DCViewport minScale={minScale} maxScale={maxScale} style={style} exportMessage={exportStatus?.message}>
758
+ {ready && worldChildren}
759
+ </DCViewport>
574
760
  {ready && overlayChildren}
575
761
  </DCCtx.Provider>
576
762
  );
@@ -677,7 +863,7 @@ function DCZoomControl({ scalePct, minScale, maxScale, onZoomTo }) {
677
863
  // (translate3d + will-change) so wheel ticks don't go through React —
678
864
  // keeps pans at 60fps on dense canvases.
679
865
  // ─────────────────────────────────────────────────────────────
680
- function DCViewport({ children, minScale = 0.1, maxScale = 8, style = {} }) {
866
+ function DCViewport({ children, minScale = 0.1, maxScale = 8, style = {}, exportMessage }) {
681
867
  const vpRef = React.useRef(null);
682
868
  const worldRef = React.useRef(null);
683
869
  // Pre-fit fallback scale. A fresh canvas is reframed by the first-visit fit
@@ -1248,6 +1434,7 @@ function DCViewport({ children, minScale = 0.1, maxScale = 8, style = {} }) {
1248
1434
  >
1249
1435
  {children}
1250
1436
  </div>
1437
+ <div className="dc-export-status" role="status" data-miaoda-chrome="">{exportMessage}</div>
1251
1438
  {/* Mobile zooms by pinch — the control is not rendered at all (host
1252
1439
  set-zoom messages still work; the protocol is independent of it). */}
1253
1440
  {!dcIsMobile && (
@@ -1328,6 +1515,7 @@ function DCSection({ id, title, subtitle, children, gap = 48 }) {
1328
1515
  <div style={{ display: 'flex', gap, padding: '0 60px', alignItems: 'flex-start', width: 'max-content' }}>
1329
1516
  {order.map((k) => (
1330
1517
  <DCArtboardFrame key={k} sectionId={sid} artboard={byId[k]} order={order}
1518
+ onExportStatus={ctx?.showExportStatus}
1331
1519
  label={(sec.labels || {})[k] ?? byId[k].props.label}
1332
1520
  onRename={(v) => ctx && ctx.patchSection(sid, (x) => ({ labels: { ...x.labels, [k]: v } }))}
1333
1521
  onReorder={(next) => ctx && ctx.patchSection(sid, { order: next })}
@@ -1439,7 +1627,6 @@ async function dcExport(node, w, h, name, kind) {
1439
1627
 
1440
1628
  const xml = new XMLSerializer().serializeToString(clone);
1441
1629
  const save = (blob, ext) => {
1442
- if (!blob) return;
1443
1630
  const a = document.createElement('a');
1444
1631
  a.href = URL.createObjectURL(blob); a.download = name + '.' + ext; a.click();
1445
1632
  setTimeout(() => URL.revokeObjectURL(a.href), 1000);
@@ -1469,10 +1656,12 @@ async function dcExport(node, w, h, name, kind) {
1469
1656
  const cv = document.createElement('canvas');
1470
1657
  cv.width = w * px; cv.height = h * px;
1471
1658
  cv.getContext('2d').drawImage(img, 0, 0);
1472
- cv.toBlob((blob) => save(blob, 'png'), 'image/png');
1659
+ const blob = await new Promise((resolve) => cv.toBlob(resolve, 'image/png'));
1660
+ if (!blob) throw new Error('PNG encoding failed');
1661
+ save(blob, 'png');
1473
1662
  }
1474
1663
 
1475
- function DCArtboardFrame({ sectionId, artboard, label, order, onRename, onReorder, onFocus, onDelete }) {
1664
+ function DCArtboardFrame({ sectionId, artboard, label, order, onRename, onReorder, onFocus, onDelete, onExportStatus }) {
1476
1665
  // Read height off the raw props (not a destructure default) so an *absent*
1477
1666
  // height can opt into auto-grow while an explicit height={N} — even 480 —
1478
1667
  // still means a fixed, content-clipping frame (thumbnail semantics).
@@ -1485,6 +1674,15 @@ function DCArtboardFrame({ sectionId, artboard, label, order, onRename, onReorde
1485
1674
  const menuRef = React.useRef(null);
1486
1675
  const [menuOpen, setMenuOpen] = React.useState(false);
1487
1676
  const [confirming, setConfirming] = React.useState(false);
1677
+ const [downloadBlocked, setDownloadBlocked] = React.useState(() =>
1678
+ window.__miaodaDownloadPolicy.isBlocked(),
1679
+ );
1680
+
1681
+ React.useEffect(() => {
1682
+ setDownloadBlocked(window.__miaodaDownloadPolicy.isBlocked());
1683
+ void window.__miaodaDownloadPolicy.prime();
1684
+ return window.__miaodaDownloadPolicy.subscribe((v) => setDownloadBlocked(v === true));
1685
+ }, []);
1488
1686
 
1489
1687
  // ⋯ menu: close on any outside pointerdown. Two-click delete lives inside
1490
1688
  // the menu — first click arms the row, second commits; closing disarms.
@@ -1495,17 +1693,34 @@ function DCArtboardFrame({ sectionId, artboard, label, order, onRename, onReorde
1495
1693
  return () => document.removeEventListener('pointerdown', off, true);
1496
1694
  }, [menuOpen]);
1497
1695
 
1498
- const doExport = (kind) => {
1696
+ React.useEffect(() => {
1697
+ if (!menuOpen || !menuRef.current) return;
1698
+ menuRef.current
1699
+ .querySelectorAll('button[data-download-blocked="true"]')
1700
+ .forEach((btn) => dcAlignTooltip(btn));
1701
+ }, [menuOpen, downloadBlocked]);
1702
+
1703
+ const doExport = async (kind) => {
1499
1704
  setMenuOpen(false);
1500
1705
  if (!cardRef.current) return;
1706
+ if ((await window.__miaodaDownloadPolicy.check()) === true) {
1707
+ if (cardRef.current) onExportStatus?.(DC_DOWNLOAD_BLOCKED_TIP);
1708
+ return;
1709
+ }
1710
+ const card = cardRef.current;
1711
+ if (!card) return;
1501
1712
  // Unicode-aware sanitize: keep letters (incl. CJK/accented), digits,
1502
1713
  // whitespace, dot/underscore/hyphen; collapse everything else to '_'.
1503
1714
  // ASCII-only \w would strip Chinese labels down to a bare '_'.
1504
1715
  const name = String(label || id || 'artboard').replace(/[^\p{L}\p{N}\s._-]+/gu, '_');
1505
- const ew = cardRef.current.offsetWidth || width;
1506
- const eh = cardRef.current.offsetHeight || height;
1507
- dcExport(cardRef.current, ew, eh, name, kind)
1508
- .catch((e) => console.error('[design-canvas] export failed:', e));
1716
+ const ew = card.offsetWidth || width;
1717
+ const eh = card.offsetHeight || height;
1718
+ try {
1719
+ await dcExport(card, ew, eh, name, kind);
1720
+ } catch (e) {
1721
+ console.error('[design-canvas] export failed:', e);
1722
+ onExportStatus?.('导出失败,请重试');
1723
+ }
1509
1724
  };
1510
1725
 
1511
1726
  // Live drag-reorder: dragged card sticks to cursor; siblings slide into
@@ -1592,8 +1807,22 @@ function DCArtboardFrame({ sectionId, artboard, label, order, onRename, onReorde
1592
1807
  </button>
1593
1808
  {menuOpen && (
1594
1809
  <div className="dc-menu" onPointerDown={(e) => e.stopPropagation()}>
1595
- <button onClick={() => doExport('png')}>下载 PNG</button>
1596
- <button onClick={() => doExport('html')}>下载 HTML</button>
1810
+ <button
1811
+ aria-disabled={downloadBlocked || undefined}
1812
+ data-download-blocked={downloadBlocked ? 'true' : undefined}
1813
+ data-tooltip={downloadBlocked ? DC_DOWNLOAD_BLOCKED_TIP : undefined}
1814
+ onPointerEnter={(e) => dcAlignTooltip(e.currentTarget)}
1815
+ onFocus={(e) => dcAlignTooltip(e.currentTarget)}
1816
+ onClick={() => { if (!downloadBlocked) doExport('png'); }}
1817
+ >下载 PNG</button>
1818
+ <button
1819
+ aria-disabled={downloadBlocked || undefined}
1820
+ data-download-blocked={downloadBlocked ? 'true' : undefined}
1821
+ data-tooltip={downloadBlocked ? DC_DOWNLOAD_BLOCKED_TIP : undefined}
1822
+ onPointerEnter={(e) => dcAlignTooltip(e.currentTarget)}
1823
+ onFocus={(e) => dcAlignTooltip(e.currentTarget)}
1824
+ onClick={() => { if (!downloadBlocked) doExport('html'); }}
1825
+ >下载 HTML</button>
1597
1826
  <button className="dc-danger"
1598
1827
  onClick={() => { if (confirming) { setMenuOpen(false); onDelete(); } else setConfirming(true); }}>
1599
1828
  {confirming ? '确认删除' : '删除'}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lark-apaas/coding-registry-buildless",
3
- "version": "0.1.28",
3
+ "version": "0.1.30",
4
4
  "description": "Miaoda registry (buildless runtime) — shadcn-style copy-in SDKs (globals + CDN-pinned, browser Babel) for buildless static HTML stacks",
5
5
  "type": "module",
6
6
  "files": [
@@ -150,6 +150,121 @@
150
150
  });
151
151
  }
152
152
 
153
+ // ── Download policy singleton ──────────────────────────────────────────────
154
+ // Shared by every buildless script on the page (first one to load defines
155
+ // it). Inlined per script (same convention as __miaodaMirror) so copy-in
156
+ // artifacts never break from a missing helper <script>. Keep every inlined
157
+ // copy identical.
158
+ if (!window.__miaodaDownloadPolicy) {
159
+ const REQ_TYPE = 'miaoda:preview:download-policy-request';
160
+ const RES_TYPE = 'miaoda:preview:download-policy';
161
+ const TIMEOUT_MS = 200;
162
+ const listeners = new Set();
163
+ let state = null; // null (unprobed) | 'unknown' | boolean
164
+ let inflight = null;
165
+ let cancelInflight = null;
166
+ let retried = false;
167
+ let seq = 0;
168
+
169
+ const notify = () => {
170
+ for (const fn of Array.from(listeners)) {
171
+ try {
172
+ fn(state);
173
+ } catch {}
174
+ }
175
+ };
176
+
177
+ const queryOnce = () => {
178
+ if (typeof state === 'boolean') return Promise.resolve(state);
179
+ if (inflight) return inflight;
180
+ let parentWin = null;
181
+ try {
182
+ parentWin = window.parent;
183
+ } catch {
184
+ parentWin = null;
185
+ }
186
+ if (!parentWin || parentWin === window) {
187
+ state = false;
188
+ notify();
189
+ return Promise.resolve(false);
190
+ }
191
+ const requestId = `dp-${++seq}-${Math.random().toString(36).slice(2, 8)}`;
192
+ inflight = new Promise((resolve) => {
193
+ let settled = false;
194
+ let timer = null;
195
+ const cleanup = () => {
196
+ if (timer !== null) {
197
+ clearTimeout(timer);
198
+ timer = null;
199
+ }
200
+ window.removeEventListener('message', onMessage);
201
+ inflight = null;
202
+ cancelInflight = null;
203
+ };
204
+ const finish = (value) => {
205
+ if (settled) return;
206
+ settled = true;
207
+ cleanup();
208
+ state = value;
209
+ notify();
210
+ resolve(value);
211
+ };
212
+ const onMessage = (e) => {
213
+ if (e.source !== parentWin) return;
214
+ const d = e.data;
215
+ if (!d || d.type !== RES_TYPE || d.requestId !== requestId) return;
216
+ if (typeof d.blockedBySandbox !== 'boolean') return;
217
+ finish(d.blockedBySandbox);
218
+ };
219
+ cancelInflight = () => {
220
+ if (settled) return;
221
+ settled = true;
222
+ cleanup();
223
+ resolve('unknown');
224
+ };
225
+ window.addEventListener('message', onMessage);
226
+ timer = setTimeout(() => finish('unknown'), TIMEOUT_MS);
227
+ try {
228
+ parentWin.postMessage({ type: REQ_TYPE, requestId }, '*');
229
+ } catch {
230
+ finish('unknown');
231
+ }
232
+ });
233
+ return inflight;
234
+ };
235
+
236
+ window.__miaodaDownloadPolicy = {
237
+ prime() {
238
+ if (state !== null) return Promise.resolve(state);
239
+ return queryOnce();
240
+ },
241
+ isBlocked() {
242
+ return state === true;
243
+ },
244
+ subscribe(fn) {
245
+ listeners.add(fn);
246
+ return () => {
247
+ listeners.delete(fn);
248
+ };
249
+ },
250
+ async check() {
251
+ if (typeof state === 'boolean') return state;
252
+ if (inflight) return inflight;
253
+ if (state === 'unknown' && retried) return 'unknown';
254
+ if (state === 'unknown') retried = true;
255
+ return queryOnce();
256
+ },
257
+ reset() {
258
+ if (cancelInflight) cancelInflight();
259
+ state = null;
260
+ inflight = null;
261
+ retried = false;
262
+ notify();
263
+ },
264
+ };
265
+ }
266
+ void window.__miaodaDownloadPolicy.prime();
267
+
153
268
  /** Shorthands for the common frames; anything else is computed by parseRatio — this is not an allowlist */
154
269
  const RATIOS = {
155
270
  '3:4': [1080, 1440],
@@ -176,6 +291,83 @@
176
291
 
177
292
  const STYLE_ID = 'card-stage-style';
178
293
  const STATE_FILE = '.card-stage.state.json';
294
+ const CS_DOWNLOAD_BLOCKED_TIP = '互联网公开时不可下载,请切换分享范围';
295
+
296
+ const isCsDownloadBlocked = () =>
297
+ !(csIsMobile && csInAppWebView) && window.__miaodaDownloadPolicy.isBlocked();
298
+ const alignCsTooltip = (btn) => {
299
+ if (!btn || btn.getAttribute('data-download-blocked') !== 'true') return;
300
+ const rect = btn.getBoundingClientRect();
301
+ const vw = window.innerWidth || document.documentElement.clientWidth || 0;
302
+ const vh = window.innerHeight || document.documentElement.clientHeight || 0;
303
+ if (!vw || !rect.width) return;
304
+ const margin = 8;
305
+ const maxW = Math.min(260, Math.max(60, vw - margin * 2));
306
+ const wrap = maxW < 252;
307
+ const estW = Math.min(maxW, 252);
308
+ const center = rect.left + rect.width / 2;
309
+ let left = center - estW / 2;
310
+ if (left < margin) left = margin;
311
+ if (left + estW > vw - margin) left = Math.max(margin, vw - margin - estW);
312
+ const shift = Math.round(left - (center - estW / 2));
313
+ btn.style.setProperty('--tt-shift', `${shift}px`);
314
+ btn.style.setProperty('--tt-max-w', `${Math.floor(maxW)}px`);
315
+ if (wrap) btn.setAttribute('data-tooltip-wrap', 'true');
316
+ else btn.removeAttribute('data-tooltip-wrap');
317
+ const tipLen = (btn.getAttribute('data-tooltip') || CS_DOWNLOAD_BLOCKED_TIP).length || 18;
318
+ const innerW = Math.max(24, maxW - 20);
319
+ const estLines = wrap
320
+ ? Math.max(1, Math.ceil(tipLen / Math.max(1, Math.floor(innerW / 12))))
321
+ : 1;
322
+ let tooltipH = Math.ceil(estLines * 17 + 12);
323
+ try {
324
+ const measuredH = parseFloat(getComputedStyle(btn, '::after').height);
325
+ if (Number.isFinite(measuredH) && measuredH > 0) {
326
+ tooltipH = Math.max(tooltipH, Math.ceil(measuredH));
327
+ }
328
+ } catch {}
329
+ const neededH = tooltipH + 8;
330
+ const spaceAbove = rect.top - margin;
331
+ const spaceBelow = vh ? vh - rect.bottom - margin : Infinity;
332
+ if (spaceAbove < neededH && spaceBelow >= spaceAbove) {
333
+ btn.setAttribute('data-tooltip-placement', 'bottom');
334
+ } else {
335
+ btn.removeAttribute('data-tooltip-placement');
336
+ }
337
+ };
338
+ const applyCsDownloadButtonState = (btn, defaultTitle) => {
339
+ if (isCsDownloadBlocked()) {
340
+ btn.setAttribute('aria-disabled', 'true');
341
+ btn.setAttribute('data-download-blocked', 'true');
342
+ btn.setAttribute('data-tooltip', CS_DOWNLOAD_BLOCKED_TIP);
343
+ if (defaultTitle) btn.removeAttribute('title');
344
+ alignCsTooltip(btn);
345
+ } else {
346
+ btn.removeAttribute('aria-disabled');
347
+ btn.removeAttribute('data-download-blocked');
348
+ btn.removeAttribute('data-tooltip');
349
+ btn.removeAttribute('data-tooltip-wrap');
350
+ btn.removeAttribute('data-tooltip-placement');
351
+ btn.style.removeProperty('--tt-shift');
352
+ btn.style.removeProperty('--tt-max-w');
353
+ if (defaultTitle) btn.title = defaultTitle;
354
+ }
355
+ };
356
+ const bindCsDownloadButton = (btn, defaultTitle) => {
357
+ applyCsDownloadButtonState(btn, defaultTitle);
358
+ const onAlign = () => alignCsTooltip(btn);
359
+ btn.addEventListener('pointerenter', onAlign);
360
+ btn.addEventListener('focus', onAlign);
361
+ void window.__miaodaDownloadPolicy.prime();
362
+ const offPolicy = window.__miaodaDownloadPolicy.subscribe(() =>
363
+ applyCsDownloadButtonState(btn, defaultTitle),
364
+ );
365
+ return () => {
366
+ offPolicy();
367
+ btn.removeEventListener('pointerenter', onAlign);
368
+ btn.removeEventListener('focus', onAlign);
369
+ };
370
+ };
179
371
 
180
372
  // Host write-file bridge, same protocol as design-canvas.jsx. Deletes and renames
181
373
  // have to survive a reload — a card that comes back after being deleted is worse than
@@ -347,6 +539,88 @@
347
539
  color: #1F2329;
348
540
  }
349
541
  .cs-menu button:hover { background: rgba(31,35,41,.05); }
542
+ .cs-menu button[data-download-blocked="true"] {
543
+ position: relative;
544
+ color: #8F959E;
545
+ cursor: not-allowed;
546
+ }
547
+ .cs-menu button[data-download-blocked="true"]:hover { background: transparent; }
548
+ .cs-focus-btn[data-download-blocked="true"],
549
+ .cs-macts button[data-download-blocked="true"] {
550
+ position: relative;
551
+ opacity: .38;
552
+ cursor: not-allowed;
553
+ }
554
+ .cs-focus-btn[data-download-blocked="true"]:hover { background: transparent; }
555
+ .cs-menu button[data-download-blocked="true"]:hover::before,
556
+ .cs-menu button[data-download-blocked="true"]:focus-visible::before,
557
+ .cs-focus-btn[data-download-blocked="true"]:hover::before,
558
+ .cs-focus-btn[data-download-blocked="true"]:focus-visible::before,
559
+ .cs-macts button[data-download-blocked="true"]:hover::before,
560
+ .cs-macts button[data-download-blocked="true"]:focus-visible::before {
561
+ content: '';
562
+ position: absolute;
563
+ bottom: calc(100% + 3px);
564
+ left: 50%;
565
+ transform: translateX(-50%);
566
+ z-index: 30;
567
+ border: 5px solid transparent;
568
+ border-top-color: #1F2329;
569
+ border-bottom: 0;
570
+ pointer-events: none;
571
+ }
572
+ .cs-menu button[data-download-blocked="true"]:hover::after,
573
+ .cs-menu button[data-download-blocked="true"]:focus-visible::after,
574
+ .cs-focus-btn[data-download-blocked="true"]:hover::after,
575
+ .cs-focus-btn[data-download-blocked="true"]:focus-visible::after,
576
+ .cs-macts button[data-download-blocked="true"]:hover::after,
577
+ .cs-macts button[data-download-blocked="true"]:focus-visible::after {
578
+ content: attr(data-tooltip);
579
+ position: absolute;
580
+ bottom: calc(100% + 8px);
581
+ left: 50%;
582
+ transform: translateX(calc(-50% + var(--tt-shift, 0px)));
583
+ z-index: 30;
584
+ width: max-content;
585
+ max-width: var(--tt-max-w, 260px);
586
+ box-sizing: border-box;
587
+ padding: 6px 10px;
588
+ border-radius: 6px;
589
+ background: #1F2329;
590
+ color: #fff;
591
+ font: 400 12px/1.4 ui-sans-serif, -apple-system, "PingFang SC", sans-serif;
592
+ white-space: nowrap;
593
+ box-shadow: 0 4px 12px rgba(0,0,0,.18);
594
+ pointer-events: none;
595
+ }
596
+ .cs-menu button[data-download-blocked="true"][data-tooltip-wrap="true"]:hover::after,
597
+ .cs-menu button[data-download-blocked="true"][data-tooltip-wrap="true"]:focus-visible::after,
598
+ .cs-focus-btn[data-download-blocked="true"][data-tooltip-wrap="true"]:hover::after,
599
+ .cs-focus-btn[data-download-blocked="true"][data-tooltip-wrap="true"]:focus-visible::after,
600
+ .cs-macts button[data-download-blocked="true"][data-tooltip-wrap="true"]:hover::after,
601
+ .cs-macts button[data-download-blocked="true"][data-tooltip-wrap="true"]:focus-visible::after {
602
+ white-space: normal;
603
+ }
604
+ .cs-menu button[data-download-blocked="true"][data-tooltip-placement="bottom"]:hover::before,
605
+ .cs-menu button[data-download-blocked="true"][data-tooltip-placement="bottom"]:focus-visible::before,
606
+ .cs-focus-btn[data-download-blocked="true"][data-tooltip-placement="bottom"]:hover::before,
607
+ .cs-focus-btn[data-download-blocked="true"][data-tooltip-placement="bottom"]:focus-visible::before,
608
+ .cs-macts button[data-download-blocked="true"][data-tooltip-placement="bottom"]:hover::before,
609
+ .cs-macts button[data-download-blocked="true"][data-tooltip-placement="bottom"]:focus-visible::before {
610
+ bottom: auto;
611
+ top: calc(100% + 3px);
612
+ border-top: 0;
613
+ border-bottom: 5px solid #1F2329;
614
+ }
615
+ .cs-menu button[data-download-blocked="true"][data-tooltip-placement="bottom"]:hover::after,
616
+ .cs-menu button[data-download-blocked="true"][data-tooltip-placement="bottom"]:focus-visible::after,
617
+ .cs-focus-btn[data-download-blocked="true"][data-tooltip-placement="bottom"]:hover::after,
618
+ .cs-focus-btn[data-download-blocked="true"][data-tooltip-placement="bottom"]:focus-visible::after,
619
+ .cs-macts button[data-download-blocked="true"][data-tooltip-placement="bottom"]:hover::after,
620
+ .cs-macts button[data-download-blocked="true"][data-tooltip-placement="bottom"]:focus-visible::after {
621
+ bottom: auto;
622
+ top: calc(100% + 8px);
623
+ }
350
624
  /* Destructive item: red text, and a light red hover instead of neutral grey. The colour
351
625
  goes through --destructive-foreground so the host theme can override it; the literal is
352
626
  only the fallback for artifacts that define no token.
@@ -1328,6 +1602,17 @@
1328
1602
  }
1329
1603
  }
1330
1604
 
1605
+ disconnectedCallback() {
1606
+ this.closeFocus();
1607
+ this.closeContextMenu();
1608
+ if (this._offMobilePolicy) { this._offMobilePolicy(); this._offMobilePolicy = null; }
1609
+ if (this.heads) {
1610
+ for (const head of this.heads) {
1611
+ if (head && head._closeMenu) head._closeMenu();
1612
+ }
1613
+ }
1614
+ }
1615
+
1331
1616
  async init() {
1332
1617
  // Safety net: even if init throws halfway, the page has to become visible — one flash
1333
1618
  // beats staying blank forever
@@ -1553,10 +1838,13 @@
1553
1838
  }
1554
1839
 
1555
1840
  /**
1556
- * Render and save card n (1-indexed). A false return means the user cancelled in the share
1557
- * sheet, which is how the caller decides whether to show a success toast.
1841
+ * Render card n (1-indexed). True means a download was requested or sharing resolved.
1842
+ * Cancelling or opening the manual save sheet returns false.
1558
1843
  */
1559
1844
  async downloadCard(n) {
1845
+ if (!(csIsMobile && csInAppWebView) && (await window.__miaodaDownloadPolicy.check()) === true) {
1846
+ return false;
1847
+ }
1560
1848
  const name = this.fileName(n);
1561
1849
  const blob = await this.renderCard(n);
1562
1850
  // Only in-app WebViews need the detour: there a blob: handed to the host is rejected as
@@ -1588,6 +1876,18 @@
1588
1876
  return true;
1589
1877
  }
1590
1878
 
1879
+ async downloadCardWithFeedback(n) {
1880
+ try {
1881
+ if (!(csIsMobile && csInAppWebView) && (await window.__miaodaDownloadPolicy.check()) === true) {
1882
+ this.toast(CS_DOWNLOAD_BLOCKED_TIP, false);
1883
+ return;
1884
+ }
1885
+ if (await this.downloadCard(n)) this.toast('图片下载成功');
1886
+ } catch {
1887
+ this.toast('下载失败', false);
1888
+ }
1889
+ }
1890
+
1591
1891
  /**
1592
1892
  * Long-press save layer. Inside a WebView this is the only universally available path for
1593
1893
  * saving or copying an image — the system's own long-press menu already offers "save image"
@@ -1633,11 +1933,16 @@
1633
1933
  /** Download every card, one at a time. Serial — running them in parallel trips the
1634
1934
  browser's multiple-download blocker. */
1635
1935
  async downloadAll(onProgress) {
1936
+ if (!(csIsMobile && csInAppWebView) && (await window.__miaodaDownloadPolicy.check()) === true) {
1937
+ this.toast(CS_DOWNLOAD_BLOCKED_TIP, false);
1938
+ return false;
1939
+ }
1636
1940
  const cards = this.cards();
1637
1941
  for (let i = 0; i < cards.length; i++) {
1638
1942
  if (onProgress) onProgress(i + 1, cards.length);
1639
1943
  await this.downloadCard(Number(cards[i].dataset.cardIndex));
1640
1944
  }
1945
+ return true;
1641
1946
  }
1642
1947
 
1643
1948
  // —— The header above each card: editable label + download + expand ——
@@ -1673,14 +1978,23 @@
1673
1978
  more.innerHTML = MORE_SVG;
1674
1979
  more.title = '更多';
1675
1980
  let menu = null;
1676
- const closeMenu = () => { if (menu) { menu.remove(); menu = null; } };
1981
+ let offMenuPolicy = null;
1982
+ const closeMenu = () => {
1983
+ if (offMenuPolicy) { offMenuPolicy(); offMenuPolicy = null; }
1984
+ if (menu) { menu.remove(); menu = null; }
1985
+ };
1986
+ head._closeMenu = closeMenu;
1677
1987
  more.onclick = (e) => {
1678
1988
  e.stopPropagation();
1679
1989
  if (menu) { closeMenu(); return; }
1680
1990
  menu = document.createElement('div');
1681
1991
  menu.className = 'cs-menu';
1682
- menu.append(...this.buildMenuItems(Number(section.dataset.cardIndex), closeMenu));
1992
+ menu.append(...this.buildMenuItems(Number(section.dataset.cardIndex), closeMenu, (off) => {
1993
+ offMenuPolicy = off;
1994
+ }));
1683
1995
  head.appendChild(menu);
1996
+ const dlBtn = menu.querySelector('button[data-download-blocked="true"]');
1997
+ if (dlBtn) alignCsTooltip(dlBtn);
1684
1998
  };
1685
1999
  addEventListener('pointerdown', (e) => {
1686
2000
  if (menu && !head.contains(e.target)) closeMenu();
@@ -1777,7 +2091,10 @@
1777
2091
  dropCard(section) {
1778
2092
  if (this.focusIndex === Number(section.dataset.cardIndex)) this.closeFocus();
1779
2093
  const head = this.headFor && this.headFor.get(section);
1780
- if (head) head.remove();
2094
+ if (head) {
2095
+ if (head._closeMenu) head._closeMenu();
2096
+ head.remove();
2097
+ }
1781
2098
  if (this.headFor) this.headFor.delete(section);
1782
2099
  section.remove();
1783
2100
 
@@ -1826,11 +2143,11 @@
1826
2143
  }
1827
2144
  }
1828
2145
 
1829
- /** Result feedback. One node is reused, so rapid clicks do not stack overlays */
1830
2146
  toast(text, ok = true) {
1831
2147
  if (!this._toast) {
1832
2148
  this._toast = document.createElement('div');
1833
2149
  this._toast.className = 'cs-toast';
2150
+ this._toast.setAttribute('role', 'status');
1834
2151
  document.body.appendChild(csChrome(this._toast));
1835
2152
  }
1836
2153
  const el = this._toast;
@@ -2121,13 +2438,15 @@
2121
2438
  const dl = document.createElement('button');
2122
2439
  dl.innerHTML = DOWNLOAD_M_SVG;
2123
2440
  dl.setAttribute('aria-label', '下载');
2124
- dl.onclick = () => withBusy(dl, async () => {
2125
- try {
2126
- if (await this.downloadCard(this.page)) this.toast('图片下载成功');
2127
- } catch {
2128
- this.toast('下载失败', false);
2441
+ if (this._offMobilePolicy) { this._offMobilePolicy(); this._offMobilePolicy = null; }
2442
+ this._offMobilePolicy = bindCsDownloadButton(dl);
2443
+ dl.onclick = () => {
2444
+ if (dl.getAttribute('aria-disabled') === 'true') {
2445
+ this.toast(CS_DOWNLOAD_BLOCKED_TIP, false);
2446
+ return;
2129
2447
  }
2130
- });
2448
+ return withBusy(dl, () => this.downloadCardWithFeedback(this.page));
2449
+ };
2131
2450
  acts.appendChild(dl);
2132
2451
  bar.appendChild(acts);
2133
2452
  document.body.appendChild(csChrome(bar));
@@ -2246,17 +2565,19 @@
2246
2565
  * times would inevitably drift (the delete confirmation is the easiest thing to end up
2247
2566
  * wired in only one of them).
2248
2567
  */
2249
- buildMenuItems(n, closeMenu) {
2568
+ buildMenuItems(n, closeMenu, onCleanup) {
2250
2569
  const dl = document.createElement('button');
2251
2570
  dl.textContent = '下载';
2252
- dl.onclick = async (e) => {
2571
+ const offPolicy = bindCsDownloadButton(dl);
2572
+ if (onCleanup) onCleanup(offPolicy);
2573
+ dl.onclick = (e) => {
2253
2574
  e.stopPropagation();
2254
- closeMenu();
2255
- try {
2256
- if (await this.downloadCard(n)) this.toast('图片下载成功');
2257
- } catch {
2258
- this.toast('下载失败', false);
2575
+ if (dl.getAttribute('aria-disabled') === 'true') {
2576
+ e.preventDefault();
2577
+ return;
2259
2578
  }
2579
+ closeMenu();
2580
+ return this.downloadCardWithFeedback(n);
2260
2581
  };
2261
2582
 
2262
2583
  const cp = document.createElement('button');
@@ -2289,17 +2610,22 @@
2289
2610
  this.closeContextMenu();
2290
2611
  const menu = document.createElement('div');
2291
2612
  menu.className = 'cs-menu cs-ctx';
2292
- menu.append(...this.buildMenuItems(n, () => this.closeContextMenu()));
2613
+ menu.append(...this.buildMenuItems(n, () => this.closeContextMenu(), (off) => {
2614
+ this._offCtxPolicy = off;
2615
+ }));
2293
2616
  menu.addEventListener('pointerdown', (e) => e.stopPropagation());
2294
2617
  document.body.appendChild(csChrome(menu));
2295
2618
  // Attach before measuring, so the menu can be clamped inside the viewport
2296
2619
  const r = menu.getBoundingClientRect();
2297
2620
  menu.style.left = Math.max(8, Math.min(x, innerWidth - r.width - 8)) + 'px';
2298
2621
  menu.style.top = Math.max(8, Math.min(y, innerHeight - r.height - 8)) + 'px';
2622
+ const dlBtn = menu.querySelector('button[data-download-blocked="true"]');
2623
+ if (dlBtn) alignCsTooltip(dlBtn);
2299
2624
  this._ctxMenu = menu;
2300
2625
  }
2301
2626
 
2302
2627
  closeContextMenu() {
2628
+ if (this._offCtxPolicy) { this._offCtxPolicy(); this._offCtxPolicy = null; }
2303
2629
  if (this._ctxMenu) this._ctxMenu.remove();
2304
2630
  this._ctxMenu = null;
2305
2631
  }
@@ -2392,13 +2718,11 @@
2392
2718
  const zoomIn = mk(ZOOM_IN_SVG, '放大', () => this.setFocusZoom(this.focusZoom * 1.25));
2393
2719
 
2394
2720
  const copy = mk(COPY_SVG, '复制图片', (b) => withBusy(b, () => this.copyCard(this.focusIndex)));
2395
- const download = mk(DOWNLOAD_M_SVG, '下载', (b) => withBusy(b, async () => {
2396
- try {
2397
- if (await this.downloadCard(this.focusIndex)) this.toast('图片下载成功');
2398
- } catch {
2399
- this.toast('下载失败', false);
2400
- }
2401
- }));
2721
+ const download = mk(DOWNLOAD_M_SVG, '下载', (b) => {
2722
+ if (b.getAttribute('aria-disabled') === 'true') return;
2723
+ withBusy(b, () => this.downloadCardWithFeedback(this.focusIndex));
2724
+ });
2725
+ this._offFocusPolicy = bindCsDownloadButton(download, '下载');
2402
2726
 
2403
2727
  const sep = () => {
2404
2728
  const s = document.createElement('span');
@@ -2457,6 +2781,7 @@
2457
2781
 
2458
2782
  closeFocus() {
2459
2783
  this.closeContextMenu();
2784
+ if (this._offFocusPolicy) { this._offFocusPolicy(); this._offFocusPolicy = null; }
2460
2785
  const wasOpen = !!this.overlay;
2461
2786
  if (this.overlay) this.overlay.remove();
2462
2787
  this.overlay = null;
@@ -143,6 +143,162 @@
143
143
  });
144
144
  }
145
145
 
146
+ // ── Download policy singleton ──────────────────────────────────────────────
147
+ // Shared by every buildless script on the page (first one to load defines
148
+ // it). Inlined per script (same convention as __miaodaMirror) so copy-in
149
+ // artifacts never break from a missing helper <script>. Keep every inlined
150
+ // copy identical.
151
+ if (!window.__miaodaDownloadPolicy) {
152
+ const REQ_TYPE = 'miaoda:preview:download-policy-request';
153
+ const RES_TYPE = 'miaoda:preview:download-policy';
154
+ const TIMEOUT_MS = 200;
155
+ const listeners = new Set();
156
+ let state = null; // null (unprobed) | 'unknown' | boolean
157
+ let inflight = null;
158
+ let cancelInflight = null;
159
+ let retried = false;
160
+ let seq = 0;
161
+
162
+ const notify = () => {
163
+ for (const fn of Array.from(listeners)) {
164
+ try {
165
+ fn(state);
166
+ } catch {}
167
+ }
168
+ };
169
+
170
+ const queryOnce = () => {
171
+ if (typeof state === 'boolean') return Promise.resolve(state);
172
+ if (inflight) return inflight;
173
+ let parentWin = null;
174
+ try {
175
+ parentWin = window.parent;
176
+ } catch {
177
+ parentWin = null;
178
+ }
179
+ if (!parentWin || parentWin === window) {
180
+ state = false;
181
+ notify();
182
+ return Promise.resolve(false);
183
+ }
184
+ const requestId = `dp-${++seq}-${Math.random().toString(36).slice(2, 8)}`;
185
+ inflight = new Promise((resolve) => {
186
+ let settled = false;
187
+ let timer = null;
188
+ const cleanup = () => {
189
+ if (timer !== null) {
190
+ clearTimeout(timer);
191
+ timer = null;
192
+ }
193
+ window.removeEventListener('message', onMessage);
194
+ inflight = null;
195
+ cancelInflight = null;
196
+ };
197
+ const finish = (value) => {
198
+ if (settled) return;
199
+ settled = true;
200
+ cleanup();
201
+ state = value;
202
+ notify();
203
+ resolve(value);
204
+ };
205
+ const onMessage = (e) => {
206
+ if (e.source !== parentWin) return;
207
+ const d = e.data;
208
+ if (!d || d.type !== RES_TYPE || d.requestId !== requestId) return;
209
+ if (typeof d.blockedBySandbox !== 'boolean') return;
210
+ finish(d.blockedBySandbox);
211
+ };
212
+ cancelInflight = () => {
213
+ if (settled) return;
214
+ settled = true;
215
+ cleanup();
216
+ resolve('unknown');
217
+ };
218
+ window.addEventListener('message', onMessage);
219
+ timer = setTimeout(() => finish('unknown'), TIMEOUT_MS);
220
+ try {
221
+ parentWin.postMessage({ type: REQ_TYPE, requestId }, '*');
222
+ } catch {
223
+ finish('unknown');
224
+ }
225
+ });
226
+ return inflight;
227
+ };
228
+
229
+ window.__miaodaDownloadPolicy = {
230
+ prime() {
231
+ if (state !== null) return Promise.resolve(state);
232
+ return queryOnce();
233
+ },
234
+ isBlocked() {
235
+ return state === true;
236
+ },
237
+ subscribe(fn) {
238
+ listeners.add(fn);
239
+ return () => {
240
+ listeners.delete(fn);
241
+ };
242
+ },
243
+ async check() {
244
+ if (typeof state === 'boolean') return state;
245
+ if (inflight) return inflight;
246
+ if (state === 'unknown' && retried) return 'unknown';
247
+ if (state === 'unknown') retried = true;
248
+ return queryOnce();
249
+ },
250
+ reset() {
251
+ if (cancelInflight) cancelInflight();
252
+ state = null;
253
+ inflight = null;
254
+ retried = false;
255
+ notify();
256
+ },
257
+ };
258
+ }
259
+ void window.__miaodaDownloadPolicy.prime();
260
+ const DC_DOWNLOAD_BLOCKED_TIP = '互联网公开时不可下载,请切换分享范围';
261
+ const dcAlignTooltip = (btn) => {
262
+ if (!btn || btn.getAttribute('data-download-blocked') !== 'true') return;
263
+ const rect = btn.getBoundingClientRect();
264
+ const vw = window.innerWidth || document.documentElement.clientWidth || 0;
265
+ const vh = window.innerHeight || document.documentElement.clientHeight || 0;
266
+ if (!vw || !rect.width) return;
267
+ const margin = 8;
268
+ const maxW = Math.min(260, Math.max(60, vw - margin * 2));
269
+ const wrap = maxW < 252;
270
+ const estW = Math.min(maxW, 252);
271
+ const center = rect.left + rect.width / 2;
272
+ let left = center - estW / 2;
273
+ if (left < margin) left = margin;
274
+ if (left + estW > vw - margin) left = Math.max(margin, vw - margin - estW);
275
+ const shift = Math.round(left - (center - estW / 2));
276
+ btn.style.setProperty('--tt-shift', `${shift}px`);
277
+ btn.style.setProperty('--tt-max-w', `${Math.floor(maxW)}px`);
278
+ if (wrap) btn.setAttribute('data-tooltip-wrap', 'true');
279
+ else btn.removeAttribute('data-tooltip-wrap');
280
+ const tipLen = (btn.getAttribute('data-tooltip') || DC_DOWNLOAD_BLOCKED_TIP).length || 18;
281
+ const innerW = Math.max(24, maxW - 20);
282
+ const estLines = wrap
283
+ ? Math.max(1, Math.ceil(tipLen / Math.max(1, Math.floor(innerW / 12))))
284
+ : 1;
285
+ let tooltipH = Math.ceil(estLines * 17 + 12);
286
+ try {
287
+ const measuredH = parseFloat(getComputedStyle(btn, '::after').height);
288
+ if (Number.isFinite(measuredH) && measuredH > 0) {
289
+ tooltipH = Math.max(tooltipH, Math.ceil(measuredH));
290
+ }
291
+ } catch {}
292
+ const neededH = tooltipH + 8;
293
+ const spaceAbove = rect.top - margin;
294
+ const spaceBelow = vh ? vh - rect.bottom - margin : Infinity;
295
+ if (spaceAbove < neededH && spaceBelow >= spaceAbove) {
296
+ btn.setAttribute('data-tooltip-placement', 'bottom');
297
+ } else {
298
+ btn.removeAttribute('data-tooltip-placement');
299
+ }
300
+ };
301
+
146
302
  /**
147
303
  * The React version lives in the light DOM, so its box model comes from the
148
304
  * product's own `*` reset (most products set border-box). That reset never
@@ -201,11 +357,32 @@
201
357
  border-radius:6px;font-family:inherit;font-size:14px;font-weight:400;line-height:24px;
202
358
  color:#1F2329;cursor:pointer;text-align:left;transition:background .12s;white-space:nowrap}
203
359
  .dc-menu button:hover{background:rgba(31,35,41,0.05)}
360
+ .dc-menu button[data-download-blocked="true"]{position:relative;color:#8F959E;cursor:not-allowed}
361
+ .dc-menu button[data-download-blocked="true"]:hover{background:transparent}
362
+ .dc-menu button[data-download-blocked="true"]:hover::before,.dc-menu button[data-download-blocked="true"]:focus-visible::before{
363
+ content:"";position:absolute;bottom:calc(100% + 3px);left:50%;transform:translateX(-50%);z-index:30;
364
+ border:5px solid transparent;border-top-color:#1F2329;border-bottom:0;pointer-events:none}
365
+ .dc-menu button[data-download-blocked="true"]:hover::after,.dc-menu button[data-download-blocked="true"]:focus-visible::after{
366
+ content:attr(data-tooltip);position:absolute;bottom:calc(100% + 8px);left:50%;transform:translateX(calc(-50% + var(--tt-shift,0px)));z-index:30;
367
+ width:max-content;max-width:var(--tt-max-w,260px);box-sizing:border-box;padding:6px 10px;border-radius:6px;background:#1F2329;color:#fff;
368
+ font-family:inherit;font-size:12px;font-weight:400;line-height:1.4;white-space:nowrap;
369
+ box-shadow:0 4px 12px rgba(0,0,0,.18);pointer-events:none}
370
+ .dc-menu button[data-download-blocked="true"][data-tooltip-wrap="true"]:hover::after,
371
+ .dc-menu button[data-download-blocked="true"][data-tooltip-wrap="true"]:focus-visible::after{white-space:normal}
372
+ .dc-menu button[data-download-blocked="true"][data-tooltip-placement="bottom"]:hover::before,
373
+ .dc-menu button[data-download-blocked="true"][data-tooltip-placement="bottom"]:focus-visible::before{
374
+ bottom:auto;top:calc(100% + 3px);border-top:0;border-bottom:5px solid #1F2329}
375
+ .dc-menu button[data-download-blocked="true"][data-tooltip-placement="bottom"]:hover::after,
376
+ .dc-menu button[data-download-blocked="true"][data-tooltip-placement="bottom"]:focus-visible::after{
377
+ bottom:auto;top:calc(100% + 8px)}
204
378
  .dc-menu .dc-danger{color:#F54A45}
205
379
  `;
206
380
 
207
381
  const CANVAS_CSS = `
208
382
  :host{display:block}
383
+ .dc-export-status:not(:empty){position:absolute;top:calc(16px + env(safe-area-inset-top,0px));left:50%;transform:translateX(-50%);z-index:101;
384
+ width:max-content;max-width:calc(100% - 32px);box-sizing:border-box;pointer-events:none;background:#fff;color:#1F2329;
385
+ padding:10px 16px;border-radius:12px;font-size:14px;line-height:1.4;box-shadow:0 4px 16px rgba(31,35,41,.12)}
209
386
  .dc-editable{cursor:text;outline:none;white-space:nowrap;border-radius:4px;padding:0 2px;margin:0 -2px}
210
387
  .dc-editable:focus{background:#fff;box-shadow:0 0 0 1px #336DF4}
211
388
  .dc-menu{position:absolute;top:100%;right:0;margin-top:4px;background:#fff;border-radius:8px;border:1px solid #DEE0E3;
@@ -378,7 +555,22 @@
378
555
  this.style.display = 'block';
379
556
  this._render();
380
557
  }
558
+ _cleanupMenu() {
559
+ this._confirming = false;
560
+ if (this._offPolicy) {
561
+ this._offPolicy();
562
+ this._offPolicy = null;
563
+ }
564
+ if (this._offMenu) {
565
+ document.removeEventListener('pointerdown', this._offMenu, true);
566
+ this._offMenu = null;
567
+ }
568
+ }
569
+ disconnectedCallback() {
570
+ this._cleanupMenu();
571
+ }
381
572
  _render() {
573
+ this._cleanupMenu();
382
574
  const chromeless = this.hasAttribute('chromeless');
383
575
  const width = numAttr(this, 'width', 260);
384
576
  const hasHeight = this.hasAttribute('height');
@@ -451,20 +643,50 @@
451
643
  const open = wrap.querySelector('.dc-menu');
452
644
  if (open) {
453
645
  open.remove();
454
- this._confirming = false;
455
- document.removeEventListener('pointerdown', this._offMenu, true);
646
+ this._cleanupMenu();
456
647
  return;
457
648
  }
458
- this._confirming = false;
649
+ this._cleanupMenu();
459
650
  const menu = document.createElement('div');
460
651
  menu.className = 'dc-menu';
461
652
  menu.innerHTML =
462
653
  '<button data-act="png">下载 PNG</button><button data-act="html">下载 HTML</button>' +
463
654
  '<button class="dc-danger" data-act="del">删除</button>';
655
+ const syncMenuDownloads = () => {
656
+ const blocked = window.__miaodaDownloadPolicy.isBlocked();
657
+ menu.querySelectorAll('button[data-act="png"], button[data-act="html"]').forEach((btn) => {
658
+ if (blocked) {
659
+ btn.setAttribute('aria-disabled', 'true');
660
+ btn.setAttribute('data-download-blocked', 'true');
661
+ btn.setAttribute('data-tooltip', DC_DOWNLOAD_BLOCKED_TIP);
662
+ dcAlignTooltip(btn);
663
+ } else {
664
+ btn.removeAttribute('aria-disabled');
665
+ btn.removeAttribute('data-download-blocked');
666
+ btn.removeAttribute('data-tooltip');
667
+ btn.removeAttribute('data-tooltip-wrap');
668
+ btn.removeAttribute('data-tooltip-placement');
669
+ btn.style.removeProperty('--tt-shift');
670
+ btn.style.removeProperty('--tt-max-w');
671
+ }
672
+ });
673
+ };
674
+ syncMenuDownloads();
675
+ menu.querySelectorAll('button[data-act="png"], button[data-act="html"]').forEach((btn) => {
676
+ btn.addEventListener('pointerenter', () => dcAlignTooltip(btn));
677
+ btn.addEventListener('focus', () => dcAlignTooltip(btn));
678
+ });
679
+ void window.__miaodaDownloadPolicy.prime();
680
+ this._offPolicy = window.__miaodaDownloadPolicy.subscribe(syncMenuDownloads);
464
681
  menu.addEventListener('pointerdown', (e) => e.stopPropagation());
465
682
  menu.addEventListener('click', (e) => {
466
- const act = e.target.closest('button')?.dataset.act;
683
+ const btn = e.target.closest('button');
684
+ const act = btn?.dataset.act;
467
685
  if (act === 'png' || act === 'html') {
686
+ if (btn.getAttribute('aria-disabled') === 'true') {
687
+ e.preventDefault();
688
+ return;
689
+ }
468
690
  this._toggleMenu();
469
691
  this._export(act);
470
692
  } else if (act === 'del') {
@@ -474,11 +696,12 @@
474
696
  this.emit('dc:delete', { slotId: this.slotId });
475
697
  } else {
476
698
  this._confirming = true;
477
- e.target.closest('button').textContent = '确认删除';
699
+ btn.textContent = '确认删除';
478
700
  }
479
701
  }
480
702
  });
481
703
  wrap.appendChild(menu);
704
+ menu.querySelectorAll('button[data-download-blocked="true"]').forEach(dcAlignTooltip);
482
705
  // Attach immediately and use composedPath to tell whether the click landed
483
706
  // inside the menu. Deferring with setTimeout would never fire under fake
484
707
  // timers, leaving the listener unattached and the menu permanently open.
@@ -491,21 +714,43 @@
491
714
  };
492
715
  document.addEventListener('pointerdown', this._offMenu, true);
493
716
  }
494
- _export(kind) {
495
- const card = this.shadowRoot.querySelector('.dc-card');
717
+ _isActiveInCanvas() {
718
+ if (!this.isConnected || this.hasAttribute('data-dc-hidden') || !this.hasAttribute('data-dc-slot')) {
719
+ return false;
720
+ }
721
+ const section = this.closest('dc-section');
722
+ if (section && !section.currentOrder().includes(this.slotId)) return false;
723
+ return true;
724
+ }
725
+ async _export(kind) {
726
+ if (!this._isActiveInCanvas()) return;
727
+ const card = this.shadowRoot?.querySelector('.dc-card');
496
728
  if (!card) return;
729
+ const canvas = this.closest('design-canvas');
730
+ if ((await window.__miaodaDownloadPolicy.check()) === true) {
731
+ if (this._isActiveInCanvas()) canvas?.showExportStatus(DC_DOWNLOAD_BLOCKED_TIP);
732
+ return;
733
+ }
734
+ if (!this._isActiveInCanvas()) return;
735
+ const currentCard = this.shadowRoot?.querySelector('.dc-card');
736
+ if (!currentCard || !currentCard.isConnected) return;
497
737
  // Unicode-friendly filename scrub: keep letters (CJK included), digits,
498
738
  // whitespace and . _ -
499
739
  const name = String(
500
740
  this._label || this.attr('label', '') || this.slotId || 'artboard',
501
741
  ).replace(/[^\p{L}\p{N}\s._-]+/gu, '_');
502
- dcExport(
503
- card,
504
- card.offsetWidth || numAttr(this, 'width', 260),
505
- card.offsetHeight || numAttr(this, 'height', 0),
506
- name,
507
- kind,
508
- ).catch((e) => console.error('[design-canvas] export failed:', e));
742
+ try {
743
+ await dcExport(
744
+ currentCard,
745
+ currentCard.offsetWidth || numAttr(this, 'width', 260),
746
+ currentCard.offsetHeight || numAttr(this, 'height', 0),
747
+ name,
748
+ kind,
749
+ );
750
+ } catch (e) {
751
+ console.error('[design-canvas] export failed:', e);
752
+ canvas?.showExportStatus('导出失败,请重试');
753
+ }
509
754
  }
510
755
  /**
511
756
  * Drag to reorder: the dragged card follows the pointer, the others make room
@@ -871,7 +1116,6 @@
871
1116
 
872
1117
  const xml = new XMLSerializer().serializeToString(clone);
873
1118
  const save = (blob, ext) => {
874
- if (!blob) return;
875
1119
  const a = document.createElement('a');
876
1120
  a.href = URL.createObjectURL(blob);
877
1121
  a.download = name + '.' + ext;
@@ -922,7 +1166,9 @@
922
1166
  cv.width = w * scale;
923
1167
  cv.height = h * scale;
924
1168
  cv.getContext('2d').drawImage(img, 0, 0);
925
- cv.toBlob((blob) => save(blob, 'png'), 'image/png');
1169
+ const blob = await new Promise((resolve) => cv.toBlob(resolve, 'image/png'));
1170
+ if (!blob) throw new Error('PNG encoding failed');
1171
+ save(blob, 'png');
926
1172
  }
927
1173
 
928
1174
  const DC_STATE_FILE = '.design-canvas.state.json';
@@ -1394,6 +1640,7 @@
1394
1640
  }
1395
1641
 
1396
1642
  disconnectedCallback() {
1643
+ clearTimeout(this._exportStatusTimer);
1397
1644
  for (const off of this._mirrorOffs || []) off();
1398
1645
  this._mirrorOffs = [];
1399
1646
  clearTimeout(this._mirrorEmitT);
@@ -1440,6 +1687,7 @@
1440
1687
  them out via a static dcOverlay marker on the component, which does not
1441
1688
  survive the custom-element boundary. -->
1442
1689
  <slot name="overlay"></slot>
1690
+ <div class="dc-export-status" role="status" data-miaoda-chrome=""></div>
1443
1691
  </div>`;
1444
1692
  this.vp = this.shadowRoot.querySelector('.design-canvas');
1445
1693
  this.world = this.shadowRoot.querySelector('.dc-world');
@@ -2150,6 +2398,15 @@
2150
2398
  );
2151
2399
  }
2152
2400
 
2401
+ showExportStatus(message) {
2402
+ const status = this.shadowRoot.querySelector('.dc-export-status');
2403
+ status.textContent = message;
2404
+ clearTimeout(this._exportStatusTimer);
2405
+ this._exportStatusTimer = setTimeout(() => {
2406
+ status.textContent = '';
2407
+ }, 3500);
2408
+ }
2409
+
2153
2410
  _bindChildEvents() {
2154
2411
  this.addEventListener('dc:rename-section', (e) => {
2155
2412
  e.stopPropagation();