Skip to content

Turn any idea, plan, or codebase into a beautiful interactive diagram. An agent skill for Claude Code, Codex, and more.

fix(viewer): preserve embedded reading addresses and clipboard policy

HengYang5d2a7237a4aa
diff --git a/archify/assets/template.html b/archify/assets/template.html
index 5e07671c..5e390912 100644
--- a/archify/assets/template.html
+++ b/archify/assets/template.html
@@ -5362,6 +5362,38 @@ OTHER DEALINGS IN THE FONT SOFTWARE.
.replace(/\b\w/g, function (letter) { return letter.toUpperCase(); });
}
+ function readerLink(state) {
+ var template = document.documentElement.getAttribute('data-reading-link-template');
+ if (template === null) return location.href.replace(/#.*$/, '') + '#' + state;
+ if (!template || template.length > 4096 || template.split('{state}').length !== 2) return null;
+ try {
+ var url = new URL(template.replace('{state}', encodeURIComponent(state)));
+ if (['http:', 'https:', 'file:'].indexOf(url.protocol) === -1 || url.username || url.password) return null;
+ return url.href;
+ } catch (_) { return null; }
+ }
+
+ function copyReaderText(value) {
+ function fallbackCopy() {
+ var field = document.createElement('textarea');
+ field.value = value;
+ field.setAttribute('readonly', '');
+ field.style.position = 'fixed';
+ field.style.opacity = '0';
+ document.body.appendChild(field);
+ field.select();
+ var copied = false;
+ try { copied = document.execCommand('copy'); } catch (_) {}
+ field.remove();
+ return copied;
+ }
+ var policy = document.permissionsPolicy || document.featurePolicy;
+ var allowed = !policy || typeof policy.allowsFeature !== 'function' || policy.allowsFeature('clipboard-write');
+ return allowed && navigator.clipboard && typeof navigator.clipboard.writeText === 'function'
+ ? navigator.clipboard.writeText(value).then(function () { return true; }).catch(fallbackCopy)
+ : Promise.resolve(fallbackCopy());
+ }
+
function hasDrawableGeometry(element) {
if (!element || element.hasAttribute('data-ambient-flow-overlay')) return false;
var geometries = /^(path|line|polyline)$/i.test(element.tagName)
@@ -8963,31 +8995,15 @@ OTHER DEALINGS IN THE FONT SOFTWARE.
return setMany([id], options);
}
- function fallbackCopy(value) {
- var field = document.createElement('textarea');
- field.value = value;
- field.setAttribute('readonly', '');
- field.style.position = 'fixed';
- field.style.opacity = '0';
- document.body.appendChild(field);
- field.select();
- var copied = false;
- try { copied = document.execCommand('copy'); } catch (_) {}
- field.remove();
- return copied;
- }
-
function copyFocusLink() {
if (activeIds.length !== 1) return Promise.resolve(false);
var record = pinnedRelationshipRecord();
var relationId = record && record.id;
- var value = location.href.replace(/#.*$/, '') + (relationId
- ? '#relation=' + encodeURIComponent(relationId)
- : '#focus=' + encodeURIComponent(activeIds[0]) + (reachabilityMode ? '&reach=' + reachabilityMode : ''));
- var copy = navigator.clipboard && typeof navigator.clipboard.writeText === 'function'
- ? navigator.clipboard.writeText(value).then(function () { return true; }).catch(function () { return fallbackCopy(value); })
- : Promise.resolve(fallbackCopy(value));
- return copy.then(function (copied) {
+ var value = readerLink(relationId
+ ? 'relation=' + encodeURIComponent(relationId)
+ : 'focus=' + encodeURIComponent(activeIds[0]) + (reachabilityMode ? '&reach=' + reachabilityMode : ''));
+ if (value === null) return Promise.resolve(false);
+ return copyReaderText(value).then(function (copied) {
copyBtn.textContent = viewerText(copied ? 'viewer.common.copied' : 'viewer.common.copyFailed');
copyBtn.setAttribute('aria-label', copied
? viewerText(relationId ? 'viewer.passport.copy.pinned.success' : 'viewer.passport.copy.focused.success')
@@ -12917,26 +12933,11 @@ OTHER DEALINGS IN THE FONT SOFTWARE.
if (!context || !Archify.finder) return false;
return Archify.finder.open({ context: context });
}
- function fallbackCopy(value) {
- var field = document.createElement('textarea');
- field.value = value;
- field.setAttribute('readonly', '');
- field.style.position = 'fixed';
- field.style.opacity = '0';
- document.body.appendChild(field);
- field.select();
- var copied = false;
- try { copied = document.execCommand('copy'); } catch (_) {}
- field.remove();
- return copied;
- }
function copyLink() {
if (mode !== 'result') return Promise.resolve(false);
- var value = location.href.replace(/#.*$/, '') + '#route=' + encodeURIComponent(startId) + '~' + encodeURIComponent(endId);
- var copy = navigator.clipboard && typeof navigator.clipboard.writeText === 'function'
- ? navigator.clipboard.writeText(value).then(function () { return true; }).catch(function () { return fallbackCopy(value); })
- : Promise.resolve(fallbackCopy(value));
- return copy.then(function (copied) {
+ var value = readerLink('route=' + encodeURIComponent(startId) + '~' + encodeURIComponent(endId));
+ if (value === null) return Promise.resolve(false);
+ return copyReaderText(value).then(function (copied) {
copyBtn.textContent = viewerText(copied ? 'viewer.common.copied' : 'viewer.common.copyFailed');
copyBtn.setAttribute('aria-label', viewerText(copied ? 'viewer.route.copy.success' : 'viewer.route.copy.failed'));
window.setTimeout(function () {
@@ -13588,26 +13589,11 @@ OTHER DEALINGS IN THE FONT SOFTWARE.
if (options.closePanel === true) close({ restoreFocus: false });
return false;
}
- function fallbackCopy(value) {
- var field = document.createElement('textarea');
- field.value = value;
- field.setAttribute('readonly', '');
- field.style.position = 'fixed';
- field.style.opacity = '0';
- document.body.appendChild(field);
- field.select();
- var copied = false;
- try { copied = document.execCommand('copy'); } catch (_) {}
- field.remove();
- return copied;
- }
function copyLink() {
if (!selectedKinds.length) return Promise.resolve(false);
- var value = location.href.replace(/#.*$/, '') + '#lens=' + selectedKinds.map(encodeURIComponent).join('~');
- var copy = navigator.clipboard && typeof navigator.clipboard.writeText === 'function'
- ? navigator.clipboard.writeText(value).then(function () { return true; }).catch(function () { return fallbackCopy(value); })
- : Promise.resolve(fallbackCopy(value));
- return copy.then(function (copied) {
+ var value = readerLink('lens=' + selectedKinds.map(encodeURIComponent).join('~'));
+ if (value === null) return Promise.resolve(false);
+ return copyReaderText(value).then(function (copied) {
copyBtn.textContent = viewerText(copied ? 'viewer.common.copied' : 'viewer.common.copyFailed');
window.setTimeout(function () { copyBtn.textContent = viewerText('viewer.common.copyLink'); }, 1600);
return copied;
diff --git a/archify/references/viewer-runtime.md b/archify/references/viewer-runtime.md
index 547b026a..ef81a7a5 100644
--- a/archify/references/viewer-runtime.md
+++ b/archify/references/viewer-runtime.md
@@ -14,6 +14,21 @@ Read this only when the user asks for a reader-facing capability. Ordinary gener
- Direct Relationship Pin makes a unique compiled relationship operable while preserving the authored line and stable relationship identity. It must fail closed on conflicting source/target/label/ID metadata.
- Route Probe resolves exactly two endpoints over authored directed relationships. It never infers a route from geometry.
+## Embedded reading addresses
+
+A host displaying the native reader in an opaque `srcdoc` frame may set
+`data-reading-link-template` on that reader's `html` element. Supply an absolute
+HTTP, HTTPS or file URL containing exactly one `{state}` marker, for example
+`https://example.test/architecture#page=mechanism&reader={state}`. Native Focus,
+Relationship, Reach, Route and Lens copy actions replace the marker with their
+percent-encoded opaque query state. The host keeps its page identity and restores
+that value as the native frame's hash; it never parses or reconstructs queries.
+
+Absent configuration preserves standalone links. Invalid, credential-bearing or
+unsupported URL templates make copying fail without accessing the clipboard.
+This seam changes copied addresses only, not query parsing, history, permissions,
+embedding isolation or authored geometry. It adds no network or storage surface.
+
## Motion and presentation
Every rendered diagram enables reader-controlled Live/Still motion by default. In Live, connection flow repeats on a separate Viewer overlay while the original line styles and arrowheads remain intact. Still stops the flow; resuming Live starts it again. Semantic exploration temporarily owns the motion budget, and continuous flow resumes when that action releases it. Diagrams without connections retain their bounded node entrance rather than inventing a flow. Omit `meta.animation`; historical `"trace"` and `"none"` values remain accepted for input compatibility and do not change this default. Reduced motion, page hiding, print, and canonical export preserve complete static meaning. Presentation Stage changes viewer chrome and framing, never authored geometry. This is not a mobile product feature; narrow layouts get containment only.
diff --git a/scripts/browser-test-inventory.mjs b/scripts/browser-test-inventory.mjs
index 76836bfa..5a6ef58b 100644
--- a/scripts/browser-test-inventory.mjs
+++ b/scripts/browser-test-inventory.mjs
@@ -22,6 +22,7 @@ export const browserTestFiles = [
'finder-browser.test.mjs',
'intent-trace-browser.test.mjs',
'semantic-lens-browser.test.mjs',
+ 'reading-address-browser.test.mjs',
'route-probe-browser.test.mjs',
'focus-browser.test.mjs',
'crossover-state-browser.test.mjs',
diff --git a/test/reading-address-browser.test.mjs b/test/reading-address-browser.test.mjs
new file mode 100644
index 00000000..1b097b9e
--- /dev/null
+++ b/test/reading-address-browser.test.mjs
@@ -0,0 +1,157 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+import { applyTemplate } from '../archify/renderers/shared/utils.mjs';
+import { findChrome } from '../archify/bin/visual-check.mjs';
+import { desktopBrowser, desktopPointerCheck } from './helpers/desktop-browser.mjs';
+
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const chrome = process.env.ARCHIFY_CHROME ? findChrome() : null;
+
+test('native copy links preserve a host page and opaque reader state without changing standalone links', {
+ skip: chrome ? false : 'Set ARCHIFY_CHROME for the native address regression.',
+}, async (t) => {
+ const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-reading-address-'));
+ t.after(() => fs.rmSync(scratch, { recursive: true, force: true }));
+ const template = fs.readFileSync(path.join(root, 'archify/assets/template.html'), 'utf8');
+ const html = applyTemplate(template, {
+ title: 'Reading address', subtitle: 'Native state stays opaque to the host.', cards: '',
+ svg: `<svg viewBox="0 0 600 360" role="img" aria-label="Directed graph">
+ <g data-node-id="source" data-node-label="Source" data-node-kind="component" role="button" tabindex="0" aria-pressed="false"><rect x="80" y="60" width="180" height="64" class="c-backend"/><text x="100" y="90" class="t-primary">Source</text></g>
+ <g data-node-id="target" data-node-label="Target" data-node-kind="component" role="button" tabindex="0" aria-pressed="false"><rect x="340" y="60" width="180" height="64" class="c-backend"/><text x="360" y="90" class="t-primary">Target</text></g>
+ <path d="M260 92 H340" class="a-default" data-edge-id="calls" data-edge-key="calls" data-edge-label="Calls" data-edge-from="source" data-edge-to="target"/>
+ </svg>`,
+ });
+ const file = path.join(scratch, 'reader.html');
+ fs.writeFileSync(file, html);
+ const browser = desktopBrowser(chrome);
+ t.after(() => browser.close());
+ const session = await browser.sessionPromise;
+ const pointer = await desktopPointerCheck(browser, session);
+ await browser.inspect({ artifactPath: file, width: 1600, height: 1100,
+ theme: 'light', writeScreenshot: false });
+ await pointer();
+ const run = async (expression, contextId) => {
+ const result = await browser.cdp.send('Runtime.evaluate', {
+ expression, contextId, returnByValue: true, awaitPromise: true,
+ }, session);
+ assert.equal(result.exceptionDetails, undefined, result.exceptionDetails?.text);
+ return result.result.value;
+ };
+ const copy = async (action, contextId, mode = 'reject', fallback = true) => run(`(async () => {
+ const original = document.execCommand;
+ const descriptor = Object.getOwnPropertyDescriptor(navigator, 'clipboard');
+ let text = null, clipboardCalls = 0;
+ Object.defineProperty(navigator, 'clipboard', { configurable: true, value:
+ ${JSON.stringify(mode)} === 'missing' ? undefined : {
+ writeText: value => { clipboardCalls++;
+ if (${JSON.stringify(mode)} !== 'success') return Promise.reject(new Error('denied'));
+ text = value; return Promise.resolve();
+ }
+ }
+ });
+ document.execCommand = command => {
+ if (command !== 'copy') return false;
+ text = document.querySelector('textarea[readonly]')?.value ?? null;
+ return ${JSON.stringify(fallback)};
+ };
+ try { return { copied: await (${action}), text, clipboardCalls,
+ residual: document.querySelectorAll('textarea[readonly]').length }; }
+ finally { document.execCommand = original;
+ if (descriptor) Object.defineProperty(navigator, 'clipboard', descriptor);
+ else delete navigator.clipboard; }
+ })()`, contextId);
+ const states = [
+ ['Archify.focus.set("source", {toggle:false,updateUrl:false})', 'Archify.focus.copyLink()', 'focus=source'],
+ ['Archify.focus.reach("downstream", {reveal:false,updateUrl:false})', 'Archify.focus.copyLink()', 'focus=source&reach=downstream'],
+ ['Archify.focus.inspectRelationshipById("calls", {updateUrl:false})', 'Archify.focus.copyLink()', 'relation=calls'],
+ ['Archify.routeProbe.begin({source:"source",focusNode:false}); Archify.routeProbe.choose("target", {updateUrl:false})', 'Archify.routeProbe.copyLink()', 'route=source~target'],
+ ['Archify.semanticLens.select("component", {updateUrl:false})', 'Archify.semanticLens.copyLink()', 'lens=component'],
+ ];
+ const check = async (contextId, address) => {
+ for (const [setup, action, state] of states) {
+ assert.equal(await run(setup, contextId), true);
+ const result = await copy(action, contextId);
+ assert.equal(result.copied, true);
+ assert.equal(result.residual, 0);
+ assert.equal(result.text, address.includes('&reader=')
+ ? address.replace('{state}', encodeURIComponent(state))
+ : address.replace('{state}', state));
+ }
+ };
+ await check(undefined, pathToFileURL(file).href + '?theme=light#{state}');
+ await run('Archify.focus.set("source", {toggle:false,updateUrl:false})');
+ for (const [mode, fallback, expected, attempts] of [
+ ['success', false, true, 1], ['reject', true, true, 1],
+ ['missing', true, true, 0], ['reject', false, false, 1],
+ ]) {
+ const result = await copy('Archify.focus.copyLink()', undefined, mode, fallback);
+ assert.equal(result.copied, expected);
+ assert.equal(result.clipboardCalls, attempts);
+ assert.equal(result.residual, 0);
+ assert.equal(result.text, pathToFileURL(file).href + '?theme=light#focus=source');
+ }
+ for (const address of [
+ 'https://example.test/publication?lang=en#page=mechanism&reader={state}',
+ 'file:///standalone/architecture.html#page=second&reader={state}',
+ ]) {
+ await run(`document.documentElement.setAttribute('data-reading-link-template', ${JSON.stringify(address)})`);
+ await check(undefined, address);
+ }
+ for (const invalid of ['javascript:{state}', 'https://example.test/no-state',
+ 'https://example.test/#{state}/{state}', 'https://user:[email protected]/#{state}']) {
+ await run(`document.documentElement.setAttribute('data-reading-link-template', ${JSON.stringify(invalid)}); Archify.focus.set('source',{toggle:false,updateUrl:false})`);
+ const result = await copy('Archify.focus.copyLink()');
+ assert.equal(result.copied, false);
+ assert.equal(result.text, null);
+ assert.equal(result.clipboardCalls, 0);
+ assert.equal(result.residual, 0);
+ }
+ const host = 'https://example.test/publication#page=opaque&reader={state}';
+ const script = `<script>(async () => {
+ if (document.readyState !== 'complete') await new Promise(resolve => addEventListener('load', resolve, {once:true}));
+ const original = document.execCommand;
+ let text = null, clipboardCalls = 0;
+ Object.defineProperty(navigator, 'clipboard', { configurable: true, value: {
+ writeText: () => { clipboardCalls++; return Promise.reject(new Error('denied')); }
+ }});
+ document.execCommand = () => { text = document.querySelector('textarea[readonly]')?.value; return true; };
+ const results = [];
+ try {
+ for (const [setup, action, state] of ${JSON.stringify(states)}) {
+ const selected = eval(setup), copied = await eval(action);
+ results.push({ selected, copied, text, state, clipboardCalls,
+ residual: document.querySelectorAll('textarea[readonly]').length });
+ }
+ const policy = document.permissionsPolicy || document.featurePolicy;
+ parent.postMessage({type:'native-reading-address', location:location.href,
+ denied: policy?.allowsFeature('clipboard-write') === false, results}, '*');
+ } catch (error) { parent.postMessage({type:'native-reading-address', error:error.message}, '*'); }
+ finally { document.execCommand = original; }
+ })();</script>`;
+ const embedded = html.replace('<html ', `<html data-reading-link-template="${host.replaceAll('&', '&amp;')}" `)
+ .replace('</body>', script + '</body>');
+ const opaque = await run(`new Promise((resolve,reject) => {
+ const frame=document.createElement('iframe'); frame.width='1600'; frame.height='1100';
+ frame.setAttribute('sandbox','allow-scripts');
+ const timeout=setTimeout(() => { removeEventListener('message', receive); frame.remove(); reject(new Error('Native address frame did not report')); },10000);
+ const receive=event => { if(event.source!==frame.contentWindow || event.data?.type!=='native-reading-address') return;
+ clearTimeout(timeout); removeEventListener('message',receive); frame.remove(); resolve(event.data); };
+ addEventListener('message',receive); frame.srcdoc=${JSON.stringify(embedded)};
+ document.body.appendChild(frame);
+ })`);
+ assert.equal(opaque.error, undefined);
+ assert.equal(opaque.location, 'about:srcdoc');
+ assert.equal(opaque.denied, true);
+ assert.equal(opaque.results.length, states.length);
+ for (const result of opaque.results) {
+ assert.equal(result.selected, true);
+ assert.equal(result.copied, true);
+ assert.equal(result.clipboardCalls, 0);
+ assert.equal(result.residual, 0);
+ assert.equal(result.text, host.replace('{state}', encodeURIComponent(result.state)));
+ }
+});
diff --git a/test/semantic-passport.test.mjs b/test/semantic-passport.test.mjs
index 2c17538e..8b256dca 100644
--- a/test/semantic-passport.test.mjs
+++ b/test/semantic-passport.test.mjs
@@ -117,8 +117,6 @@ test('Relationship Lens renders one Semantic Passport and copyable stable focus
assert.match(html, /id="btn-focus-relations"[^>]+aria-expanded="false"[^>]+aria-controls="relationship-lens-list"/);
assert.match(html, /function renderPassport\(id, node\)/);
assert.match(html, /var relationId = record && record\.id/);
- assert.match(html, /\? '#relation=' \+ encodeURIComponent\(relationId\)/);
- assert.match(html, /: '#focus=' \+ encodeURIComponent\(activeIds\[0\]\)/);
assert.match(html, /navigator\.clipboard\.writeText\(value\)/);
assert.match(html, /document\.execCommand\('copy'\)/);
assert.match(html, /copyLink: copyFocusLink/);
diff --git a/viewer/focus.js b/viewer/focus.js
index 5a86012c..72c1e187 100644
--- a/viewer/focus.js
+++ b/viewer/focus.js
@@ -1392,31 +1392,15 @@
return setMany([id], options);
}
- function fallbackCopy(value) {
- var field = document.createElement('textarea');
- field.value = value;
- field.setAttribute('readonly', '');
- field.style.position = 'fixed';
- field.style.opacity = '0';
- document.body.appendChild(field);
- field.select();
- var copied = false;
- try { copied = document.execCommand('copy'); } catch (_) {}
- field.remove();
- return copied;
- }
-
function copyFocusLink() {
if (activeIds.length !== 1) return Promise.resolve(false);
var record = pinnedRelationshipRecord();
var relationId = record && record.id;
- var value = location.href.replace(/#.*$/, '') + (relationId
- ? '#relation=' + encodeURIComponent(relationId)
- : '#focus=' + encodeURIComponent(activeIds[0]) + (reachabilityMode ? '&reach=' + reachabilityMode : ''));
- var copy = navigator.clipboard && typeof navigator.clipboard.writeText === 'function'
- ? navigator.clipboard.writeText(value).then(function () { return true; }).catch(function () { return fallbackCopy(value); })
- : Promise.resolve(fallbackCopy(value));
- return copy.then(function (copied) {
+ var value = readerLink(relationId
+ ? 'relation=' + encodeURIComponent(relationId)
+ : 'focus=' + encodeURIComponent(activeIds[0]) + (reachabilityMode ? '&reach=' + reachabilityMode : ''));
+ if (value === null) return Promise.resolve(false);
+ return copyReaderText(value).then(function (copied) {
copyBtn.textContent = viewerText(copied ? 'viewer.common.copied' : 'viewer.common.copyFailed');
copyBtn.setAttribute('aria-label', copied
? viewerText(relationId ? 'viewer.passport.copy.pinned.success' : 'viewer.passport.copy.focused.success')
diff --git a/viewer/route-probe.js b/viewer/route-probe.js
index 9fc1926e..20f62d6d 100644
--- a/viewer/route-probe.js
+++ b/viewer/route-probe.js
@@ -885,26 +885,11 @@
if (!context || !Archify.finder) return false;
return Archify.finder.open({ context: context });
}
- function fallbackCopy(value) {
- var field = document.createElement('textarea');
- field.value = value;
- field.setAttribute('readonly', '');
- field.style.position = 'fixed';
- field.style.opacity = '0';
- document.body.appendChild(field);
- field.select();
- var copied = false;
- try { copied = document.execCommand('copy'); } catch (_) {}
- field.remove();
- return copied;
- }
function copyLink() {
if (mode !== 'result') return Promise.resolve(false);
- var value = location.href.replace(/#.*$/, '') + '#route=' + encodeURIComponent(startId) + '~' + encodeURIComponent(endId);
- var copy = navigator.clipboard && typeof navigator.clipboard.writeText === 'function'
- ? navigator.clipboard.writeText(value).then(function () { return true; }).catch(function () { return fallbackCopy(value); })
- : Promise.resolve(fallbackCopy(value));
- return copy.then(function (copied) {
+ var value = readerLink('route=' + encodeURIComponent(startId) + '~' + encodeURIComponent(endId));
+ if (value === null) return Promise.resolve(false);
+ return copyReaderText(value).then(function (copied) {
copyBtn.textContent = viewerText(copied ? 'viewer.common.copied' : 'viewer.common.copyFailed');
copyBtn.setAttribute('aria-label', viewerText(copied ? 'viewer.route.copy.success' : 'viewer.route.copy.failed'));
window.setTimeout(function () {
diff --git a/viewer/semantic-lens.js b/viewer/semantic-lens.js
index 03a6a685..2f7a5674 100644
--- a/viewer/semantic-lens.js
+++ b/viewer/semantic-lens.js
@@ -519,26 +519,11 @@
if (options.closePanel === true) close({ restoreFocus: false });
return false;
}
- function fallbackCopy(value) {
- var field = document.createElement('textarea');
- field.value = value;
- field.setAttribute('readonly', '');
- field.style.position = 'fixed';
- field.style.opacity = '0';
- document.body.appendChild(field);
- field.select();
- var copied = false;
- try { copied = document.execCommand('copy'); } catch (_) {}
- field.remove();
- return copied;
- }
function copyLink() {
if (!selectedKinds.length) return Promise.resolve(false);
- var value = location.href.replace(/#.*$/, '') + '#lens=' + selectedKinds.map(encodeURIComponent).join('~');
- var copy = navigator.clipboard && typeof navigator.clipboard.writeText === 'function'
- ? navigator.clipboard.writeText(value).then(function () { return true; }).catch(function () { return fallbackCopy(value); })
- : Promise.resolve(fallbackCopy(value));
- return copy.then(function (copied) {
+ var value = readerLink('lens=' + selectedKinds.map(encodeURIComponent).join('~'));
+ if (value === null) return Promise.resolve(false);
+ return copyReaderText(value).then(function (copied) {
copyBtn.textContent = viewerText(copied ? 'viewer.common.copied' : 'viewer.common.copyFailed');
window.setTimeout(function () { copyBtn.textContent = viewerText('viewer.common.copyLink'); }, 1600);
return copied;
diff --git a/viewer/template.source.html b/viewer/template.source.html
index 07780879..09244adc 100644
--- a/viewer/template.source.html
+++ b/viewer/template.source.html
@@ -697,6 +697,38 @@ OTHER DEALINGS IN THE FONT SOFTWARE.
.replace(/\b\w/g, function (letter) { return letter.toUpperCase(); });
}
+ function readerLink(state) {
+ var template = document.documentElement.getAttribute('data-reading-link-template');
+ if (template === null) return location.href.replace(/#.*$/, '') + '#' + state;
+ if (!template || template.length > 4096 || template.split('{state}').length !== 2) return null;
+ try {
+ var url = new URL(template.replace('{state}', encodeURIComponent(state)));
+ if (['http:', 'https:', 'file:'].indexOf(url.protocol) === -1 || url.username || url.password) return null;
+ return url.href;
+ } catch (_) { return null; }
+ }
+
+ function copyReaderText(value) {
+ function fallbackCopy() {
+ var field = document.createElement('textarea');
+ field.value = value;
+ field.setAttribute('readonly', '');
+ field.style.position = 'fixed';
+ field.style.opacity = '0';
+ document.body.appendChild(field);
+ field.select();
+ var copied = false;
+ try { copied = document.execCommand('copy'); } catch (_) {}
+ field.remove();
+ return copied;
+ }
+ var policy = document.permissionsPolicy || document.featurePolicy;
+ var allowed = !policy || typeof policy.allowsFeature !== 'function' || policy.allowsFeature('clipboard-write');
+ return allowed && navigator.clipboard && typeof navigator.clipboard.writeText === 'function'
+ ? navigator.clipboard.writeText(value).then(function () { return true; }).catch(fallbackCopy)
+ : Promise.resolve(fallbackCopy());
+ }
+
function hasDrawableGeometry(element) {
if (!element || element.hasAttribute('data-ambient-flow-overlay')) return false;
var geometries = /^(path|line|polyline)$/i.test(element.tagName)