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:
Sam Zhou 2020-03-15 01:47:52 -04:00 committed by GitHub
parent da0a61d1f0
commit 55a50d37dc
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 268 additions and 30 deletions

View file

@ -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;