Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@ CHANGELOG.md
.yarn_home/
/test/integration/
/storybook-static/

!.storybook
57 changes: 27 additions & 30 deletions .storybook/DocsContainer.js → .storybook/DocsContainer.tsx
Original file line number Diff line number Diff line change
@@ -1,33 +1,44 @@

import React, { useEffect } from "react";
import { DocsContainer as BaseContainer } from "@storybook/addon-docs";
import { useDarkMode } from "storybook-dark-mode";
import React, { PropsWithChildren, useEffect } from "react";
import {
DocsContainer as BaseContainer,
DocsContainerProps,
Unstyled
} from "@storybook/addon-docs/blocks";
import { useDarkMode } from "@vueless/storybook-dark-mode";
import { darkTheme, lightTheme } from "./customTheme";
import "../dist/dsfr/utility/icons/icons.min.css";
import "../dist/dsfr/dsfr.css";
import { useIsDark } from "../dist/useIsDark";
import { startReactDsfr } from "../dist/spa";
import { fr } from "../dist/fr";
import { MuiDsfrThemeProvider } from "../dist/mui";
import { TableOfContentsCustom, TocType } from "./TableOfContents";

startReactDsfr({
"defaultColorScheme": "system",
"useLang": () => "fr"
});

export const DocsContainer = ({ children, context }) => {
export const DocsContainer = ({ children, context }: PropsWithChildren<DocsContainerProps>) => {
const isStorybookUiDark = useDarkMode();
const { setIsDark } = useIsDark();

useEffect(
()=> {
setIsDark(isStorybookUiDark);
},
[isStorybookUiDark]
);
useEffect(() => {
setIsDark(isStorybookUiDark);
}, [isStorybookUiDark]);

const backgroundColor = fr.colors.decisions.background.default.grey.default;

// took from addon-docs/src/blocks/DocsContainer.tsx
let toc: TocType | undefined;
try {
const meta = context.resolveOf("meta", ["meta"]);
toc = meta.preparedMeta.parameters?.docs?.toc;
} catch (err) {
// No meta, falling back to project annotations
toc = context?.projectAnnotations?.parameters?.docs?.toc;
}

return (
<>
<style>{`
Expand All @@ -52,26 +63,12 @@ export const DocsContainer = ({ children, context }) => {
}

`}</style>
<BaseContainer
context={{
...context,
"storyById": id => {
const storyContext = context.storyById(id);
return {
...storyContext,
"parameters": {
...storyContext?.parameters,
"docs": {
...storyContext?.parameters?.docs,
"theme": isStorybookUiDark ? darkTheme : lightTheme
}
}
};
}
}}
>
<BaseContainer context={context} theme={isStorybookUiDark ? darkTheme : lightTheme}>
<MuiDsfrThemeProvider>
{children}
<Unstyled>
{toc && <TableOfContentsCustom channel={context.channel} />}
{children}
</Unstyled>
</MuiDsfrThemeProvider>
</BaseContainer>
</>
Expand Down
7 changes: 7 additions & 0 deletions .storybook/Stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import React from "react";
import { Stories as BaseStories } from "@storybook/addon-docs/blocks";
import { type PropsOf } from "@emotion/react";

export const Stories = (props: PropsOf<typeof BaseStories>) => {
return <BaseStories {...props} />;
};
156 changes: 156 additions & 0 deletions .storybook/TableOfContents.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
import { styled } from "storybook/theming";
import SideMenu, { SideMenuProps } from "../dist/SideMenu";
import Channel from "storybook/internal/channels";
import { NAVIGATE_URL } from "storybook/internal/core-events";
import React, { useEffect, useState } from "react";
import { DocsTypes } from "@storybook/addon-docs";

export type TocType = Exclude<Required<DocsTypes["parameters"]>["docs"]["toc"], undefined>;

const Aside = styled.div`
position: fixed;
right: 4rem;
top: 0;
bottom: 0;
width: 16rem;
z-index: 1;
overflow: auto;
padding-top: 4rem;
padding-bottom: 2rem;
padding-left: 1rem;
padding-right: 1rem;

-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
-webkit-overflow-scrolling: touch;

@media (max-width: 768px) {
display: none;
}

& .fr-sidemenu__inner {
padding: 0;
}

& .fr-sidemenu__link {
padding: 0.5rem 0.75rem;
}
`;

/**
* Hook pour détecter le heading actuellement visible avec IntersectionObserver
*/
function useActiveHeading(headings: HTMLHeadingElement[]) {
const [activeId, setActiveId] = useState<string>("");

useEffect(() => {
if (headings.length === 0) return;

// Map pour stocker les ratios d'intersection de chaque heading
const headingObservers = new Map<string, number>();

const observer = new IntersectionObserver(
entries => {
// Mettre à jour le ratio d'intersection pour chaque heading observé
entries.forEach(entry => {
const id = entry.target.id;
if (entry.isIntersecting) {
headingObservers.set(id, entry.intersectionRatio);
} else {
headingObservers.set(id, 0);
}
});

// Trouver le heading avec le plus grand ratio d'intersection
let maxRatio = 0;
let activeHeadingId = "";

headingObservers.forEach((ratio, id) => {
if (ratio > maxRatio) {
maxRatio = ratio;
activeHeadingId = id;
}
});

// Ne mettre à jour que si on a trouvé un heading visible
// Sinon on garde l'état précédent
if (activeHeadingId && activeHeadingId !== activeId) {
setActiveId(activeHeadingId);
} else if (!activeId && headings.length > 0) {
// Cas initial : si aucun heading n'est actif encore, prendre le premier
setActiveId(headings[0].id);
}
},
{
// rootMargin négatif = créer une zone "active" au centre du viewport
// "-20% 0px -35% 0px" = zone active entre 20% du haut et 65% du bas
rootMargin: "-20% 0px -35% 0px",
threshold: [0, 0.25, 0.5, 0.75, 1] // Observer à différents niveaux de visibilité
}
);

// Observer tous les headings
headings.forEach(heading => {
if (heading.id) {
observer.observe(heading);
headingObservers.set(heading.id, 0);
}
});

return () => {
observer.disconnect();
};
}, [headings, activeId]);

return activeId;
}

interface TableOfContentsCustomProps {
channel: Channel;
}

export const TableOfContentsCustom = ({ channel }: TableOfContentsCustomProps) => {
const [headingElements, setHeadingElements] = useState<HTMLHeadingElement[]>([]);

// Initialiser les headings une seule fois
useEffect(() => {
const contentElement = document.querySelector(".sbdocs-content");
const elements = Array.from(
contentElement?.querySelectorAll<HTMLHeadingElement>(
"h3:not(.docs-story *, .skip-toc)"
) ?? []
);
setHeadingElements(elements);
}, []);

// Utiliser le hook pour tracker l'ID actif
const activeId = useActiveHeading(headingElements);

// Créer les items avec isActive
const headings = headingElements.map<SideMenuProps.Item>(heading => ({
text: (heading.innerText || heading.textContent).trim(),
isActive: heading.id === activeId,
linkProps: {
href: `#${heading.id}`,
onClick(e) {
e.preventDefault();
if (e.currentTarget instanceof HTMLAnchorElement) {
const [, headerId] = e.currentTarget.href.split("#");
if (headerId) {
channel.emit(NAVIGATE_URL, { url: `#${headerId}` });
document.querySelector(`#${heading.id}`)?.scrollIntoView({
behavior: "smooth"
});
}
}
}
}
}));

return (
<Aside>
<SideMenu align="right" burgerMenuButtonText="Table des matières" items={headings} />
</Aside>
);
};
35 changes: 0 additions & 35 deletions .storybook/customTheme.js

This file was deleted.

35 changes: 35 additions & 0 deletions .storybook/customTheme.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { create } from "storybook/theming";

const brandImage = "logo.png";
const brandTitle = "@codegouvfr/react-dsfr";
const brandUrl = "https://github.com/codegouvfr/react-dsfr";
const fontBase = '"Marianne", arial, sans-serif';
const fontCode = "monospace";

export const darkTheme = create({
base: "dark",
appBg: "#1E1E1E",
appContentBg: "#161616",
barBg: "#161616",
colorSecondary: "#8585F6",
textColor: "#FFFFFF",
brandImage,
brandTitle,
brandUrl,
fontBase,
fontCode
});

export const lightTheme = create({
base: "light",
appBg: "#F6F6F6",
appContentBg: "#FFFFFF",
barBg: "#FFFFFF",
colorSecondary: "#000091",
textColor: "#212121",
brandImage,
brandTitle,
brandUrl,
fontBase,
fontCode
});
19 changes: 0 additions & 19 deletions .storybook/main.js

This file was deleted.

21 changes: 21 additions & 0 deletions .storybook/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { defineMain } from "@storybook/react-vite/node";

export default defineMain({
framework: "@storybook/react-vite",
features: {
backgrounds: false
},
stories: [
"../stories/*.mdx",
"../stories/*.stories.@(ts|tsx)",
"../stories/blocks/*.stories.@(ts|tsx)",
"../stories/charts/*.stories.@(ts|tsx)"
],
addons: [
"@vueless/storybook-dark-mode",
"@storybook/addon-links",
"@storybook/addon-a11y",
"@storybook/addon-docs"
],
staticDirs: ["../dist", "./static"]
});
20 changes: 20 additions & 0 deletions .storybook/manager-head.html
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,24 @@
[data-parent-id^="hidden"] {
display: none !important;
}

/* full manager loader (circle) */
body.dark div[aria-label^="Content is loading..."] {
border-color: rgb(133, 133, 246) rgba(130, 130, 243, 0.29) rgba(130, 130, 243, 0.29) !important;
mix-blend-mode: normal !important;
}

body:not(.dark) div[aria-label^="Content is loading..."] {
border-color: rgb(0, 0, 145) rgba(0, 0, 142, 0.29) rgba(0, 0, 142, 0.29) !important;
mix-blend-mode: normal !important;
}

/* full manager page loader (dsfr vars not available) */
body.dark section[aria-labelledby="main-preview-heading"] div:has(+ #storybook-preview-wrapper) {
background-color: #161616 !important;
}

body:not(.dark) section[aria-labelledby="main-preview-heading"] div:has(+ #storybook-preview-wrapper) {
background-color: #ffffff !important;
}
</style>
Loading