GrammarRecent.tsx 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import { List } from "antd";
  2. const maxRecent = 10;
  3. const storeKey = "grammar-handbook/recent";
  4. export interface IGrammarRecent {
  5. title: string;
  6. description?: string;
  7. word?: string;
  8. wordId?: string;
  9. }
  10. export const popRecent = (): IGrammarRecent | null => {
  11. const old = localStorage.getItem(storeKey);
  12. if (old) {
  13. const recentList = JSON.parse(old);
  14. const top = recentList.shift();
  15. localStorage.setItem(storeKey, JSON.stringify(recentList));
  16. return top;
  17. } else {
  18. return null;
  19. }
  20. };
  21. export const pushRecent = (value: IGrammarRecent) => {
  22. const old = localStorage.getItem(storeKey);
  23. if (old) {
  24. const newRecent = [value, ...JSON.parse(old)].slice(0, maxRecent - 1);
  25. localStorage.setItem(storeKey, JSON.stringify(newRecent));
  26. } else {
  27. localStorage.setItem(storeKey, JSON.stringify([value]));
  28. }
  29. };
  30. interface IWidget {
  31. onClick?: Function;
  32. }
  33. const GrammarRecentWidget = ({ onClick }: IWidget) => {
  34. const data = localStorage.getItem(storeKey);
  35. let items: IGrammarRecent[] = [];
  36. if (data) {
  37. items = JSON.parse(data);
  38. }
  39. return (
  40. <List
  41. header={"最近搜索"}
  42. size="small"
  43. dataSource={items}
  44. renderItem={(item, index) => (
  45. <List.Item
  46. key={index}
  47. style={{ cursor: "pointer" }}
  48. onClick={() => {
  49. if (typeof onClick !== "undefined") {
  50. onClick(item);
  51. }
  52. }}
  53. >
  54. <List.Item.Meta title={item.title} description={item.description} />
  55. </List.Item>
  56. )}
  57. />
  58. );
  59. };
  60. export default GrammarRecentWidget;