host: the tab bridge ships from waybetter-host; create-waybetter uses it
tab-bridge.js (moved from wayBetter for X) is served by bridge::SOURCE, or by bridge::script(BridgeOptions) with shortcut and link-drag forwarding switched off for a shell that does not handle them (a forwarded shortcut is taken from the page). Tests: one options line, only tab_report/tab_shortcut/tab_link_drag, every forwarded shortcut is one tabs::valid_shortcut accepts. Generated apps now inject bridge::script(BridgeOptions::REPORT_ONLY) instead of writing their own duplicated src-tauri/runtime/tab-bridge.js.
This commit is contained in:
parent
3e6cbe0773
commit
d3ed72ea4d
4 changed files with 209 additions and 37 deletions
67
crates/waybetter-host/src/bridge.rs
Normal file
67
crates/waybetter-host/src/bridge.rs
Normal file
|
|
@ -0,0 +1,67 @@
|
||||||
|
//! The tab bridge: the script every tab webview gets as a main-frame initialization script
|
||||||
|
//! ([`script`]). It reports the tab's own URL, title, favicon and focus to the shell (`tab_report`)
|
||||||
|
//! and, when the app enables them, forwards browser shortcuts pressed in the page (`tab_shortcut`,
|
||||||
|
//! [`crate::tabs::valid_shortcut`]) and link drags (`tab_link_drag`, [`crate::tabs::link_drag`]).
|
||||||
|
//! The app's `tab-chrome` capability grants exactly the commands it calls, about the tab itself.
|
||||||
|
|
||||||
|
/// The bridge source (`tab-bridge.js` next to this crate's `Cargo.toml`), all features on.
|
||||||
|
pub const SOURCE: &str = include_str!("../tab-bridge.js");
|
||||||
|
const DEFAULT_OPTIONS: &str = "const options = { shortcuts: true, linkDrags: true };";
|
||||||
|
|
||||||
|
/// What the bridge forwards besides the tab report. Turn a feature off when the app's shell does
|
||||||
|
/// not handle it: a forwarded shortcut is taken from the page (`preventDefault`).
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub struct BridgeOptions {
|
||||||
|
/// Browser shortcuts (new/close/reopen tab, reload, back/forward, split, palette, deck keys).
|
||||||
|
pub shortcuts: bool,
|
||||||
|
/// Link drags out of (or into) the page, for the shell's split/tab drop zones.
|
||||||
|
pub link_drags: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BridgeOptions {
|
||||||
|
pub const ALL: Self = Self { shortcuts: true, link_drags: true };
|
||||||
|
/// Only `tab_report` (URL, title, favicon, focus).
|
||||||
|
pub const REPORT_ONLY: Self = Self { shortcuts: false, link_drags: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The bridge script with `options`.
|
||||||
|
pub fn script(options: BridgeOptions) -> String {
|
||||||
|
let set = format!("const options = {{ shortcuts: {}, linkDrags: {} }};", options.shortcuts, options.link_drags);
|
||||||
|
SOURCE.replacen(DEFAULT_OPTIONS, &set, 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn options_are_set_in_the_one_options_line() {
|
||||||
|
assert_eq!(SOURCE.matches(DEFAULT_OPTIONS).count(), 1);
|
||||||
|
assert_eq!(script(BridgeOptions::ALL), SOURCE);
|
||||||
|
let report = script(BridgeOptions::REPORT_ONLY);
|
||||||
|
assert!(report.contains("const options = { shortcuts: false, linkDrags: false };"));
|
||||||
|
assert!(!report.contains(DEFAULT_OPTIONS));
|
||||||
|
assert!(report.contains("if (options.shortcuts) addEventListener('keydown'"));
|
||||||
|
assert!(report.contains("if (options.linkDrags) {"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn bridge_calls_only_the_tab_chrome_commands() {
|
||||||
|
let mut commands: Vec<&str> = SOURCE.match_indices("invoke('").map(|(at, _)| SOURCE[at + 8..].split('\'').next().unwrap()).collect();
|
||||||
|
commands.sort();
|
||||||
|
commands.dedup();
|
||||||
|
assert_eq!(commands, ["tab_link_drag", "tab_report", "tab_shortcut"]);
|
||||||
|
assert!(SOURCE.contains("if (window.top !== window || window.__wbTabBridge) return;"), "top frame only, once");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn forwarded_shortcuts_are_ones_the_host_accepts() {
|
||||||
|
for name in ["deck-toggle", "deck-compose", "column-page-prev", "column-page-next", "column-prev", "column-next", "reopen-tab", "new-tab",
|
||||||
|
"open-panel", "close-tab", "focus-address", "command-palette", "prev-tab", "next-tab", "hard-reload", "reload", "split-down",
|
||||||
|
"split-right", "back", "forward"] {
|
||||||
|
assert!(SOURCE.contains(&format!("'{name}'")), "{name} is not in the bridge");
|
||||||
|
assert!(crate::tabs::valid_shortcut(name), "{name} would be refused");
|
||||||
|
}
|
||||||
|
assert!(crate::tabs::valid_shortcut("column-3"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -14,6 +14,7 @@
|
||||||
//! - [`hotfix`]: the signed, data-only hotfix channel.
|
//! - [`hotfix`]: the signed, data-only hotfix channel.
|
||||||
//! - [`update`]: silent-update scheduling and the crash handshake.
|
//! - [`update`]: silent-update scheduling and the crash handshake.
|
||||||
//! - [`tabs`]: tab layout/state payloads, link routing and tab-chrome validation.
|
//! - [`tabs`]: tab layout/state payloads, link routing and tab-chrome validation.
|
||||||
|
//! - [`bridge`]: the tab bridge script every tab gets (URL/title/focus reports, shortcut and link-drag forwarding).
|
||||||
//! - [`layout`]: native placement bookkeeping (unchanged bounds skipped, window-resize follow).
|
//! - [`layout`]: native placement bookkeeping (unchanged bounds skipped, window-resize follow).
|
||||||
//! - [`i18n`]: the strings native UI and site tabs get in the owner's language (validated data), OS locale.
|
//! - [`i18n`]: the strings native UI and site tabs get in the owner's language (validated data), OS locale.
|
||||||
//! - [`backup`]: the settings backup envelope, secret scrubbing and the plugin/account sections.
|
//! - [`backup`]: the settings backup envelope, secret scrubbing and the plugin/account sections.
|
||||||
|
|
@ -33,6 +34,7 @@
|
||||||
|
|
||||||
pub mod alerts;
|
pub mod alerts;
|
||||||
pub mod backup;
|
pub mod backup;
|
||||||
|
pub mod bridge;
|
||||||
pub mod devmode;
|
pub mod devmode;
|
||||||
#[cfg(feature = "net")]
|
#[cfg(feature = "net")]
|
||||||
pub mod fonts;
|
pub mod fonts;
|
||||||
|
|
|
||||||
135
crates/waybetter-host/tab-bridge.js
Normal file
135
crates/waybetter-host/tab-bridge.js
Normal file
|
|
@ -0,0 +1,135 @@
|
||||||
|
// wayBetter tab bridge (waybetter-host `bridge.rs` serves this file). Injected into every browser
|
||||||
|
// tab (top frame only). Tells the shell about SPA URL changes, the favicon and focus and, when the
|
||||||
|
// app enables them, forwards browser shortcuts pressed while the page has focus and link drags.
|
||||||
|
// It can only call `tab_report` / `tab_shortcut` / `tab_link_drag`, which affect this tab's own
|
||||||
|
// address bar, forward a shortcut, or tell the shell a link drag started/entered/ended here.
|
||||||
|
(() => {
|
||||||
|
if (window.top !== window || window.__wbTabBridge) return;
|
||||||
|
window.__wbTabBridge = true;
|
||||||
|
const options = { shortcuts: true, linkDrags: true }; // waybetter-host: bridge::script() options
|
||||||
|
const invoke = (cmd, args) => {
|
||||||
|
const ipc = window.__TAURI_INTERNALS__;
|
||||||
|
if (ipc && typeof ipc.invoke === 'function') ipc.invoke(cmd, args).catch(() => {});
|
||||||
|
};
|
||||||
|
|
||||||
|
let lastUrl = '';
|
||||||
|
let lastTitle = '';
|
||||||
|
let lastIcon = '';
|
||||||
|
const favicon = () => {
|
||||||
|
const link = document.querySelector('link[rel~="icon"][href], link[rel="shortcut icon"][href]');
|
||||||
|
try { return link ? new URL(link.getAttribute('href'), location.href).href : `${location.origin}/favicon.ico`; } catch { return ''; }
|
||||||
|
};
|
||||||
|
const report = (extra) => {
|
||||||
|
const url = location.href;
|
||||||
|
const title = document.title || '';
|
||||||
|
const icon = favicon();
|
||||||
|
if (!extra && url === lastUrl && title === lastTitle && icon === lastIcon) return;
|
||||||
|
lastUrl = url; lastTitle = title; lastIcon = icon;
|
||||||
|
invoke('tab_report', { report: { url, title, favicon: icon, ...extra } });
|
||||||
|
};
|
||||||
|
let queued = false;
|
||||||
|
const schedule = () => { if (!queued) { queued = true; setTimeout(() => { queued = false; report(); }, 50); } };
|
||||||
|
|
||||||
|
for (const method of ['pushState', 'replaceState']) {
|
||||||
|
const original = history[method];
|
||||||
|
history[method] = function (...args) {
|
||||||
|
const result = original.apply(this, args);
|
||||||
|
schedule();
|
||||||
|
return result;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
addEventListener('popstate', schedule);
|
||||||
|
addEventListener('hashchange', schedule);
|
||||||
|
addEventListener('focus', () => report({ focused: true }));
|
||||||
|
addEventListener('pointerdown', () => report({ focused: true }), true);
|
||||||
|
const watchHead = () => {
|
||||||
|
if (!document.head) return;
|
||||||
|
new MutationObserver(schedule).observe(document.head, { childList: true, subtree: true, attributes: true, attributeFilter: ['href'] });
|
||||||
|
schedule();
|
||||||
|
};
|
||||||
|
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', watchHead, { once: true });
|
||||||
|
else watchHead();
|
||||||
|
|
||||||
|
// Power User Mode: a deck column (the X runtime marks <html data-wb-column>) forwards the deck
|
||||||
|
// keys; bare keys only while nothing editable has focus.
|
||||||
|
const typing = () => {
|
||||||
|
const el = document.activeElement;
|
||||||
|
return !!el && (el.isContentEditable || /^(input|textarea|select)$/i.test(el.tagName));
|
||||||
|
};
|
||||||
|
const deckKey = (event) => {
|
||||||
|
const mod = event.ctrlKey || event.metaKey;
|
||||||
|
if (mod && event.shiftKey && !event.altKey && event.code === 'KeyD') return 'deck-toggle';
|
||||||
|
if (!document.documentElement || !document.documentElement.hasAttribute('data-wb-column')) return null;
|
||||||
|
if (event.ctrlKey && event.altKey && !event.metaKey && !event.shiftKey && event.code === 'KeyN' && !typing()) return 'deck-compose';
|
||||||
|
if (event.altKey && !mod && !event.shiftKey) {
|
||||||
|
const digit = /^Digit([1-9])$/.exec(event.code);
|
||||||
|
if (digit) return `column-${digit[1]}`;
|
||||||
|
if (event.key === 'PageUp') return 'column-page-prev';
|
||||||
|
if (event.key === 'PageDown') return 'column-page-next';
|
||||||
|
}
|
||||||
|
if (!mod && !event.altKey && !typing()) {
|
||||||
|
if (event.key === '[') return 'column-prev';
|
||||||
|
if (event.key === ']') return 'column-next';
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
const shortcut = (event) => {
|
||||||
|
const deck = deckKey(event);
|
||||||
|
if (deck) return deck;
|
||||||
|
const mod = event.ctrlKey || event.metaKey;
|
||||||
|
const key = event.key.toLowerCase();
|
||||||
|
if (mod && !event.altKey) {
|
||||||
|
if (key === 't' && event.shiftKey) return 'reopen-tab';
|
||||||
|
if (key === 't') return 'new-tab';
|
||||||
|
if (key === 'w' && event.shiftKey) return 'open-panel';
|
||||||
|
if (key === 'w') return 'close-tab';
|
||||||
|
if (key === 'l') return 'focus-address';
|
||||||
|
if (key === 'k' && !event.shiftKey) return 'command-palette';
|
||||||
|
if (key === 'tab') return event.shiftKey ? 'prev-tab' : 'next-tab';
|
||||||
|
if (key === 'r') return event.shiftKey ? 'hard-reload' : 'reload';
|
||||||
|
// Physical key: layouts like Turkish-Q produce other characters on this key.
|
||||||
|
if (event.code === 'Backslash' || event.code === 'IntlBackslash') return event.shiftKey ? 'split-down' : 'split-right';
|
||||||
|
}
|
||||||
|
if (key === 'f5') return 'reload';
|
||||||
|
if (event.altKey && !mod && key === 'arrowleft') return 'back';
|
||||||
|
if (event.altKey && !mod && key === 'arrowright') return 'forward';
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
// Link drags: the shell hides the tab webviews and shows its split/tab drop zones, so a link
|
||||||
|
// dragged out of this page (or into it from another app) can be dropped as a new pane.
|
||||||
|
if (options.linkDrags) {
|
||||||
|
let localDrag = false;
|
||||||
|
let lastEnter = 0;
|
||||||
|
const linkTypes = (types) => {
|
||||||
|
const list = Array.from(types || []);
|
||||||
|
return !list.includes('Files') && (list.includes('text/uri-list') || list.includes('text/x-moz-url'));
|
||||||
|
};
|
||||||
|
addEventListener('dragstart', (event) => {
|
||||||
|
localDrag = true;
|
||||||
|
// Links, and images inside links (sites like X wrap photos in `/status/.../photo/N` anchors).
|
||||||
|
const target = event.target;
|
||||||
|
const anchor = target && target.closest ? target.closest('a[href]') : null;
|
||||||
|
const url = anchor ? String(anchor.href) : '';
|
||||||
|
if (/^https?:\/\//i.test(url) && url.length <= 4096) invoke('tab_link_drag', { phase: 'start', url });
|
||||||
|
}, true);
|
||||||
|
addEventListener('dragend', () => {
|
||||||
|
localDrag = false;
|
||||||
|
invoke('tab_link_drag', { phase: 'end' });
|
||||||
|
}, true);
|
||||||
|
addEventListener('dragenter', (event) => {
|
||||||
|
if (localDrag || !event.dataTransfer || !linkTypes(event.dataTransfer.types)) return;
|
||||||
|
const now = Date.now();
|
||||||
|
if (now - lastEnter < 500) return;
|
||||||
|
lastEnter = now;
|
||||||
|
invoke('tab_link_drag', { phase: 'enter' });
|
||||||
|
}, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.shortcuts) addEventListener('keydown', (event) => {
|
||||||
|
const action = shortcut(event);
|
||||||
|
if (!action) return;
|
||||||
|
event.preventDefault();
|
||||||
|
event.stopImmediatePropagation();
|
||||||
|
invoke('tab_shortcut', { shortcut: action });
|
||||||
|
}, true);
|
||||||
|
})();
|
||||||
|
|
@ -420,6 +420,7 @@ function desktopRs(o) {
|
||||||
'use std::sync::{Mutex, MutexGuard};',
|
'use std::sync::{Mutex, MutexGuard};',
|
||||||
'use tauri::webview::{NewWindowResponse, PageLoadEvent};',
|
'use tauri::webview::{NewWindowResponse, PageLoadEvent};',
|
||||||
'use tauri::{AppHandle, LogicalPosition, LogicalSize, Manager, State, Webview, WebviewBuilder, WebviewUrl};',
|
'use tauri::{AppHandle, LogicalPosition, LogicalSize, Manager, State, Webview, WebviewBuilder, WebviewUrl};',
|
||||||
|
'use waybetter_host::bridge::{self, BridgeOptions};',
|
||||||
'use waybetter_host::plugins::{PluginStore, ScriptPlugin};',
|
'use waybetter_host::plugins::{PluginStore, ScriptPlugin};',
|
||||||
'use waybetter_host::profiles::Account;',
|
'use waybetter_host::profiles::Account;',
|
||||||
'use waybetter_host::tabs::{parse_web_url, TabLayout, TabState};',
|
'use waybetter_host::tabs::{parse_web_url, TabLayout, TabState};',
|
||||||
|
|
@ -427,8 +428,6 @@ function desktopRs(o) {
|
||||||
'',
|
'',
|
||||||
'/// The page runtime (src/runtime/main.ts), written by `npm run build`.',
|
'/// The page runtime (src/runtime/main.ts), written by `npm run build`.',
|
||||||
'const RUNTIME: &str = include_str!("../runtime/runtime.js");',
|
'const RUNTIME: &str = include_str!("../runtime/runtime.js");',
|
||||||
'/// Reports every tab\'s URL and title to the address bar. It may call only `tab_report`.',
|
|
||||||
'const TAB_BRIDGE: &str = include_str!("../runtime/tab-bridge.js");',
|
|
||||||
'',
|
'',
|
||||||
'struct AppState {',
|
'struct AppState {',
|
||||||
' plugins: Mutex<PluginStore>,',
|
' plugins: Mutex<PluginStore>,',
|
||||||
|
|
@ -591,7 +590,10 @@ function desktopRs(o) {
|
||||||
' let (load_app, load_id) = (app.clone(), id.to_owned());',
|
' let (load_app, load_id) = (app.clone(), id.to_owned());',
|
||||||
' let (title_app, title_id) = (app.clone(), id.to_owned());',
|
' let (title_app, title_id) = (app.clone(), id.to_owned());',
|
||||||
' WebviewBuilder::new(policy::tab_label(id), WebviewUrl::External(url))',
|
' WebviewBuilder::new(policy::tab_label(id), WebviewUrl::External(url))',
|
||||||
' .initialization_script(TAB_BRIDGE)',
|
' // The framework tab bridge: reports each tab\'s URL and title to the address bar; it',
|
||||||
|
' // may call only `tab_report` (shortcut and link-drag forwarding are off: this shell',
|
||||||
|
' // does not handle them yet).',
|
||||||
|
' .initialization_script(bridge::script(BridgeOptions::REPORT_ONLY))',
|
||||||
' // The runtime checks the origin itself and stays inert on other sites.',
|
' // The runtime checks the origin itself and stays inert on other sites.',
|
||||||
' .initialization_script(RUNTIME)',
|
' .initialization_script(RUNTIME)',
|
||||||
' // Pop-ups are refused in this skeleton; open them as tabs with `tabs::OpenRequest`.',
|
' // Pop-ups are refused in this skeleton; open them as tabs with `tabs::OpenRequest`.',
|
||||||
|
|
@ -1060,39 +1062,6 @@ function examplePlugin(o) {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function tabBridge() {
|
|
||||||
return lines(
|
|
||||||
'// Injected into every tab (top frame only): reports URL and title changes of single-page apps',
|
|
||||||
'// to the address bar. It can call only `tab_report` (capability tab-chrome), about this tab.',
|
|
||||||
'(() => {',
|
|
||||||
' if (window.top !== window || window.__wbTabBridge) return;',
|
|
||||||
' window.__wbTabBridge = true;',
|
|
||||||
' const invoke = (command, args) => {',
|
|
||||||
' const ipc = window.__TAURI_INTERNALS__;',
|
|
||||||
" if (ipc && typeof ipc.invoke === 'function') ipc.invoke(command, args).catch(() => {});",
|
|
||||||
' };',
|
|
||||||
" let last = '';",
|
|
||||||
' const report = () => {',
|
|
||||||
' const key = `${location.href}\\n${document.title}`;',
|
|
||||||
' if (key === last) return;',
|
|
||||||
' last = key;',
|
|
||||||
" invoke('tab_report', { report: { url: location.href, title: document.title } });",
|
|
||||||
' };',
|
|
||||||
' const soon = () => setTimeout(report, 50);',
|
|
||||||
" for (const method of ['pushState', 'replaceState']) {",
|
|
||||||
' const original = history[method];',
|
|
||||||
' history[method] = function (...args) {',
|
|
||||||
' const result = original.apply(this, args);',
|
|
||||||
' soon();',
|
|
||||||
' return result;',
|
|
||||||
' };',
|
|
||||||
' }',
|
|
||||||
" addEventListener('popstate', soon);",
|
|
||||||
" addEventListener('DOMContentLoaded', report);",
|
|
||||||
'})();',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildMjs() {
|
function buildMjs() {
|
||||||
return lines(
|
return lines(
|
||||||
'// Builds the two bundles: the page runtime (one IIFE that native code injects into tabs) and the',
|
'// Builds the two bundles: the page runtime (one IIFE that native code injects into tabs) and the',
|
||||||
|
|
@ -1243,7 +1212,6 @@ export function appFiles(o) {
|
||||||
{ path: 'src-tauri/src/site.rs', content: siteRs(o) },
|
{ path: 'src-tauri/src/site.rs', content: siteRs(o) },
|
||||||
{ path: 'src-tauri/src/plugins.rs', content: pluginsRs(o) },
|
{ path: 'src-tauri/src/plugins.rs', content: pluginsRs(o) },
|
||||||
{ path: 'src-tauri/src/desktop.rs', content: desktopRs(o) },
|
{ path: 'src-tauri/src/desktop.rs', content: desktopRs(o) },
|
||||||
{ path: 'src-tauri/runtime/tab-bridge.js', content: tabBridge() },
|
|
||||||
// Replaced by `npm run build`; here so `cargo check` works before the first build.
|
// Replaced by `npm run build`; here so `cargo check` works before the first build.
|
||||||
{ path: APP_OUTPUTS.runtime, content: lines('// Placeholder: `npm run build` writes the page runtime here (src/runtime/main.ts).') },
|
{ path: APP_OUTPUTS.runtime, content: lines('// Placeholder: `npm run build` writes the page runtime here (src/runtime/main.ts).') },
|
||||||
];
|
];
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue