feat: open a tab in a new window from its context menu
This commit is contained in:
164
src/main.rs
164
src/main.rs
@@ -41,6 +41,7 @@ enum UserEvent {
|
||||
OpenPaths(Vec<PathBuf>, bool),
|
||||
ActivateTab(WindowId, u64),
|
||||
CloseTab(WindowId, u64),
|
||||
DetachTab(WindowId, u64),
|
||||
CloseActiveTab,
|
||||
LocateTab(WindowId, u64),
|
||||
FileChanged(WindowId, PathBuf), // external change: refresh preview AND textarea
|
||||
@@ -200,6 +201,7 @@ struct Strings {
|
||||
btn_edit: &'static str,
|
||||
btn_preview: &'static str,
|
||||
btn_new: &'static str,
|
||||
btn_new_window: &'static str,
|
||||
new_filename: &'static str,
|
||||
fold_toggle: &'static str,
|
||||
btn_zoom: &'static str,
|
||||
@@ -227,6 +229,7 @@ impl Strings {
|
||||
btn_edit: "编辑 (Cmd/Ctrl+E)",
|
||||
btn_preview: "预览 (Cmd/Ctrl+E)",
|
||||
btn_new: "新建 Markdown (Cmd/Ctrl+N)",
|
||||
btn_new_window: "在新窗口打开",
|
||||
new_filename: "新建.md",
|
||||
fold_toggle: "折叠/展开",
|
||||
btn_zoom: "正文缩放",
|
||||
@@ -250,6 +253,7 @@ impl Strings {
|
||||
btn_edit: "Edit (Cmd/Ctrl+E)",
|
||||
btn_preview: "Preview (Cmd/Ctrl+E)",
|
||||
btn_new: "New Markdown (Cmd/Ctrl+N)",
|
||||
btn_new_window: "Open in New Window",
|
||||
new_filename: "Untitled.md",
|
||||
fold_toggle: "Collapse / Expand",
|
||||
btn_zoom: "Content zoom",
|
||||
@@ -1320,6 +1324,18 @@ body.has-tabs {{ --chrome-top: 50px; }}
|
||||
font: 16px/1 -apple-system, BlinkMacSystemFont, sans-serif; opacity: .58;
|
||||
}}
|
||||
.tab-close:hover {{ opacity: 1; background: rgba(0,0,0,.08); }}
|
||||
.tab-menu {{
|
||||
position: fixed; z-index: 200; min-width: 184px; padding: 5px;
|
||||
background: #fff; border: 1px solid #ddd; border-radius: 8px;
|
||||
box-shadow: 0 8px 24px rgba(0,0,0,.16);
|
||||
}}
|
||||
.tab-menu[hidden] {{ display: none; }}
|
||||
.tab-menu button {{
|
||||
display: block; width: 100%; padding: 7px 10px; border: 0; border-radius: 5px;
|
||||
background: transparent; color: #222; text-align: left; font: inherit;
|
||||
font-size: 13px; cursor: pointer;
|
||||
}}
|
||||
.tab-menu button:hover {{ background: #f2f2f2; }}
|
||||
.tab-open {{
|
||||
width: 31px; height: 31px; flex: 0 0 auto; padding: 0; border: 0; border-radius: 7px;
|
||||
color: #666; background: transparent; cursor: pointer; font: 20px/1 -apple-system, sans-serif;
|
||||
@@ -1443,6 +1459,9 @@ body.empty .toolbar {{ display: none !important; }}
|
||||
.tab.active {{ color: #eee; background: #2c2c2c; border-color: #444; }}
|
||||
.tab.missing {{ color: #e3a04b; }}
|
||||
.tab-close:hover, .tab-open:hover {{ background: rgba(255,255,255,.1); color: #fff; }}
|
||||
.tab-menu {{ background: #2a2a2a; border-color: #444; box-shadow: 0 8px 24px rgba(0,0,0,.45); }}
|
||||
.tab-menu button {{ color: #ddd; }}
|
||||
.tab-menu button:hover {{ background: rgba(255,255,255,.08); }}
|
||||
.missing-file p {{ color: #aaa; }}
|
||||
.missing-actions button {{ background: #292929; border-color: #444; color: #ddd; }}
|
||||
.missing-actions button:hover {{ background: #333; }}
|
||||
@@ -1479,6 +1498,7 @@ body.editing #app {{ max-width: none; padding: 0; }}
|
||||
}}
|
||||
</style></head><body class="{body_class}">
|
||||
<div class="tabbar" id="tabbar"><div class="tabs" id="tabs"></div><div class="doc-stats" id="doc-stats" aria-live="polite"></div><button class="tab-open" id="tab-open" type="button" title="{btn_new}" aria-label="{btn_new}">+</button></div>
|
||||
<div class="tab-menu" id="tab-menu" hidden><button type="button" id="tab-menu-new-window">{btn_new_window}</button></div>
|
||||
<div class="toolbar">
|
||||
<button id="btn-toggle" title="{btn_edit}" aria-label="{btn_edit}"></button>
|
||||
<div class="zoom-control" id="zoom-control">
|
||||
@@ -1527,6 +1547,9 @@ body.editing #app {{ max-width: none; padding: 0; }}
|
||||
var tabsEl = document.getElementById('tabs');
|
||||
var docStats = document.getElementById('doc-stats');
|
||||
var tabOpen = document.getElementById('tab-open');
|
||||
var tabMenu = document.getElementById('tab-menu');
|
||||
var tabMenuNewWindow = document.getElementById('tab-menu-new-window');
|
||||
var tabMenuTargetId = 0;
|
||||
var ta = document.getElementById('editor');
|
||||
var dirty = false;
|
||||
var activeTabId = 0;
|
||||
@@ -1611,7 +1634,39 @@ body.editing #app {{ max-width: none; padding: 0; }}
|
||||
applyZoom(100, false);
|
||||
window.__mdPreviewSetZoom = function(percent) {{ applyZoom(percent, false); }};
|
||||
updateDocumentStats(ta.value);
|
||||
function hideTabMenu() {{
|
||||
if (!tabMenu || tabMenu.hidden) return;
|
||||
tabMenu.hidden = true;
|
||||
tabMenuTargetId = 0;
|
||||
}}
|
||||
function showTabMenu(id, x, y) {{
|
||||
if (!tabMenu) return;
|
||||
tabMenuTargetId = id;
|
||||
tabMenu.hidden = false;
|
||||
tabMenu.style.left = '0px';
|
||||
tabMenu.style.top = '0px';
|
||||
var rect = tabMenu.getBoundingClientRect();
|
||||
var left = Math.max(8, Math.min(x, window.innerWidth - rect.width - 8));
|
||||
var top = Math.max(8, Math.min(y, window.innerHeight - rect.height - 8));
|
||||
tabMenu.style.left = left + 'px';
|
||||
tabMenu.style.top = top + 'px';
|
||||
}}
|
||||
function detachTab(id) {{
|
||||
if (saveBlocked) {{
|
||||
window.alert(window.__mdPreviewCannotSave || 'Discard unsaved changes?');
|
||||
return;
|
||||
}}
|
||||
requestTabAction('detach', id);
|
||||
}}
|
||||
document.addEventListener('contextmenu', function(e) {{
|
||||
var tab = e.target && e.target.closest ? e.target.closest('[data-tab-id]') : null;
|
||||
if (tab) {{
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
showTabMenu(tab.getAttribute('data-tab-id'), e.clientX, e.clientY);
|
||||
return;
|
||||
}}
|
||||
hideTabMenu();
|
||||
if (!inEdit() || e.target !== ta) e.preventDefault();
|
||||
}});
|
||||
function setDirty(d) {{
|
||||
@@ -1833,7 +1888,20 @@ body.editing #app {{ max-width: none; padding: 0; }}
|
||||
}};
|
||||
|
||||
tabOpen.addEventListener('click', newFile);
|
||||
if (tabMenuNewWindow) {{
|
||||
tabMenuNewWindow.addEventListener('click', function(e) {{
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
var id = tabMenuTargetId;
|
||||
hideTabMenu();
|
||||
if (id) detachTab(id);
|
||||
}});
|
||||
}}
|
||||
window.addEventListener('resize', hideTabMenu);
|
||||
window.addEventListener('scroll', hideTabMenu, true);
|
||||
window.addEventListener('blur', hideTabMenu);
|
||||
document.addEventListener('click', function(e) {{
|
||||
if (tabMenu && !tabMenu.hidden) hideTabMenu();
|
||||
var closeTab = e.target && e.target.closest ? e.target.closest('[data-close-tab]') : null;
|
||||
if (closeTab) {{
|
||||
e.preventDefault();
|
||||
@@ -1907,6 +1975,10 @@ body.editing #app {{ max-width: none; padding: 0; }}
|
||||
}});
|
||||
|
||||
document.addEventListener('keydown', function(e) {{
|
||||
if (e.key === 'Escape' && tabMenu && !tabMenu.hidden) {{
|
||||
hideTabMenu();
|
||||
return;
|
||||
}}
|
||||
if ((e.metaKey || e.ctrlKey) && (e.key === 'w' || e.key === 'W')) {{
|
||||
if (activeTabId) {{
|
||||
e.preventDefault();
|
||||
@@ -2013,6 +2085,7 @@ body.editing #app {{ max-width: none; padding: 0; }}
|
||||
window.ipc.postMessage('external-change:' + (dirty ? 'dirty' : 'clean'));
|
||||
}};
|
||||
window.__setTabs = function(tabs) {{
|
||||
hideTabMenu();
|
||||
tabs = Array.isArray(tabs) ? tabs : [];
|
||||
tabsEl.textContent = '';
|
||||
activeTabId = 0;
|
||||
@@ -2124,6 +2197,7 @@ if(window.__enhancePreview)window.__enhancePreview();
|
||||
preview_html = preview_html,
|
||||
raw_md_escaped = html_escape_ta(raw_md),
|
||||
btn_new = s.btn_new,
|
||||
btn_new_window = s.btn_new_window,
|
||||
btn_edit = s.btn_edit,
|
||||
btn_preview = s.btn_preview,
|
||||
fold_toggle = s.fold_toggle,
|
||||
@@ -3909,6 +3983,9 @@ fn build_webview(
|
||||
"close" => {
|
||||
let _ = proxy_for_ipc.send_event(UserEvent::CloseTab(window_id, id));
|
||||
}
|
||||
"detach" => {
|
||||
let _ = proxy_for_ipc.send_event(UserEvent::DetachTab(window_id, id));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
} else if let Some(id) = body.strip_prefix("locate-tab:") {
|
||||
@@ -4029,6 +4106,23 @@ fn create_empty_window(
|
||||
target: &EventLoopWindowTarget<UserEvent>,
|
||||
app: &mut AppState,
|
||||
proxy: &EventLoopProxy<UserEvent>,
|
||||
) -> Result<WindowId, String> {
|
||||
let source_window_id = app.active_window;
|
||||
create_window_with_session(
|
||||
target,
|
||||
app,
|
||||
proxy,
|
||||
DocumentSession::default(),
|
||||
source_window_id,
|
||||
)
|
||||
}
|
||||
|
||||
fn create_window_with_session(
|
||||
target: &EventLoopWindowTarget<UserEvent>,
|
||||
app: &mut AppState,
|
||||
proxy: &EventLoopProxy<UserEvent>,
|
||||
initial_session: DocumentSession,
|
||||
source_window_id: WindowId,
|
||||
) -> Result<WindowId, String> {
|
||||
if app.windows.len() >= MAX_WINDOWS {
|
||||
return Err(format!(
|
||||
@@ -4037,7 +4131,8 @@ fn create_empty_window(
|
||||
}
|
||||
let source = app
|
||||
.windows
|
||||
.get(&app.active_window)
|
||||
.get(&source_window_id)
|
||||
.or_else(|| app.windows.get(&app.active_window))
|
||||
.ok_or_else(|| "No active window.".to_string())?;
|
||||
let geom = secondary_geom(source, target);
|
||||
let theme = load_theme_choice();
|
||||
@@ -4052,7 +4147,7 @@ fn create_empty_window(
|
||||
let window = builder.build(target).map_err(|error| error.to_string())?;
|
||||
let window_id = window.id();
|
||||
let page = build_startup_page(&app.strings);
|
||||
let session = Arc::new(Mutex::new(DocumentSession::default()));
|
||||
let session = Arc::new(Mutex::new(initial_session));
|
||||
let last_self_write = Arc::new(Mutex::new(None));
|
||||
let recent_files = Arc::clone(&app.recent_files);
|
||||
let webview = build_webview(
|
||||
@@ -4493,6 +4588,71 @@ fn main() {
|
||||
}
|
||||
}
|
||||
}
|
||||
TaoEvent::UserEvent(UserEvent::DetachTab(window_id, tab_id)) => {
|
||||
let Some(ws) = app.windows.get_mut(&window_id) else {
|
||||
return;
|
||||
};
|
||||
let mut session = ws.session.lock().unwrap();
|
||||
let Some(tab) = session.tabs.iter().find(|tab| tab.id == tab_id).cloned() else {
|
||||
return;
|
||||
};
|
||||
let target_active = session.active_id == Some(tab_id);
|
||||
if !target_active && tab.dirty {
|
||||
drop(session);
|
||||
show_warning_dialog(
|
||||
"Could Not Move Tab",
|
||||
"Save this file before moving it to a new window.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
if !target_active {
|
||||
session.activate(tab_id);
|
||||
}
|
||||
drop(session);
|
||||
|
||||
let mut moved = tab;
|
||||
moved.dirty = false;
|
||||
moved.missing = false;
|
||||
moved.edit_on_open = false;
|
||||
let new_session = DocumentSession::with_tab(moved);
|
||||
let new_window_id = match create_window_with_session(
|
||||
target,
|
||||
&mut app,
|
||||
&proxy,
|
||||
new_session,
|
||||
window_id,
|
||||
) {
|
||||
Ok(id) => id,
|
||||
Err(error) => {
|
||||
show_warning_dialog("Could Not Open New Window", &error);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let close_source;
|
||||
{
|
||||
let Some(ws) = app.windows.get_mut(&window_id) else {
|
||||
return;
|
||||
};
|
||||
let mut session = ws.session.lock().unwrap();
|
||||
if session.detach(tab_id).is_none() {
|
||||
drop(session);
|
||||
close_window(&mut app, new_window_id, control_flow);
|
||||
show_warning_dialog("Could Not Move Tab", "The tab is no longer available.");
|
||||
return;
|
||||
}
|
||||
close_source = session.tabs.is_empty();
|
||||
if !close_source {
|
||||
drop(session);
|
||||
ws.render_active(&recent_files, &strings);
|
||||
let path = ws.session.lock().unwrap().active().map(|tab| tab.path.clone());
|
||||
install_file_watcher(&ws.watcher, &proxy, &ws.last_self_write, window_id, path);
|
||||
}
|
||||
}
|
||||
if close_source {
|
||||
close_window(&mut app, window_id, control_flow);
|
||||
}
|
||||
}
|
||||
TaoEvent::UserEvent(UserEvent::CloseActiveTab) => {
|
||||
let window_id = app.active_window;
|
||||
let Some(ws) = app.windows.get_mut(&window_id) else {
|
||||
|
||||
@@ -65,6 +65,29 @@ impl DocumentSession {
|
||||
true
|
||||
}
|
||||
|
||||
pub fn with_tab(tab: DocumentTab) -> Self {
|
||||
let id = tab.id;
|
||||
Self {
|
||||
tabs: vec![tab],
|
||||
active_id: Some(id),
|
||||
next_id: id,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn detach(&mut self, id: u64) -> Option<DocumentTab> {
|
||||
let index = self.tabs.iter().position(|tab| tab.id == id)?;
|
||||
let was_active = self.active_id == Some(id);
|
||||
let tab = self.tabs.remove(index);
|
||||
if was_active {
|
||||
self.active_id = self
|
||||
.tabs
|
||||
.get(index)
|
||||
.or_else(|| index.checked_sub(1).and_then(|i| self.tabs.get(i)))
|
||||
.map(|tab| tab.id);
|
||||
}
|
||||
Some(tab)
|
||||
}
|
||||
|
||||
pub fn active(&self) -> Option<&DocumentTab> {
|
||||
let id = self.active_id?;
|
||||
self.tabs.iter().find(|tab| tab.id == id)
|
||||
@@ -180,6 +203,25 @@ mod tests {
|
||||
let _ = fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detaching_a_tab_keeps_source_and_adopts_it_in_new_session() {
|
||||
let dir = temp_dir("detach");
|
||||
let mut session = DocumentSession::default();
|
||||
let first = session.open(dir.join("one.md"), false);
|
||||
let second = session.open(dir.join("two.md"), false);
|
||||
session.activate(first);
|
||||
|
||||
let moved = session.detach(second).unwrap();
|
||||
assert_eq!(session.active_id, Some(first));
|
||||
assert_eq!(session.tabs.len(), 1);
|
||||
|
||||
let adopted = DocumentSession::with_tab(moved);
|
||||
assert_eq!(adopted.active_id, Some(second));
|
||||
assert_eq!(adopted.tabs.len(), 1);
|
||||
assert_eq!(adopted.tabs[0].id, second);
|
||||
let _ = fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
#[test]
|
||||
fn opened_paths_drop_windows_verbatim_prefix() {
|
||||
|
||||
Reference in New Issue
Block a user