mirror of
https://github.com/HeyPuter/puter.git
synced 2026-11-25 07:09:11 +00:00
fix(gui): a file picker opens in the view and sort last chosen in one
This commit is contained in:
1 parent
d0a75e3b2e
commit
2c4db5d4d1
3 files changed
+173
-20
No files matched your search
@@ -66,34 +66,102 @@ const encode = (value) => window.html_encode(value);
|
||||
/** On a Mac, Ctrl+click is a right-click; Cmd is what adds to a selection. */
|
||||
const CTRL_CLICK_IS_SECONDARY = /mac/i.test(navigator.userAgentData?.platform ?? navigator.platform ?? '');
|
||||
|
||||
// The saved view, read once per page.
|
||||
let savedPrefs = null;
|
||||
// Where the view and sort chosen in a picker are saved, as JSON.
|
||||
const PICKER_PREFS_KEY = 'file_picker_view';
|
||||
const SAVED_PREFS_KEYS = [PICKER_PREFS_KEY, 'view_mode', 'sort_column', 'sort_direction'];
|
||||
|
||||
// One account's saved views, read once per page.
|
||||
let prefsAccount;
|
||||
let savedPrefsRead = null;
|
||||
/** @type {Partial<FilePickerViewPrefs>} The Files tab's saved view and sort */
|
||||
let savedFilesPrefs = {};
|
||||
/** @type {Partial<FilePickerViewPrefs>} What was chosen in a picker: the saved choices, with this page's over them */
|
||||
let pickerChoices = {};
|
||||
|
||||
/**
|
||||
* The view and sort a picker opens with: the Files tab's, else the saved
|
||||
* preference. A change made in a picker stays in that picker; the Files
|
||||
* tab's preference stays as the user set it there.
|
||||
* Reads the account's saved views, once per page.
|
||||
*
|
||||
* @returns {Promise<void>} Resolves when they're in, or couldn't be read
|
||||
*/
|
||||
function readSavedPrefs () {
|
||||
const account = window.user?.uuid ?? window.user?.username;
|
||||
if ( account !== prefsAccount ) {
|
||||
prefsAccount = account;
|
||||
savedPrefsRead = null;
|
||||
savedFilesPrefs = {};
|
||||
pickerChoices = {};
|
||||
}
|
||||
savedPrefsRead ??= Promise.resolve()
|
||||
.then(() => window.puter.kv.get(SAVED_PREFS_KEYS))
|
||||
.then(([choices, view, sortColumn, sortDirection]) => {
|
||||
if ( account !== prefsAccount ) return;
|
||||
savedFilesPrefs = { view, sortColumn, sortDirection };
|
||||
// A choice made while the read was out is the newer one.
|
||||
pickerChoices = { ...savedChoices(choices), ...pickerChoices };
|
||||
})
|
||||
.catch(() => {});
|
||||
return savedPrefsRead;
|
||||
}
|
||||
|
||||
/**
|
||||
* The view and sort a picker opens with: what was last chosen in a picker,
|
||||
* and the Files tab's for the rest.
|
||||
*
|
||||
* @returns {Promise<FilePickerViewPrefs>}
|
||||
*/
|
||||
function loadViewPrefs () {
|
||||
const files = window.dashboard_object;
|
||||
if ( files?.currentView ) {
|
||||
return Promise.resolve(validPrefs([files.currentView, files.sortColumn, files.sortDirection]));
|
||||
}
|
||||
const read = (key) => Promise.resolve().then(() => window.puter.kv.get(key)).catch(() => null);
|
||||
savedPrefs ??= Promise.race([
|
||||
Promise.all([read('view_mode'), read('sort_column'), read('sort_direction')]),
|
||||
new Promise(resolve => setTimeout(() => resolve([]), PREFS_TIMEOUT_MS)),
|
||||
]).then(validPrefs);
|
||||
return savedPrefs.then(prefs => ({ ...prefs }));
|
||||
const timeout = new Promise(resolve => setTimeout(resolve, PREFS_TIMEOUT_MS));
|
||||
return Promise.race([readSavedPrefs(), timeout]).then(() => {
|
||||
const files = window.dashboard_object;
|
||||
const filesPrefs = files?.currentView
|
||||
? { view: files.currentView, sortColumn: files.sortColumn, sortDirection: files.sortDirection }
|
||||
: savedFilesPrefs;
|
||||
return validPrefs({ ...filesPrefs, ...pickerChoices });
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Array<unknown>} values - View, sort column and sort direction, as stored
|
||||
* Remembers a view or sort chosen in a picker for the pickers opened after
|
||||
* it, on this page and from the account's saved choices. The Files tab's
|
||||
* own preference stays as the user set it there.
|
||||
*
|
||||
* @param {Partial<FilePickerViewPrefs>} choice
|
||||
* @returns {void}
|
||||
*/
|
||||
function rememberChoice (choice) {
|
||||
pickerChoices = { ...pickerChoices, ...choice };
|
||||
// After the read, so the save keeps the saved choices this one doesn't replace.
|
||||
readSavedPrefs()
|
||||
.then(() => window.puter.kv.set(PICKER_PREFS_KEY, JSON.stringify(pickerChoices)))
|
||||
.catch(err => console.warn(`Could not save ${PICKER_PREFS_KEY}:`, err));
|
||||
}
|
||||
|
||||
/**
|
||||
* The choices in a saved value that can be used.
|
||||
*
|
||||
* @param {unknown} stored - The saved JSON, or what it parses to
|
||||
* @returns {Partial<FilePickerViewPrefs>}
|
||||
*/
|
||||
function savedChoices (stored) {
|
||||
let saved = stored;
|
||||
try {
|
||||
if ( typeof stored === 'string' ) saved = JSON.parse(stored);
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
if ( ! saved || typeof saved !== 'object' ) return {};
|
||||
const choices = {};
|
||||
if ( VIEWS.includes(saved.view) ) choices.view = saved.view;
|
||||
if ( SORT_COLUMNS.includes(saved.sortColumn) ) choices.sortColumn = saved.sortColumn;
|
||||
if ( ['asc', 'desc'].includes(saved.sortDirection) ) choices.sortDirection = saved.sortDirection;
|
||||
return choices;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{ view?: unknown, sortColumn?: unknown, sortDirection?: unknown }} [values] - As stored
|
||||
* @returns {FilePickerViewPrefs}
|
||||
*/
|
||||
function validPrefs ([view, sortColumn, sortDirection] = []) {
|
||||
function validPrefs ({ view, sortColumn, sortDirection } = {}) {
|
||||
return {
|
||||
view: VIEWS.includes(view) ? view : 'list',
|
||||
sortColumn: SORT_COLUMNS.includes(sortColumn) ? sortColumn : 'name',
|
||||
@@ -1102,6 +1170,7 @@ export default class FilePicker {
|
||||
if ( ! SORT_COLUMNS.includes(column) ) return;
|
||||
this.prefs.sortDirection = this.activeSortColumn() === column && this.prefs.sortDirection === 'asc' ? 'desc' : 'asc';
|
||||
this.prefs.sortColumn = column;
|
||||
rememberChoice({ sortColumn: column, sortDirection: this.prefs.sortDirection });
|
||||
// Shown at once: the re-sorted listing is a round trip away.
|
||||
this.updateSortIndicators();
|
||||
this.refresh();
|
||||
@@ -1114,6 +1183,7 @@ export default class FilePicker {
|
||||
setView (view) {
|
||||
if ( this.prefs.view === view ) return;
|
||||
this.prefs.view = view;
|
||||
rememberChoice({ view });
|
||||
this.applyViewMode();
|
||||
// Grid tiles show thumbnails where list rows show type icons.
|
||||
this.refresh();
|
||||
|
||||
@@ -68,9 +68,12 @@ const settle = async () => {
|
||||
for ( let i = 0; i < 5; i++ ) await new Promise(resolve => setTimeout(resolve, 0));
|
||||
};
|
||||
|
||||
// A new account each test: a picker's view and sort are remembered per account.
|
||||
let accounts = 0;
|
||||
|
||||
beforeEach(() => {
|
||||
Object.assign(window, {
|
||||
user: { username: 'alice' },
|
||||
user: { username: 'alice', uuid: `alice-${++accounts}` },
|
||||
home_path: '/alice',
|
||||
desktop_path: DESKTOP,
|
||||
docs_path: '/alice/Documents',
|
||||
@@ -90,7 +93,10 @@ beforeEach(() => {
|
||||
check_fsentry_against_allowed_file_types_string: (entry, allowed) => ! allowed
|
||||
|| allowed.split(',').some(ext => entry.name.endsWith(ext.trim())),
|
||||
puter: {
|
||||
kv: { get: vi.fn(async () => null) },
|
||||
kv: {
|
||||
get: vi.fn(async keys => (Array.isArray(keys) ? keys.map(() => null) : null)),
|
||||
set: vi.fn(async () => true),
|
||||
},
|
||||
fs: {
|
||||
readdir: vi.fn(async ({ path }) => {
|
||||
if ( ! folders[path] ) throw new Error('not found');
|
||||
@@ -693,4 +699,57 @@ describe('view preferences', () => {
|
||||
expect(dialog.$('.files').hasClass('files-grid-view')).toBe(true);
|
||||
expect(dialog.$('.sortable[data-sort="size"]').hasClass('sort-desc')).toBe(true);
|
||||
});
|
||||
|
||||
it('opens the next picker in the view and sort chosen in the last one, and saves them apart from the Files tab\'s', async () => {
|
||||
const first = await openDialog({ is_openFileDialog: true });
|
||||
first.picker.setView('grid-sm');
|
||||
first.$('.header .columns .sortable[data-sort="size"]').trigger('click');
|
||||
first.$('.header .columns .sortable[data-sort="size"]').trigger('click');
|
||||
await settle();
|
||||
first.$('.filedialog-cancel-btn').trigger('click');
|
||||
document.body.innerHTML = '';
|
||||
|
||||
const second = await openDialog({ is_saveFileDialog: true });
|
||||
|
||||
expect(second.$('.files').hasClass('files-grid-view-sm')).toBe(true);
|
||||
expect(second.$('.sortable[data-sort="size"]').hasClass('sort-desc')).toBe(true);
|
||||
expect(window.puter.kv.set).toHaveBeenLastCalledWith('file_picker_view',
|
||||
JSON.stringify({ view: 'grid-sm', sortColumn: 'size', sortDirection: 'desc' }));
|
||||
expect(window.puter.kv.set.mock.calls.every(([key]) => key === 'file_picker_view')).toBe(true);
|
||||
// One read serves every picker on the page.
|
||||
expect(window.puter.kv.get).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('opens in the view saved from a picker, and follows the Files tab for what no picker chose', async () => {
|
||||
window.dashboard_object = { currentView: 'grid', sortColumn: 'size', sortDirection: 'desc' };
|
||||
window.puter.kv.get.mockResolvedValue([JSON.stringify({ view: 'list', sortColumn: 'nonsense' }), 'grid', 'name', 'asc']);
|
||||
|
||||
const dialog = await openDialog({ is_openFileDialog: true });
|
||||
|
||||
expect(dialog.$('.files').hasClass('files-list-view')).toBe(true);
|
||||
expect(dialog.$('.sortable[data-sort="size"]').hasClass('sort-desc')).toBe(true);
|
||||
});
|
||||
|
||||
it('keeps the saved sort when only the view is changed', async () => {
|
||||
window.puter.kv.get.mockResolvedValue([JSON.stringify({ sortColumn: 'modified', sortDirection: 'desc' }), null, null, null]);
|
||||
const dialog = await openDialog({ is_openFileDialog: true });
|
||||
|
||||
dialog.picker.setView('grid');
|
||||
await settle();
|
||||
|
||||
expect(window.puter.kv.set).toHaveBeenLastCalledWith('file_picker_view',
|
||||
JSON.stringify({ sortColumn: 'modified', sortDirection: 'desc', view: 'grid' }));
|
||||
});
|
||||
|
||||
it('doesn\'t carry one account\'s choices to another signed in on the same page', async () => {
|
||||
const first = await openDialog({ is_openFileDialog: true });
|
||||
first.picker.setView('grid');
|
||||
await settle();
|
||||
document.body.innerHTML = '';
|
||||
window.user = { username: 'bob', uuid: 'bob-1' };
|
||||
|
||||
const second = await openDialog({ is_openFileDialog: true });
|
||||
|
||||
expect(second.$('.files').hasClass('files-list-view')).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -16,9 +16,11 @@ const pickerWindow = (page) => page.locator('.window.window-filedialog');
|
||||
const row = (picker, name) => picker.locator(`.files .row.item[data-name="${name}"]`);
|
||||
const logged = (appFrame) => appFrame.locator('[data-testid="log"] div');
|
||||
|
||||
// The Desktop with a folder, two text files and an image, and no earlier save.
|
||||
// The Desktop with a folder, two text files and an image, no earlier save,
|
||||
// and no view remembered from an earlier picker.
|
||||
async function seedDesktop (page) {
|
||||
await page.evaluate(async ({ folder, files, saved }) => {
|
||||
await window.puter.kv.del('file_picker_view').catch(() => {});
|
||||
const desktop = `/${window.user.username}/Desktop`;
|
||||
await window.puter.fs.mkdir(`${desktop}/${folder}`, { dedupeName: false }).catch(() => {});
|
||||
for ( const name of files ) {
|
||||
@@ -239,6 +241,28 @@ test.describe('file pickers (env=app)', () => {
|
||||
expect(gap).toBe(0);
|
||||
});
|
||||
|
||||
test('a picker opens in the view chosen in the last one, here and after a reload', async ({ page }) => {
|
||||
const { picker, appFrame } = await openPicker(page, appName);
|
||||
await expect(picker.locator('.files')).toHaveClass(/files-list-view/);
|
||||
await picker.locator('.view-toggle-btn').click();
|
||||
await page.locator('.context-menu .context-menu-item', { hasText: 'Compact Grid' }).last().click();
|
||||
await expect(picker.locator('.files')).toHaveClass(/files-grid-view-sm/);
|
||||
await picker.locator('.filedialog-cancel-btn').click();
|
||||
await expect(picker).toHaveCount(0);
|
||||
|
||||
await appFrame.locator('#save-file').click();
|
||||
await expect(row(picker, FOLDER)).toBeVisible();
|
||||
await expect(picker.locator('.files')).toHaveClass(/files-grid-view-sm/);
|
||||
// Saved before the page goes away.
|
||||
await expect.poll(() => page.evaluate(() => window.puter.kv.get('file_picker_view'))).toContain('grid-sm');
|
||||
|
||||
const reloaded = await gotoTestApp(page, appName);
|
||||
await reloaded.locator('#pick-directory').click();
|
||||
await expect(row(picker, FOLDER)).toBeVisible();
|
||||
await expect(picker.locator('.files')).toHaveClass(/files-grid-view-sm/);
|
||||
await page.evaluate(() => window.puter.kv.del('file_picker_view').catch(() => {}));
|
||||
});
|
||||
|
||||
test('Escape cancels the picker', async ({ page }) => {
|
||||
const { picker, appFrame } = await openPicker(page, appName, '#open-files');
|
||||
|
||||
|
||||
Reference in new issue
Block a user