Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion file-management.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
16 changes: 14 additions & 2 deletions main.js
Original file line number Diff line number Diff line change
@@ -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');
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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) };
Expand Down
1 change: 1 addition & 0 deletions preload.js
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
18 changes: 18 additions & 0 deletions public/viewer-panel.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -53,6 +54,7 @@ class ViewerPanel {
wrap: true,
gotoLine: true,
save: !!opts.onSave,
share: window.api.platform === 'darwin',
openExternal: true,
close: !!opts.onClose,
});
Expand Down Expand Up @@ -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());
}
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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();
Expand Down
15 changes: 15 additions & 0 deletions public/viewer-toolbar.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ const PREVIEW_ICON = '<svg stroke="currentColor" fill="currentColor" stroke-widt

const GOTO_LINE_ICON = '<svg stroke="currentColor" fill="none" stroke-width="2" viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round" width="14" height="14" xmlns="http://www.w3.org/2000/svg"><path d="M14 2v4a2 2 0 0 0 2 2h4"></path><path d="M4.268 21a2 2 0 0 0 1.727 1H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v3"></path><path d="m9 18-1.5-1.5"></path><circle cx="5" cy="14" r="3"></circle><g stroke="currentColor" stroke-width="1" text-anchor="middle" font-family="monospace" font-size="8"><text x="10" y="10">1</text><text x="14" y="18">2</text></g></svg>';

const SHARE_ICON = '<svg stroke="currentColor" fill="none" stroke-width="2" viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round" width="14" height="14" xmlns="http://www.w3.org/2000/svg"><path d="M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"></path><path d="M16 6l-4-4-4 4"></path><path d="M12 2v13"></path></svg>';

const OPEN_EXTERNAL_ICON = '<svg stroke="currentColor" fill="none" stroke-width="2" viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round" width="14" height="14" xmlns="http://www.w3.org/2000/svg"><path d="M15 3h6v6"></path><path d="M10 14 21 3"></path><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"></path></svg>';

const CLOSE_ICON = '<svg stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 512 512" width="14" height="14" xmlns="http://www.w3.org/2000/svg"><path d="M400 145.49 366.51 112 256 222.51 145.49 112 112 145.49 222.51 256 112 366.51 145.49 400 256 289.49 366.51 400 400 366.51 289.49 256 400 145.49z"></path></svg>';
Expand Down Expand Up @@ -68,6 +70,7 @@ function toggleMarkdownPreview({ editorEl, previewEl, toggleBtn, editorView, isP
* @param {boolean} opts.preview - Show preview toggle
* @param {boolean} opts.wrap - Show wrap toggle
* @param {boolean} opts.save - Show save button
* @param {boolean} opts.share - Show share button
* @param {boolean} opts.openExternal - Show open-in-default-app button
* @param {boolean} opts.close - Show close button
* @param {boolean} opts.diffToggle - Show diff mode toggle
Expand All @@ -79,6 +82,7 @@ function toggleMarkdownPreview({ editorEl, previewEl, toggleBtn, editorView, isP
* .previewBtn - Preview button (or null)
* .wrapBtn - Wrap button (or null)
* .saveBtn - Save button (or null)
* .shareBtn - Share button (or null)
* .openExternalBtn - Open-in-default-app button (or null)
* .closeBtn - Close button (or null)
* .copyPathBtn - Copy path button (or null)
Expand Down Expand Up @@ -173,6 +177,16 @@ function createViewerToolbar(opts = {}) {
controlsEl.appendChild(saveBtn);
}

let shareBtn = null;
if (opts.share) {
shareBtn = document.createElement('button');
shareBtn.className = 'fp-toolbar-btn fp-icon-btn';
shareBtn.title = 'Share';
shareBtn.setAttribute('aria-label', shareBtn.title);
shareBtn.innerHTML = SHARE_ICON;
controlsEl.appendChild(shareBtn);
}

let openExternalBtn = null;
if (opts.openExternal) {
openExternalBtn = document.createElement('button');
Expand Down Expand Up @@ -202,6 +216,7 @@ function createViewerToolbar(opts = {}) {
previewBtn,
wrapBtn,
saveBtn,
shareBtn,
openExternalBtn,
closeBtn,
copyPathBtn,
Expand Down
18 changes: 17 additions & 1 deletion test/file-management.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { manageProjectEntry } = require('../file-management');
const { manageProjectEntry, shareFile } = require('../file-management');

function fixture(t) {
const temp = fs.mkdtempSync(path.join(os.tmpdir(), 'switchboard-file-actions-'));
Expand Down Expand Up @@ -109,3 +109,19 @@ test('replacing an item during confirmation cannot trash its replacement', async
assert.deepEqual(calls, []);
assert.equal(fs.readFileSync(file, 'utf8'), 'replacement');
});

test('shareFile shares any existing absolute file, resolved, and nothing else', t => {
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);
});
22 changes: 21 additions & 1 deletion test/viewer-panel.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;');
Expand Down
32 changes: 32 additions & 0 deletions test/viewer-toolbar.test.js
Original file line number Diff line number Diff line change
@@ -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);
});
Loading