mirror of
https://github.com/facebook/docusaurus.git
synced 2025-06-09 06:12:28 +02:00
feat(v2): support syncing tab choices (#2366)
* feat(v2): Support syncing tab choices * Move docs changes to website/docs * Do not import entire React in TabGroupChoiceContext * Store only one tab choice according to discussion in PR * Remove leftover logging code during debugging * Put storage value in separate const outside the hook-level * Use an array to keep track of different tab groups * Revert back to using `groupId` * Update markdown-features.mdx * Update markdown-features.mdx Co-authored-by: Yangshun Tay <tay.yang.shun@gmail.com>
This commit is contained in:
parent
da0a61d1f0
commit
55a50d37dc
8 changed files with 268 additions and 30 deletions
|
@ -0,0 +1,47 @@
|
|||
/**
|
||||
* Copyright (c) Facebook, Inc. and its affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import {useState, useCallback, useEffect} from 'react';
|
||||
|
||||
const TAB_CHOICE_PREFIX = 'docusaurus.tab.';
|
||||
|
||||
const useTabGroupChoice = () => {
|
||||
const [tabGroupChoices, setChoices] = useState({});
|
||||
const setChoiceSyncWithLocalStorage = useCallback((groupId, newChoice) => {
|
||||
try {
|
||||
localStorage.setItem(`${TAB_CHOICE_PREFIX}${groupId}`, newChoice);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
try {
|
||||
const localStorageChoices = {};
|
||||
for (let i = 0; i < localStorage.length; i += 1) {
|
||||
const storageKey = localStorage.key(i);
|
||||
if (storageKey.startsWith(TAB_CHOICE_PREFIX)) {
|
||||
const groupId = storageKey.substring(TAB_CHOICE_PREFIX.length);
|
||||
localStorageChoices[groupId] = localStorage.getItem(storageKey);
|
||||
}
|
||||
}
|
||||
setChoices(localStorageChoices);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
}
|
||||
}, []);
|
||||
|
||||
return {
|
||||
tabGroupChoices,
|
||||
setTabGroupChoices: (groupId, newChoice) => {
|
||||
setChoices(oldChoices => ({...oldChoices, [groupId]: newChoice}));
|
||||
setChoiceSyncWithLocalStorage(groupId, newChoice);
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export default useTabGroupChoice;
|
Loading…
Add table
Add a link
Reference in a new issue