Skip to content

Commit dbc1f7f

Browse files
authored
Merge pull request #140 from mongoosejs/codex/store-search-in-url-for-document-details
Persist document field search in URL
2 parents 4809840 + 18398ea commit dbc1f7f

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

frontend/src/document-details/document-details.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@ module.exports = app => app.component('document-details', {
3737
this.initializeFieldValueEditor();
3838
}
3939
});
40+
41+
this.searchQuery = this.getSearchQueryFromRoute();
4042
},
4143
beforeDestroy() {
4244
this.destroyFieldValueEditor();
@@ -55,6 +57,17 @@ module.exports = app => app.component('document-details', {
5557
});
5658
}
5759
}
60+
},
61+
searchQuery(newValue) {
62+
this.syncSearchQueryToUrl(newValue);
63+
},
64+
'$route.query.fieldSearch': {
65+
handler(newValue) {
66+
const nextValue = typeof newValue === 'string' ? newValue : '';
67+
if (nextValue !== this.searchQuery) {
68+
this.searchQuery = nextValue;
69+
}
70+
}
5871
}
5972
},
6073
computed: {
@@ -245,6 +258,35 @@ module.exports = app => app.component('document-details', {
245258
}
246259
},
247260
methods: {
261+
getSearchQueryFromRoute() {
262+
return this.$route?.query?.fieldSearch || '';
263+
},
264+
syncSearchQueryToUrl(value) {
265+
if (typeof window === 'undefined') {
266+
return;
267+
}
268+
269+
const normalizedValue = typeof value === 'string' ? value : '';
270+
const shouldStore = normalizedValue.trim().length > 0;
271+
const hash = window.location.hash.replace(/^#?/, '');
272+
const [hashPath, hashQueryString = ''] = hash.split('?');
273+
const params = new URLSearchParams(hashQueryString);
274+
const currentValue = params.get('fieldSearch') || '';
275+
276+
if (normalizedValue === currentValue || (!shouldStore && !currentValue)) {
277+
return;
278+
}
279+
280+
if (shouldStore) {
281+
params.set('fieldSearch', normalizedValue);
282+
} else {
283+
params.delete('fieldSearch');
284+
}
285+
286+
const nextQueryString = params.toString();
287+
const nextHash = nextQueryString ? `${hashPath}?${nextQueryString}` : hashPath;
288+
window.history.replaceState(window.history.state, '', `#${nextHash}`);
289+
},
248290
toggleVirtualField(fieldName) {
249291
if (this.collapsedVirtuals.has(fieldName)) {
250292
this.collapsedVirtuals.delete(fieldName);

0 commit comments

Comments
 (0)