diff --git a/file-management.js b/file-management.js index c7b6b7d3b..c6385cce6 100644 --- a/file-management.js +++ b/file-management.js @@ -57,4 +57,20 @@ async function manageProjectEntry(projectPath, relativePath, action, newName, { return result; } -module.exports = { manageProjectEntry, resolveManagedEntry }; +// Hand a viewer panel's file to the system share menu. Takes an absolute path, +// since those panels also open files outside any project, and only shares a +// file that exists. +function shareFile(filePath, { share }) { + if (typeof filePath !== 'string' || !path.isAbsolute(filePath)) throw new Error('Invalid file path'); + let resolved; + try { + resolved = fs.realpathSync(filePath); + } catch { + throw new Error('The file does not exist'); + } + if (!fs.statSync(resolved).isFile()) throw new Error('Not a file'); + share(resolved); + return { filePath: resolved }; +} + +module.exports = { manageProjectEntry, resolveManagedEntry, shareFile }; diff --git a/main.js b/main.js index d09bceba2..defefe319 100644 --- a/main.js +++ b/main.js @@ -1,4 +1,4 @@ -const { app, BrowserWindow, clipboard, dialog, ipcMain, Menu, protocol, screen, shell } = require('electron'); +const { app, BrowserWindow, clipboard, dialog, ipcMain, Menu, protocol, screen, shell, ShareMenu } = require('electron'); const { Worker } = require('worker_threads'); const path = require('path'); const fs = require('fs'); @@ -39,7 +39,7 @@ const { scanSchedules } = require('./schedule-runner'); const { encodeProjectPath } = require('./encode-project-path'); const { resolveEffectiveSettings } = require('./resolve-effective-settings'); const { listProjectDirectory, readProjectFile, readPreviewFile, openFileExternally } = require('./project-files'); -const { manageProjectEntry } = require('./file-management'); +const { manageProjectEntry, shareFile } = require('./file-management'); const { resolveTerminalFiles } = require('./terminal-file-links'); const { PREVIEW_SCHEME, PREVIEW_SCHEMES, handlePreviewAssetRequest } = require('./preview-assets'); protocol.registerSchemesAsPrivileged(PREVIEW_SCHEMES); @@ -555,6 +555,18 @@ ipcMain.handle('open-file-externally', async (_event, filePath, projectRoot) => } }); +// Share a viewer panel's file through the macOS share menu (AirDrop, Mail, +// Messages and any app with a share extension). Other systems have no such menu. +ipcMain.handle('share-file', (event, filePath) => { + try { + if (process.platform !== 'darwin') throw new Error('Sharing files is only available on macOS'); + const window = BrowserWindow.fromWebContents(event.sender); + return { ok: true, ...shareFile(filePath, { share: file => new ShareMenu({ filePaths: [file] }).popup({ window }) }) }; + } catch (err) { + return { ok: false, error: err.message }; + } +}); + ipcMain.handle('read-file-for-panel', async (_event, filePath) => { try { return { ok: true, ...readPreviewFile(filePath) }; diff --git a/preload.js b/preload.js index f98e36c73..400b54f51 100644 --- a/preload.js +++ b/preload.js @@ -183,6 +183,7 @@ contextBridge.exposeInMainWorld('api', { }, readFileForPanel: (filePath) => ipcRenderer.invoke('read-file-for-panel', filePath), openFileExternally: (filePath, projectRoot) => ipcRenderer.invoke('open-file-externally', filePath, projectRoot), + shareFile: (filePath) => ipcRenderer.invoke('share-file', filePath), resolveTerminalFiles: (references, context) => ipcRenderer.invoke('resolve-terminal-files', references, context), listProjectDirectory: (projectPath, relativePath) => ipcRenderer.invoke('list-project-directory', projectPath, relativePath), readProjectFile: (projectPath, relativePath) => ipcRenderer.invoke('read-project-file', projectPath, relativePath), diff --git a/public/viewer-panel.js b/public/viewer-panel.js index 9a5ef75ae..b42dbd729 100644 --- a/public/viewer-panel.js +++ b/public/viewer-panel.js @@ -10,6 +10,7 @@ * - Images, PDFs and PowerPoint: read-only previews with text editing controls hidden * - Wrap: shown for text (defaults on for markdown, off for others) * - Save: shown if onSave is provided + * - Share: macOS share menu, shown while a file is open * - Open in default app: always shown * - Close: shown if onClose is provided * - Copy path/content: shown if opted in @@ -53,6 +54,7 @@ class ViewerPanel { wrap: true, gotoLine: true, save: !!opts.onSave, + share: window.api.platform === 'darwin', openExternal: true, close: !!opts.onClose, }); @@ -112,6 +114,10 @@ class ViewerPanel { toolbar.saveBtn.addEventListener('click', () => this._save()); } + if (toolbar.shareBtn) { + toolbar.shareBtn.addEventListener('click', () => this._share()); + } + if (toolbar.openExternalBtn) { toolbar.openExternalBtn.addEventListener('click', () => this._openExternally()); } @@ -151,6 +157,7 @@ class ViewerPanel { this.previewType = preview.previewType || (/\.html?$/i.test(filePath) ? 'html' : 'text'); this.toolbar.setTitle(title); this.toolbar.setPath(filePath); + if (this.toolbar.shareBtn) this.toolbar.shareBtn.style.display = filePath ? '' : 'none'; const isMd = this._isMarkdown(filePath); const isJson = this._isJson(filePath); @@ -427,6 +434,17 @@ class ViewerPanel { } } + // Shares the file as saved on disk; unsaved edits stay in this editor. + async _share() { + if (!this.filePath) return; + try { + const shared = await window.api.shareFile(this.filePath); + if (!shared?.ok) throw new Error(shared?.error || 'Could not share the file.'); + } catch (error) { + alert(error.message || 'Could not share the file.'); + } + } + // Keep the current buffer when its file (or an ancestor folder) is renamed. async relocate(title, filePath) { this._unwatchFile(); diff --git a/public/viewer-toolbar.js b/public/viewer-toolbar.js index b1c957b13..7daf0f559 100644 --- a/public/viewer-toolbar.js +++ b/public/viewer-toolbar.js @@ -15,6 +15,8 @@ const PREVIEW_ICON = ' { + const { temp } = fixture(t); + const shared = []; + const share = file => shared.push(file); + const outside = path.join(fs.realpathSync(temp), 'elsewhere', 'plan.md'); + fs.mkdirSync(path.dirname(outside)); + fs.writeFileSync(outside, '# plan'); + assert.deepEqual(shareFile(path.join(temp, 'elsewhere', '..', 'elsewhere', 'plan.md'), { share }), { filePath: outside }); + assert.deepEqual(shared, [outside]); + assert.throws(() => shareFile('elsewhere/plan.md', { share }), /Invalid file path/); + assert.throws(() => shareFile(undefined, { share }), /Invalid file path/); + assert.throws(() => shareFile(path.join(temp, 'missing.md'), { share }), /does not exist/); + assert.throws(() => shareFile(path.dirname(outside), { share }), /Not a file/); + assert.equal(shared.length, 1); +}); diff --git a/test/viewer-panel.test.js b/test/viewer-panel.test.js index b7a91c8b7..cdc1cab94 100644 --- a/test/viewer-panel.test.js +++ b/test/viewer-panel.test.js @@ -15,7 +15,7 @@ function setup() { replaceChildren(...children) { this.children = children; }, }); const toolbar = { setTitle(title) { this.titleEl.textContent = title; }, setPath() {}, setWrapMode() {}, setPreviewMode() {} }; - for (const key of ['el', 'titleEl', 'previewBtn', 'wrapBtn', 'saveBtn', 'gotoLineBtn', 'copyContentBtn', 'openExternalBtn']) toolbar[key] = element(); + for (const key of ['el', 'titleEl', 'previewBtn', 'wrapBtn', 'saveBtn', 'gotoLineBtn', 'copyContentBtn', 'openExternalBtn', 'shareBtn']) toolbar[key] = element(); const revoked = []; let nextUrl = 0; let saved = 0; @@ -52,6 +52,26 @@ test('the toolbar opens the shown file in its default app and reports failures', assert.deepEqual(alerts, ['No default application']); }); +test('the share button hands the shown file to the share menu, media included, and reports failures', async () => { + const { panel, toolbar, api, media, alerts } = setup(); + const calls = []; + api.shareFile = async (...args) => { calls.push(args); return { ok: true }; }; + await toolbar.shareBtn.click(); + assert.deepEqual(calls, []); + panel.open('Plan', '/Users/me/plan.md', '# plan'); + assert.equal(toolbar.shareBtn.style.display, ''); + await toolbar.shareBtn.click(); + panel.open('Image', '/Users/me/shot.png', undefined, media); + assert.equal(toolbar.shareBtn.style.display, ''); + await toolbar.shareBtn.click(); + assert.deepEqual(calls, [['/Users/me/plan.md'], ['/Users/me/shot.png']]); + api.shareFile = async () => ({ ok: false, error: 'The file does not exist' }); + await toolbar.shareBtn.click(); + assert.deepEqual(alerts, ['The file does not exist']); + panel.open('Nothing', '', ''); + assert.equal(toolbar.shareBtn.style.display, 'none'); +}); + test('media previews cannot save binary files and switching files restores editing', async () => { const { panel, toolbar, media, revoked, saved } = setup(); panel.open('Code', '/app.js', 'const original = true;'); diff --git a/test/viewer-toolbar.test.js b/test/viewer-toolbar.test.js new file mode 100644 index 000000000..c16201c5f --- /dev/null +++ b/test/viewer-toolbar.test.js @@ -0,0 +1,32 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); + +function createToolbar(opts) { + const element = () => ({ + style: {}, children: [], className: '', title: '', + classList: { add() {}, remove() {}, toggle() {}, contains() { return false; } }, + setAttribute(name, value) { this[name] = value; }, + appendChild(child) { this.children.push(child); }, + }); + const window = { api: {} }; + const context = vm.createContext({ + window, navigator: { platform: '' }, + document: { createElement: element, addEventListener() {} }, + }); + vm.runInContext(fs.readFileSync(path.join(__dirname, '../public/viewer-toolbar.js'), 'utf8'), context); + return window.createViewerToolbar(opts); +} + +test('the share button sits right after Save and before Open in default app', () => { + const toolbar = createToolbar({ preview: true, wrap: true, save: true, share: true, openExternal: true, close: true }); + const controls = toolbar.el.children[1].children; + const at = button => controls.indexOf(button); + assert.equal(at(toolbar.shareBtn), at(toolbar.saveBtn) + 1); + assert.equal(at(toolbar.openExternalBtn), at(toolbar.shareBtn) + 1); + assert.equal(toolbar.shareBtn.title, 'Share'); + assert.equal(toolbar.shareBtn['aria-label'], 'Share'); + assert.equal(createToolbar({ save: true, close: true }).shareBtn, null); +});