react-bionic-reading
Version:
A React component that implements the bionic reading method.
86 lines (82 loc) • 2.44 kB
JavaScript
// src/utils/bionic.utils.tsx
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
var SplitForBionicText = (word) => {
const half = Math.ceil(word.length / 2);
return {
bold: word.slice(0, half),
rest: word.slice(half)
};
};
var ApplyBionicText = (text) => {
const trimmedText = text.trim();
if (!trimmedText) return /* @__PURE__ */ jsx(Fragment, {});
const words = trimmedText.split(/\s+/);
return /* @__PURE__ */ jsx(Fragment, { children: words.map((word, index) => {
const { bold, rest } = SplitForBionicText(word);
return /* @__PURE__ */ jsxs("span", { children: [
/* @__PURE__ */ jsx("strong", { children: bold }),
rest,
" "
] }, index);
}) });
};
// src/store/useBionic.ts
import { create } from "zustand";
import { persist } from "zustand/middleware";
var useBionic = create()(
persist(
(set) => ({
bionicMode: true,
setBionicMode: (bionicMode) => set({ bionicMode })
}),
{
name: "bionic-storage"
}
)
);
// src/components/bionic-text/bionic-text.tsx
import { jsx as jsx2 } from "react/jsx-runtime";
var BionicText = ({
text,
as: Component = "span",
style,
className,
forceBionicMode = false
}) => {
const { bionicMode } = useBionic();
const isBionicModeEnabled = forceBionicMode || bionicMode;
return /* @__PURE__ */ jsx2(Component, { style, className, children: isBionicModeEnabled ? ApplyBionicText(text) : text });
};
// src/components/bionic-block/bionic-block.tsx
import React, { isValidElement } from "react";
import { Fragment as Fragment2, jsx as jsx3 } from "react/jsx-runtime";
var BionicBlock = ({
children,
forceBionicMode = false
}) => {
const { bionicMode } = useBionic();
const isBionicModeEnabled = forceBionicMode || bionicMode;
const transform = (node) => {
if (typeof node === "string") {
return ApplyBionicText(node);
}
if (Array.isArray(node)) {
return node.map((child, index) => /* @__PURE__ */ jsx3(React.Fragment, { children: transform(child) }, index));
}
if (isValidElement(node)) {
const { children: nodeChildren, ...restProps } = node.props;
return React.cloneElement(
node,
restProps,
transform(nodeChildren)
);
}
return node;
};
return /* @__PURE__ */ jsx3(Fragment2, { children: isBionicModeEnabled ? transform(children) : children });
};
export {
BionicBlock,
BionicText,
useBionic
};