@storybook/react-native
Version:
A better way to develop React Native Components for your app
1,481 lines (1,466 loc) • 53.2 kB
JavaScript
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var index_exports = {};
__export(index_exports, {
RN_STORYBOOK_EVENTS: () => RN_STORYBOOK_EVENTS,
RN_STORYBOOK_STORAGE_KEY: () => RN_STORYBOOK_STORAGE_KEY,
STORYBOOK_STORY_ID_PARAM: () => STORYBOOK_STORY_ID_PARAM,
darkTheme: () => import_react_native_theming3.darkTheme,
getProjectAnnotations: () => getProjectAnnotations,
prepareStories: () => prepareStories,
start: () => start,
theme: () => import_react_native_theming3.theme,
updateView: () => updateView
});
module.exports = __toCommonJS(index_exports);
var import_react_native_theming3 = require("@storybook/react-native-theming");
// ../../node_modules/react-native-web/dist/exports/Platform/index.js
var Platform = {
OS: "web",
select: (obj) => "web" in obj ? obj.web : obj.default,
get isTesting() {
if (process.env.NODE_ENV === "test") {
return true;
}
return false;
},
get Version() {
return "0.0.0";
}
};
var Platform_default = Platform;
// src/polyfill.ts
if (Platform_default.OS !== "web") {
try {
let params = new URLSearchParams({ test: "1" });
params.get("test");
} catch {
const { setupURLPolyfill } = require("react-native-url-polyfill");
setupURLPolyfill();
}
}
// src/Start.tsx
var import_react_native4 = require("react-native");
var import_manager_api2 = require("storybook/manager-api");
var import_preview_api2 = require("storybook/internal/preview-api");
var import_csf2 = require("storybook/internal/csf");
var import_channels2 = require("storybook/internal/channels");
// src/View.tsx
var import_csf = require("storybook/internal/csf");
var import_react_native_theming2 = require("@storybook/react-native-theming");
var import_react_native_ui_common = require("@storybook/react-native-ui-common");
var import_channels = require("storybook/internal/channels");
var import_core_events = require("storybook/internal/core-events");
var import_manager_api = require("storybook/manager-api");
var import_preview_api = require("storybook/internal/preview-api");
var import_dedent = __toESM(require("dedent"));
var import_deepmerge = __toESM(require("deepmerge"));
var import_react4 = require("react");
var import_react_native3 = require("react-native");
// src/components/StoryView/StoryView.tsx
var import_react_native_theming = require("@storybook/react-native-theming");
var import_react3 = __toESM(require("react"));
var import_react_native2 = require("react-native");
// ../../node_modules/jotai/esm/vanilla/internals.mjs
var import_meta = {};
function hasInitialValue(atom2) {
return "init" in atom2;
}
function isActuallyWritableAtom(atom2) {
return !!atom2.write;
}
function isAtomStateInitialized(atomState) {
return "v" in atomState || "e" in atomState;
}
function returnAtomValue(atomState) {
if ("e" in atomState) {
throw atomState.e;
}
if ((import_meta.env ? import_meta.env.MODE : void 0) !== "production" && !("v" in atomState)) {
throw new Error("[Bug] atom state is not initialized");
}
return atomState.v;
}
var promiseStateMap = /* @__PURE__ */ new WeakMap();
function isPendingPromise(value) {
var _a;
return isPromiseLike(value) && !!((_a = promiseStateMap.get(value)) == null ? void 0 : _a[0]);
}
function abortPromise(promise) {
const promiseState = promiseStateMap.get(promise);
if (promiseState == null ? void 0 : promiseState[0]) {
promiseState[0] = false;
promiseState[1].forEach((fn) => fn());
}
}
function registerAbortHandler(promise, abortHandler) {
let promiseState = promiseStateMap.get(promise);
if (!promiseState) {
promiseState = [true, /* @__PURE__ */ new Set()];
promiseStateMap.set(promise, promiseState);
const settle = () => {
promiseState[0] = false;
};
promise.then(settle, settle);
}
promiseState[1].add(abortHandler);
}
function isPromiseLike(p) {
return typeof (p == null ? void 0 : p.then) === "function";
}
function addPendingPromiseToDependency(atom2, promise, dependencyAtomState) {
if (!dependencyAtomState.p.has(atom2)) {
dependencyAtomState.p.add(atom2);
const cleanup = () => dependencyAtomState.p.delete(atom2);
promise.then(cleanup, cleanup);
}
}
function getMountedOrPendingDependents(atom2, atomState, mountedMap) {
var _a;
const dependents = /* @__PURE__ */ new Set();
for (const a of ((_a = mountedMap.get(atom2)) == null ? void 0 : _a.t) || []) {
dependents.add(a);
}
for (const atomWithPendingPromise of atomState.p) {
dependents.add(atomWithPendingPromise);
}
return dependents;
}
var BUILDING_BLOCK_atomRead = (_store, atom2, ...params) => atom2.read(...params);
var BUILDING_BLOCK_atomWrite = (_store, atom2, ...params) => atom2.write(...params);
var BUILDING_BLOCK_atomOnInit = (store, atom2) => {
var _a;
return (_a = atom2.INTERNAL_onInit) == null ? void 0 : _a.call(atom2, store);
};
var BUILDING_BLOCK_atomOnMount = (_store, atom2, setAtom) => {
var _a;
return (_a = atom2.onMount) == null ? void 0 : _a.call(atom2, setAtom);
};
var BUILDING_BLOCK_ensureAtomState = (store, atom2) => {
var _a;
const buildingBlocks = getInternalBuildingBlocks(store);
const atomStateMap = buildingBlocks[0];
const storeHooks = buildingBlocks[6];
const atomOnInit = buildingBlocks[9];
if ((import_meta.env ? import_meta.env.MODE : void 0) !== "production" && !atom2) {
throw new Error("Atom is undefined or null");
}
let atomState = atomStateMap.get(atom2);
if (!atomState) {
atomState = { d: /* @__PURE__ */ new Map(), p: /* @__PURE__ */ new Set(), n: 0 };
atomStateMap.set(atom2, atomState);
(_a = storeHooks.i) == null ? void 0 : _a.call(storeHooks, atom2);
atomOnInit == null ? void 0 : atomOnInit(store, atom2);
}
return atomState;
};
var BUILDING_BLOCK_flushCallbacks = (store) => {
const buildingBlocks = getInternalBuildingBlocks(store);
const mountedMap = buildingBlocks[1];
const changedAtoms = buildingBlocks[3];
const mountCallbacks = buildingBlocks[4];
const unmountCallbacks = buildingBlocks[5];
const storeHooks = buildingBlocks[6];
const recomputeInvalidatedAtoms = buildingBlocks[13];
const errors = [];
const call = (fn) => {
try {
fn();
} catch (e) {
errors.push(e);
}
};
do {
if (storeHooks.f) {
call(storeHooks.f);
}
const callbacks = /* @__PURE__ */ new Set();
const add = callbacks.add.bind(callbacks);
changedAtoms.forEach((atom2) => {
var _a;
return (_a = mountedMap.get(atom2)) == null ? void 0 : _a.l.forEach(add);
});
changedAtoms.clear();
unmountCallbacks.forEach(add);
unmountCallbacks.clear();
mountCallbacks.forEach(add);
mountCallbacks.clear();
callbacks.forEach(call);
if (changedAtoms.size) {
recomputeInvalidatedAtoms(store);
}
} while (changedAtoms.size || unmountCallbacks.size || mountCallbacks.size);
if (errors.length) {
throw new AggregateError(errors);
}
};
var BUILDING_BLOCK_recomputeInvalidatedAtoms = (store) => {
const buildingBlocks = getInternalBuildingBlocks(store);
const mountedMap = buildingBlocks[1];
const invalidatedAtoms = buildingBlocks[2];
const changedAtoms = buildingBlocks[3];
const ensureAtomState = buildingBlocks[11];
const readAtomState = buildingBlocks[14];
const mountDependencies = buildingBlocks[17];
const topSortedReversed = [];
const visiting = /* @__PURE__ */ new WeakSet();
const visited = /* @__PURE__ */ new WeakSet();
const stack = Array.from(changedAtoms);
while (stack.length) {
const a = stack[stack.length - 1];
const aState = ensureAtomState(store, a);
if (visited.has(a)) {
stack.pop();
continue;
}
if (visiting.has(a)) {
if (invalidatedAtoms.get(a) === aState.n) {
topSortedReversed.push([a, aState]);
} else if ((import_meta.env ? import_meta.env.MODE : void 0) !== "production" && invalidatedAtoms.has(a)) {
throw new Error("[Bug] invalidated atom exists");
}
visited.add(a);
stack.pop();
continue;
}
visiting.add(a);
for (const d of getMountedOrPendingDependents(a, aState, mountedMap)) {
if (!visiting.has(d)) {
stack.push(d);
}
}
}
for (let i = topSortedReversed.length - 1; i >= 0; --i) {
const [a, aState] = topSortedReversed[i];
let hasChangedDeps = false;
for (const dep of aState.d.keys()) {
if (dep !== a && changedAtoms.has(dep)) {
hasChangedDeps = true;
break;
}
}
if (hasChangedDeps) {
readAtomState(store, a);
mountDependencies(store, a);
}
invalidatedAtoms.delete(a);
}
};
var storeMutationSet = /* @__PURE__ */ new WeakSet();
var BUILDING_BLOCK_readAtomState = (store, atom2) => {
var _a, _b;
const buildingBlocks = getInternalBuildingBlocks(store);
const mountedMap = buildingBlocks[1];
const invalidatedAtoms = buildingBlocks[2];
const changedAtoms = buildingBlocks[3];
const storeHooks = buildingBlocks[6];
const atomRead = buildingBlocks[7];
const ensureAtomState = buildingBlocks[11];
const flushCallbacks = buildingBlocks[12];
const recomputeInvalidatedAtoms = buildingBlocks[13];
const readAtomState = buildingBlocks[14];
const writeAtomState = buildingBlocks[16];
const mountDependencies = buildingBlocks[17];
const setAtomStateValueOrPromise = buildingBlocks[20];
const atomState = ensureAtomState(store, atom2);
if (isAtomStateInitialized(atomState)) {
if (mountedMap.has(atom2) && invalidatedAtoms.get(atom2) !== atomState.n) {
return atomState;
}
let hasChangedDeps = false;
for (const [a, n] of atomState.d) {
if (readAtomState(store, a).n !== n) {
hasChangedDeps = true;
break;
}
}
if (!hasChangedDeps) {
return atomState;
}
}
atomState.d.clear();
let isSync = true;
function mountDependenciesIfAsync() {
if (mountedMap.has(atom2)) {
mountDependencies(store, atom2);
recomputeInvalidatedAtoms(store);
flushCallbacks(store);
}
}
function getter(a) {
var _a2;
if (a === atom2) {
const aState2 = ensureAtomState(store, a);
if (!isAtomStateInitialized(aState2)) {
if (hasInitialValue(a)) {
setAtomStateValueOrPromise(store, a, a.init);
} else {
throw new Error("no atom init");
}
}
return returnAtomValue(aState2);
}
const aState = readAtomState(store, a);
try {
return returnAtomValue(aState);
} finally {
atomState.d.set(a, aState.n);
if (isPendingPromise(atomState.v)) {
addPendingPromiseToDependency(atom2, atomState.v, aState);
}
if (mountedMap.has(atom2)) {
(_a2 = mountedMap.get(a)) == null ? void 0 : _a2.t.add(atom2);
}
if (!isSync) {
mountDependenciesIfAsync();
}
}
}
let controller;
let setSelf;
const options = {
get signal() {
if (!controller) {
controller = new AbortController();
}
return controller.signal;
},
get setSelf() {
if ((import_meta.env ? import_meta.env.MODE : void 0) !== "production") {
console.warn(
"[DEPRECATED] setSelf is deprecated and will be removed in v3."
);
}
if ((import_meta.env ? import_meta.env.MODE : void 0) !== "production" && !isActuallyWritableAtom(atom2)) {
console.warn("setSelf function cannot be used with read-only atom");
}
if (!setSelf && isActuallyWritableAtom(atom2)) {
setSelf = (...args) => {
if ((import_meta.env ? import_meta.env.MODE : void 0) !== "production" && isSync) {
console.warn("setSelf function cannot be called in sync");
}
if (!isSync) {
try {
return writeAtomState(store, atom2, ...args);
} finally {
recomputeInvalidatedAtoms(store);
flushCallbacks(store);
}
}
};
}
return setSelf;
}
};
const prevEpochNumber = atomState.n;
try {
if ((import_meta.env ? import_meta.env.MODE : void 0) !== "production") {
storeMutationSet.delete(store);
}
const valueOrPromise = atomRead(store, atom2, getter, options);
if ((import_meta.env ? import_meta.env.MODE : void 0) !== "production" && storeMutationSet.has(store)) {
console.warn(
"Detected store mutation during atom read. This is not supported."
);
}
setAtomStateValueOrPromise(store, atom2, valueOrPromise);
if (isPromiseLike(valueOrPromise)) {
registerAbortHandler(valueOrPromise, () => controller == null ? void 0 : controller.abort());
valueOrPromise.then(mountDependenciesIfAsync, mountDependenciesIfAsync);
}
(_a = storeHooks.r) == null ? void 0 : _a.call(storeHooks, atom2);
return atomState;
} catch (error) {
delete atomState.v;
atomState.e = error;
++atomState.n;
return atomState;
} finally {
isSync = false;
if (prevEpochNumber !== atomState.n && invalidatedAtoms.get(atom2) === prevEpochNumber) {
invalidatedAtoms.set(atom2, atomState.n);
changedAtoms.add(atom2);
(_b = storeHooks.c) == null ? void 0 : _b.call(storeHooks, atom2);
}
}
};
var BUILDING_BLOCK_invalidateDependents = (store, atom2) => {
const buildingBlocks = getInternalBuildingBlocks(store);
const mountedMap = buildingBlocks[1];
const invalidatedAtoms = buildingBlocks[2];
const ensureAtomState = buildingBlocks[11];
const stack = [atom2];
while (stack.length) {
const a = stack.pop();
const aState = ensureAtomState(store, a);
for (const d of getMountedOrPendingDependents(a, aState, mountedMap)) {
const dState = ensureAtomState(store, d);
invalidatedAtoms.set(d, dState.n);
stack.push(d);
}
}
};
var BUILDING_BLOCK_writeAtomState = (store, atom2, ...args) => {
const buildingBlocks = getInternalBuildingBlocks(store);
const changedAtoms = buildingBlocks[3];
const storeHooks = buildingBlocks[6];
const atomWrite = buildingBlocks[8];
const ensureAtomState = buildingBlocks[11];
const flushCallbacks = buildingBlocks[12];
const recomputeInvalidatedAtoms = buildingBlocks[13];
const readAtomState = buildingBlocks[14];
const invalidateDependents = buildingBlocks[15];
const writeAtomState = buildingBlocks[16];
const mountDependencies = buildingBlocks[17];
const setAtomStateValueOrPromise = buildingBlocks[20];
let isSync = true;
const getter = (a) => returnAtomValue(readAtomState(store, a));
const setter = (a, ...args2) => {
var _a;
const aState = ensureAtomState(store, a);
try {
if (a === atom2) {
if (!hasInitialValue(a)) {
throw new Error("atom not writable");
}
if ((import_meta.env ? import_meta.env.MODE : void 0) !== "production") {
storeMutationSet.add(store);
}
const prevEpochNumber = aState.n;
const v = args2[0];
setAtomStateValueOrPromise(store, a, v);
mountDependencies(store, a);
if (prevEpochNumber !== aState.n) {
changedAtoms.add(a);
invalidateDependents(store, a);
(_a = storeHooks.c) == null ? void 0 : _a.call(storeHooks, a);
}
return void 0;
} else {
return writeAtomState(store, a, ...args2);
}
} finally {
if (!isSync) {
recomputeInvalidatedAtoms(store);
flushCallbacks(store);
}
}
};
try {
return atomWrite(store, atom2, getter, setter, ...args);
} finally {
isSync = false;
}
};
var BUILDING_BLOCK_mountDependencies = (store, atom2) => {
var _a;
const buildingBlocks = getInternalBuildingBlocks(store);
const mountedMap = buildingBlocks[1];
const changedAtoms = buildingBlocks[3];
const storeHooks = buildingBlocks[6];
const ensureAtomState = buildingBlocks[11];
const invalidateDependents = buildingBlocks[15];
const mountAtom = buildingBlocks[18];
const unmountAtom = buildingBlocks[19];
const atomState = ensureAtomState(store, atom2);
const mounted = mountedMap.get(atom2);
if (mounted && !isPendingPromise(atomState.v)) {
for (const [a, n] of atomState.d) {
if (!mounted.d.has(a)) {
const aState = ensureAtomState(store, a);
const aMounted = mountAtom(store, a);
aMounted.t.add(atom2);
mounted.d.add(a);
if (n !== aState.n) {
changedAtoms.add(a);
invalidateDependents(store, a);
(_a = storeHooks.c) == null ? void 0 : _a.call(storeHooks, a);
}
}
}
for (const a of mounted.d) {
if (!atomState.d.has(a)) {
mounted.d.delete(a);
const aMounted = unmountAtom(store, a);
aMounted == null ? void 0 : aMounted.t.delete(atom2);
}
}
}
};
var BUILDING_BLOCK_mountAtom = (store, atom2) => {
var _a;
const buildingBlocks = getInternalBuildingBlocks(store);
const mountedMap = buildingBlocks[1];
const mountCallbacks = buildingBlocks[4];
const storeHooks = buildingBlocks[6];
const atomOnMount = buildingBlocks[10];
const ensureAtomState = buildingBlocks[11];
const flushCallbacks = buildingBlocks[12];
const recomputeInvalidatedAtoms = buildingBlocks[13];
const readAtomState = buildingBlocks[14];
const writeAtomState = buildingBlocks[16];
const mountAtom = buildingBlocks[18];
const atomState = ensureAtomState(store, atom2);
let mounted = mountedMap.get(atom2);
if (!mounted) {
readAtomState(store, atom2);
for (const a of atomState.d.keys()) {
const aMounted = mountAtom(store, a);
aMounted.t.add(atom2);
}
mounted = {
l: /* @__PURE__ */ new Set(),
d: new Set(atomState.d.keys()),
t: /* @__PURE__ */ new Set()
};
mountedMap.set(atom2, mounted);
if (isActuallyWritableAtom(atom2)) {
const processOnMount = () => {
let isSync = true;
const setAtom = (...args) => {
try {
return writeAtomState(store, atom2, ...args);
} finally {
if (!isSync) {
recomputeInvalidatedAtoms(store);
flushCallbacks(store);
}
}
};
try {
const onUnmount = atomOnMount(store, atom2, setAtom);
if (onUnmount) {
mounted.u = () => {
isSync = true;
try {
onUnmount();
} finally {
isSync = false;
}
};
}
} finally {
isSync = false;
}
};
mountCallbacks.add(processOnMount);
}
(_a = storeHooks.m) == null ? void 0 : _a.call(storeHooks, atom2);
}
return mounted;
};
var BUILDING_BLOCK_unmountAtom = (store, atom2) => {
var _a, _b;
const buildingBlocks = getInternalBuildingBlocks(store);
const mountedMap = buildingBlocks[1];
const unmountCallbacks = buildingBlocks[5];
const storeHooks = buildingBlocks[6];
const ensureAtomState = buildingBlocks[11];
const unmountAtom = buildingBlocks[19];
const atomState = ensureAtomState(store, atom2);
let mounted = mountedMap.get(atom2);
if (!mounted || mounted.l.size) {
return mounted;
}
let isDependent = false;
for (const a of mounted.t) {
if ((_a = mountedMap.get(a)) == null ? void 0 : _a.d.has(atom2)) {
isDependent = true;
break;
}
}
if (!isDependent) {
if (mounted.u) {
unmountCallbacks.add(mounted.u);
}
mounted = void 0;
mountedMap.delete(atom2);
for (const a of atomState.d.keys()) {
const aMounted = unmountAtom(store, a);
aMounted == null ? void 0 : aMounted.t.delete(atom2);
}
(_b = storeHooks.u) == null ? void 0 : _b.call(storeHooks, atom2);
return void 0;
}
return mounted;
};
var BUILDING_BLOCK_setAtomStateValueOrPromise = (store, atom2, valueOrPromise) => {
const ensureAtomState = getInternalBuildingBlocks(store)[11];
const atomState = ensureAtomState(store, atom2);
const hasPrevValue = "v" in atomState;
const prevValue = atomState.v;
if (isPromiseLike(valueOrPromise)) {
for (const a of atomState.d.keys()) {
addPendingPromiseToDependency(
atom2,
valueOrPromise,
ensureAtomState(store, a)
);
}
}
atomState.v = valueOrPromise;
delete atomState.e;
if (!hasPrevValue || !Object.is(prevValue, atomState.v)) {
++atomState.n;
if (isPromiseLike(prevValue)) {
abortPromise(prevValue);
}
}
};
var BUILDING_BLOCK_storeGet = (store, atom2) => {
const readAtomState = getInternalBuildingBlocks(store)[14];
return returnAtomValue(readAtomState(store, atom2));
};
var BUILDING_BLOCK_storeSet = (store, atom2, ...args) => {
const buildingBlocks = getInternalBuildingBlocks(store);
const flushCallbacks = buildingBlocks[12];
const recomputeInvalidatedAtoms = buildingBlocks[13];
const writeAtomState = buildingBlocks[16];
try {
return writeAtomState(store, atom2, ...args);
} finally {
recomputeInvalidatedAtoms(store);
flushCallbacks(store);
}
};
var BUILDING_BLOCK_storeSub = (store, atom2, listener) => {
const buildingBlocks = getInternalBuildingBlocks(store);
const flushCallbacks = buildingBlocks[12];
const mountAtom = buildingBlocks[18];
const unmountAtom = buildingBlocks[19];
const mounted = mountAtom(store, atom2);
const listeners = mounted.l;
listeners.add(listener);
flushCallbacks(store);
return () => {
listeners.delete(listener);
unmountAtom(store, atom2);
flushCallbacks(store);
};
};
var buildingBlockMap = /* @__PURE__ */ new WeakMap();
var getInternalBuildingBlocks = (store) => {
const buildingBlocks = buildingBlockMap.get(store);
if ((import_meta.env ? import_meta.env.MODE : void 0) !== "production" && !buildingBlocks) {
throw new Error(
"Store must be created by buildStore to read its building blocks"
);
}
return buildingBlocks;
};
function buildStore(...buildArgs) {
const store = {
get(atom2) {
const storeGet = getInternalBuildingBlocks(store)[21];
return storeGet(store, atom2);
},
set(atom2, ...args) {
const storeSet = getInternalBuildingBlocks(store)[22];
return storeSet(store, atom2, ...args);
},
sub(atom2, listener) {
const storeSub = getInternalBuildingBlocks(store)[23];
return storeSub(store, atom2, listener);
}
};
const buildingBlocks = [
// store state
/* @__PURE__ */ new WeakMap(),
// atomStateMap
/* @__PURE__ */ new WeakMap(),
// mountedMap
/* @__PURE__ */ new WeakMap(),
// invalidatedAtoms
/* @__PURE__ */ new Set(),
// changedAtoms
/* @__PURE__ */ new Set(),
// mountCallbacks
/* @__PURE__ */ new Set(),
// unmountCallbacks
{},
// storeHooks
// atom interceptors
BUILDING_BLOCK_atomRead,
BUILDING_BLOCK_atomWrite,
BUILDING_BLOCK_atomOnInit,
BUILDING_BLOCK_atomOnMount,
// building-block functions
BUILDING_BLOCK_ensureAtomState,
BUILDING_BLOCK_flushCallbacks,
BUILDING_BLOCK_recomputeInvalidatedAtoms,
BUILDING_BLOCK_readAtomState,
BUILDING_BLOCK_invalidateDependents,
BUILDING_BLOCK_writeAtomState,
BUILDING_BLOCK_mountDependencies,
BUILDING_BLOCK_mountAtom,
BUILDING_BLOCK_unmountAtom,
BUILDING_BLOCK_setAtomStateValueOrPromise,
BUILDING_BLOCK_storeGet,
BUILDING_BLOCK_storeSet,
BUILDING_BLOCK_storeSub,
void 0
].map((fn, i) => buildArgs[i] || fn);
buildingBlockMap.set(store, Object.freeze(buildingBlocks));
return store;
}
// ../../node_modules/jotai/esm/vanilla.mjs
var import_meta2 = {};
var keyCount = 0;
function atom(read, write) {
const key = `atom${++keyCount}`;
const config = {
toString() {
return (import_meta2.env ? import_meta2.env.MODE : void 0) !== "production" && this.debugLabel ? key + ":" + this.debugLabel : key;
}
};
if (typeof read === "function") {
config.read = read;
} else {
config.init = read;
config.read = defaultRead;
config.write = defaultWrite;
}
if (write) {
config.write = write;
}
return config;
}
function defaultRead(get) {
return get(this);
}
function defaultWrite(get, set, arg) {
return set(
this,
typeof arg === "function" ? arg(get(this)) : arg
);
}
var overriddenCreateStore;
function createStore() {
if (overriddenCreateStore) {
return overriddenCreateStore();
}
return buildStore();
}
var defaultStore;
function getDefaultStore() {
if (!defaultStore) {
defaultStore = createStore();
if ((import_meta2.env ? import_meta2.env.MODE : void 0) !== "production") {
globalThis.__JOTAI_DEFAULT_STORE__ || (globalThis.__JOTAI_DEFAULT_STORE__ = defaultStore);
if (globalThis.__JOTAI_DEFAULT_STORE__ !== defaultStore) {
console.warn(
"Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044"
);
}
}
}
return defaultStore;
}
// ../../node_modules/jotai/esm/react.mjs
var import_react = __toESM(require("react"), 1);
var import_meta3 = {};
var StoreContext = (0, import_react.createContext)(
void 0
);
function useStore(options) {
const store = (0, import_react.useContext)(StoreContext);
return (options == null ? void 0 : options.store) || store || getDefaultStore();
}
var isPromiseLike2 = (x) => typeof (x == null ? void 0 : x.then) === "function";
var attachPromiseStatus = (promise) => {
if (!promise.status) {
promise.status = "pending";
promise.then(
(v) => {
promise.status = "fulfilled";
promise.value = v;
},
(e) => {
promise.status = "rejected";
promise.reason = e;
}
);
}
};
var use = import_react.default.use || // A shim for older React versions
((promise) => {
if (promise.status === "pending") {
throw promise;
} else if (promise.status === "fulfilled") {
return promise.value;
} else if (promise.status === "rejected") {
throw promise.reason;
} else {
attachPromiseStatus(promise);
throw promise;
}
});
var continuablePromiseMap = /* @__PURE__ */ new WeakMap();
var createContinuablePromise = (promise, getValue) => {
let continuablePromise = continuablePromiseMap.get(promise);
if (!continuablePromise) {
continuablePromise = new Promise((resolve, reject) => {
let curr = promise;
const onFulfilled = (me) => (v) => {
if (curr === me) {
resolve(v);
}
};
const onRejected = (me) => (e) => {
if (curr === me) {
reject(e);
}
};
const onAbort = () => {
try {
const nextValue = getValue();
if (isPromiseLike2(nextValue)) {
continuablePromiseMap.set(nextValue, continuablePromise);
curr = nextValue;
nextValue.then(onFulfilled(nextValue), onRejected(nextValue));
registerAbortHandler(nextValue, onAbort);
} else {
resolve(nextValue);
}
} catch (e) {
reject(e);
}
};
promise.then(onFulfilled(promise), onRejected(promise));
registerAbortHandler(promise, onAbort);
});
continuablePromiseMap.set(promise, continuablePromise);
}
return continuablePromise;
};
function useAtomValue(atom2, options) {
const { delay, unstable_promiseStatus: promiseStatus = !import_react.default.use } = options || {};
const store = useStore(options);
const [[valueFromReducer, storeFromReducer, atomFromReducer], rerender] = (0, import_react.useReducer)(
(prev) => {
const nextValue = store.get(atom2);
if (Object.is(prev[0], nextValue) && prev[1] === store && prev[2] === atom2) {
return prev;
}
return [nextValue, store, atom2];
},
void 0,
() => [store.get(atom2), store, atom2]
);
let value = valueFromReducer;
if (storeFromReducer !== store || atomFromReducer !== atom2) {
rerender();
value = store.get(atom2);
}
(0, import_react.useEffect)(() => {
const unsub = store.sub(atom2, () => {
if (promiseStatus) {
try {
const value2 = store.get(atom2);
if (isPromiseLike2(value2)) {
attachPromiseStatus(
createContinuablePromise(value2, () => store.get(atom2))
);
}
} catch (e) {
}
}
if (typeof delay === "number") {
setTimeout(rerender, delay);
return;
}
rerender();
});
rerender();
return unsub;
}, [store, atom2, delay, promiseStatus]);
(0, import_react.useDebugValue)(value);
if (isPromiseLike2(value)) {
const promise = createContinuablePromise(value, () => store.get(atom2));
if (promiseStatus) {
attachPromiseStatus(promise);
}
return use(promise);
}
return value;
}
function useSetAtom(atom2, options) {
const store = useStore(options);
const setAtom = (0, import_react.useCallback)(
(...args) => {
if ((import_meta3.env ? import_meta3.env.MODE : void 0) !== "production" && !("write" in atom2)) {
throw new Error("not writable atom");
}
return store.set(atom2, ...args);
},
[store, atom2]
);
return setAtom;
}
// src/hooks.tsx
var storyContextAtom = atom(null);
function useSetStoryContext() {
return useSetAtom(storyContextAtom);
}
function useStoryContext() {
return useAtomValue(storyContextAtom);
}
// src/components/StoryView/ErrorBoundary.tsx
var import_react2 = __toESM(require("react"));
var import_react_native = require("react-native");
var import_jsx_runtime = require("react/jsx-runtime");
var ErrorBoundary = class extends import_react2.default.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(_error) {
return { hasError: true };
}
componentDidCatch(error, info) {
this.props.onError(error, info.componentStack);
}
render() {
if (this.state.hasError) {
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
import_react_native.View,
{
style: {
margin: 16,
padding: 16,
borderColor: "red",
borderWidth: 2,
alignItems: "center",
justifyContent: "center",
borderRadius: 4
},
children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_native.Text, { style: { fontWeight: "bold" }, children: "Something went wrong rendering your story" })
}
);
}
return this.props.children;
}
};
// src/components/StoryView/StoryView.tsx
var import_jsx_runtime2 = require("react/jsx-runtime");
function dismissOnStartResponder() {
import_react_native2.Keyboard.dismiss();
return false;
}
var Text2 = import_react_native_theming.styled.Text(({ theme: theme3 }) => ({
color: theme3?.color?.defaultText
}));
var errorContainerStyle = {
flex: 1,
padding: 16,
alignItems: "center",
justifyContent: "center"
};
var layoutStyles = {
padded: { padding: 8 },
centered: { alignItems: "center", justifyContent: "center" },
fullscreen: {}
};
var StoryView = ({ useWrapper = true }) => {
const context = useStoryContext();
const id = context?.id;
const theme3 = (0, import_react_native_theming.useTheme)();
const containerStyle = (0, import_react3.useMemo)(() => {
const layout = context?.parameters?.layout;
const layoutStyle = layout ? layoutStyles[layout] : {};
return {
flex: 1,
backgroundColor: theme3.background?.content,
overflow: "hidden",
...layoutStyle
};
}, [theme3.background?.content, context?.parameters?.layout]);
const onError = (0, import_react3.useCallback)(() => {
console.log(`Error rendering story for ${context?.title} ${context?.name}`);
}, [context?.title, context?.name]);
if (context && context.unboundStoryFn) {
const { unboundStoryFn: StoryComponent } = context;
if (useWrapper) {
return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
import_react_native2.View,
{
style: containerStyle,
testID: id,
accessibilityLabel: id,
importantForAccessibility: "no",
onStartShouldSetResponder: dismissOnStartResponder,
children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(ErrorBoundary, { onError, children: StoryComponent && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(StoryComponent, { ...context }) })
},
id
);
}
return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(ErrorBoundary, { onError, children: StoryComponent && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(StoryComponent, { ...context }) });
}
return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_react_native2.View, { style: errorContainerStyle, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Text2, { children: "Please select a story to preview." }) });
};
var StoryView_default = import_react3.default.memo(StoryView);
// src/constants.ts
var RN_STORYBOOK_STORAGE_KEY = "lastOpenedStory";
var RN_STORYBOOK_EVENTS = {
RN_GET_INDEX: "RN_GET_INDEX",
RN_GET_INDEX_RESPONSE: "RN_GET_INDEX_RESPONSE"
};
var STORYBOOK_STORY_ID_PARAM = "STORYBOOK_STORY_ID";
// src/View.tsx
var import_jsx_runtime3 = require("react/jsx-runtime");
var View3 = class {
_storyIndex;
_setStory = () => {
};
_forceRerender = () => {
};
_ready = false;
_preview;
_asyncStorageStoryId;
_webUrl;
_storage;
_channel;
_idToPrepared = {};
constructor(preview, channel) {
this._preview = preview;
this._channel = channel;
}
_storyIdExists = (storyId) => {
return Object.keys(this._storyIndex.entries).includes(storyId);
};
_getInitialStory = async ({
initialSelection,
shouldPersistSelection = true
} = {}) => {
if (initialSelection) {
if (typeof initialSelection === "string") {
return { storySpecifier: initialSelection, viewMode: "story" };
} else {
return {
storySpecifier: (0, import_csf.toId)(initialSelection.kind, initialSelection.name),
viewMode: "story"
};
}
}
if (shouldPersistSelection) {
try {
let value = this._asyncStorageStoryId;
if (!value && this._storage != null) {
value = await this._storage.getItem(RN_STORYBOOK_STORAGE_KEY);
this._asyncStorageStoryId = value;
}
const exists = value && this._storyIdExists(value);
if (!exists) console.log("Storybook: could not find persisted story");
return { storySpecifier: exists ? value : "*", viewMode: "story" };
} catch (e) {
console.warn("storybook-log: error reading from async storage", e);
}
}
return { storySpecifier: "*", viewMode: "story" };
};
_getHost = (params = {}) => {
if (params.host) {
return params.host;
}
if (globalThis.STORYBOOK_WEBSOCKET?.host) {
return globalThis.STORYBOOK_WEBSOCKET.host;
}
return import_react_native3.Platform.OS === "android" ? "10.0.2.2" : "localhost";
};
__getPort = (params = {}) => {
if (params.port) {
return params.port;
}
if (globalThis.STORYBOOK_WEBSOCKET?.port) {
return globalThis.STORYBOOK_WEBSOCKET.port;
}
return 7007;
};
_getServerChannel = (params = {}) => {
const host = this._getHost(params);
const port = `:${this.__getPort(params)}`;
const query = params.query || "";
const websocketType = params.secured ? "wss" : "ws";
const url = `${websocketType}://${host}${port}/${query}`;
const channel = new import_channels.Channel({
transport: new import_channels.WebsocketTransport({
url,
onError: (e) => {
console.log(`WebsocketTransport error ${JSON.stringify(e)}`);
}
}),
async: true
});
return channel;
};
createPreparedStoryMapping = async () => {
await this._preview.ready().then(
() => Promise.all(
Object.keys(this._storyIndex.entries).map(async (storyId) => {
this._idToPrepared[storyId] = await this._preview.loadStory({ storyId });
})
)
);
};
getStorybookUI = (params = {}) => {
const {
shouldPersistSelection = true,
onDeviceUI = true,
enableWebsockets = false,
storage,
CustomUIComponent,
hasStoryWrapper: storyViewWrapper = true
} = params;
const getFullUI = (enabled) => {
if (enabled) {
try {
const { FullUI: FullUI2 } = require("@storybook/react-native-ui");
return FullUI2;
} catch (error) {
console.warn("storybook-log: error loading UI", error);
}
}
const PlaceholderUI = ({ children }) => children;
return PlaceholderUI;
};
const FullUI = getFullUI(onDeviceUI && !CustomUIComponent);
this._storage = storage;
const initialStory = this._getInitialStory(params);
if (enableWebsockets) {
const channel = this._getServerChannel(params);
import_manager_api.addons.setChannel(channel);
import_preview_api.addons.setChannel(channel);
this._channel = channel;
this._preview.channel = channel;
this._preview.setupListeners();
channel.emit(import_core_events.CHANNEL_CREATED);
this._preview.ready().then(() => this._preview.onStoryIndexChanged());
}
this._channel.on(RN_STORYBOOK_EVENTS.RN_GET_INDEX, () => {
this._channel.emit(RN_STORYBOOK_EVENTS.RN_GET_INDEX_RESPONSE, { index: this._storyIndex });
});
import_manager_api.addons.loadAddons({
store: () => ({
fromId: (id) => {
if (!this._ready) {
throw new Error("Storybook is not ready yet");
}
return this._preview.getStoryContext(this._idToPrepared[id]);
},
getSelection: () => {
return this._preview.currentSelection;
},
_channel: this._channel
})
});
const self = this;
return () => {
const setContext = useSetStoryContext();
const story = useStoryContext();
const colorScheme = (0, import_react_native3.useColorScheme)();
const [update, forceUpdate] = (0, import_react4.useReducer)((x) => x + 1, 0);
const [ready, setReady] = (0, import_react4.useState)(false);
const appliedTheme = (0, import_react4.useMemo)(
() => (0, import_deepmerge.default)(colorScheme === "dark" ? import_react_native_theming2.darkTheme : import_react_native_theming2.theme, params.theme ?? {}),
[colorScheme]
);
(0, import_react4.useEffect)(() => {
const listener = import_react_native3.Linking.addEventListener("url", ({ url }) => {
if (typeof url === "string") {
const urlObj = new URL(url);
const storyId = urlObj.searchParams.get(STORYBOOK_STORY_ID_PARAM);
const hasStoryId = storyId && typeof storyId === "string";
const storyExists = hasStoryId && self._storyIdExists(storyId);
if (storyExists && self._ready) {
console.log(`STORYBOOK: Linking event received, navigating to story: ${storyId}`);
self._channel.emit(import_core_events.SET_CURRENT_STORY, { storyId });
}
if (hasStoryId && !storyExists) {
console.log(
`STORYBOOK: Linking event received, but story does not exist: ${storyId}`
);
}
}
});
return () => {
listener.remove();
};
}, []);
(0, import_react4.useEffect)(() => {
self.createPreparedStoryMapping().then(() => {
self._ready = true;
setReady(true);
return import_react_native3.Linking.getInitialURL().then((url) => {
if (url && typeof url === "string") {
const urlObj = new URL(url);
const storyId = urlObj.searchParams.get(STORYBOOK_STORY_ID_PARAM);
const hasStoryId = storyId && typeof storyId === "string";
const storyExists = hasStoryId && self._storyIdExists(storyId);
if (hasStoryId && !storyExists) {
console.log(
`STORYBOOK: Initial Linking event received, but story does not exist: ${storyId}`
);
}
if (storyExists) {
return storyId;
} else {
return null;
}
}
}).then((initialStoryIdFromUrl) => {
return initialStory.then((st) => {
self._preview.selectionStore.selectionSpecifier = st;
if (initialStoryIdFromUrl) {
console.log(
`STORYBOOK: Setting initial story from Linking event, storyId: ${initialStoryIdFromUrl}`
);
self._preview.selectionStore.selectionSpecifier = {
storySpecifier: initialStoryIdFromUrl,
viewMode: "story"
};
}
self._preview.selectSpecifiedStory();
});
});
}).catch((e) => console.error(e));
self._setStory = (newStory) => {
setContext(newStory);
if (shouldPersistSelection && !storage) {
console.warn(import_dedent.default`Please set storage in getStorybookUI like this:
const StorybookUIRoot = view.getStorybookUI({
storage: {
getItem: AsyncStorage.getItem,
setItem: AsyncStorage.setItem,
},
});
`);
}
if (shouldPersistSelection && !!self._storage) {
self._storage.setItem(RN_STORYBOOK_STORAGE_KEY, newStory.id).catch((e) => {
console.warn("storybook-log: error writing to async storage", e);
});
}
};
self._forceRerender = () => forceUpdate();
}, []);
const storyHash = (0, import_react4.useMemo)(() => {
if (!ready) {
return {};
}
return (0, import_react_native_ui_common.transformStoryIndexToStoriesHash)(self._storyIndex, {
docsOptions: { docsMode: false, defaultName: "" },
filters: {},
allStatuses: {},
provider: {
handleAPI: () => ({}),
getConfig: () => ({})
}
});
}, [ready, update]);
if (!ready) {
return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
import_react_native3.View,
{
style: {
...import_react_native3.StyleSheet.absoluteFillObject,
alignItems: "center",
justifyContent: "center"
},
children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_react_native3.ActivityIndicator, { animating: true, size: "large" })
}
);
}
if (onDeviceUI) {
if (CustomUIComponent) {
return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
CustomUIComponent,
{
story,
storyHash,
setStory: (newStoryId) => self._channel.emit(import_core_events.SET_CURRENT_STORY, { storyId: newStoryId }),
storage,
theme: appliedTheme,
children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(StoryView_default, { useWrapper: storyViewWrapper })
}
);
}
return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
FullUI,
{
storage,
theme: appliedTheme,
storyHash,
story,
setStory: (newStoryId) => self._channel.emit(import_core_events.SET_CURRENT_STORY, { storyId: newStoryId }),
children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(StoryView_default, { useWrapper: storyViewWrapper })
}
);
} else {
return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(StoryView_default, { useWrapper: storyViewWrapper });
}
};
};
};
// src/Start.tsx
var import_jsx_runtime4 = require("react/jsx-runtime");
globalThis.FEATURES = {
measure: false,
outline: false,
interactions: false,
viewport: false,
highlight: false,
backgrounds: false
};
if (import_react_native4.Platform.OS === "web" && typeof globalThis.setImmediate === "undefined") {
require("setimmediate");
}
function prepareStories({
storyEntries,
options,
storySort
}) {
let index = {
v: 5,
entries: {}
};
let importMap = {};
const makeTitle = (fileName, specifier, userTitle) => {
const title = (0, import_preview_api2.userOrAutoTitleFromSpecifier)(fileName, specifier, userTitle);
if (title) {
return title.replace("./", "");
} else {
console.log({
fileName,
userTitle,
storyEntries: storyEntries.map((entry) => {
return { ...entry, importPathMatcher: entry.importPathMatcher.source };
}),
title: title ?? ""
});
throw new Error("Could not generate title");
}
};
storyEntries.forEach((specifier) => {
const { req, directory: root } = specifier;
req.keys().forEach((filename) => {
try {
const fileExports = req(filename);
if (!fileExports.default) return;
const meta = fileExports.default;
Object.keys(fileExports).forEach((key) => {
if (key === "default") return;
if (!(0, import_csf2.isExportStory)(key, fileExports.default)) return;
const exportValue = fileExports[key];
if (!exportValue) return;
const title = makeTitle(filename, specifier, meta.title);
if (title) {
const nameFromExport = (0, import_csf2.storyNameFromExport)(key);
const id = (0, import_csf2.toId)(title, nameFromExport);
let name = nameFromExport;
if (typeof exportValue === "function") {
name = exportValue?.storyName || nameFromExport;
} else {
name = exportValue?.name || exportValue?.storyName || nameFromExport;
}
index.entries[id] = {
type: "story",
id,
name,
title,
importPath: `${root}/${filename.substring(2)}`,
// FIXME: use normalize function here
tags: ["story"],
subtype: "story"
};
const importedStories = req(filename);
const stories = Object.entries(importedStories).reduce(
(carry, [storyKey, story]) => {
if (!(0, import_csf2.isExportStory)(storyKey, fileExports.default)) return carry;
if (story.play && !options?.playFn) {
carry[storyKey] = { ...story, play: void 0 };
} else {
carry[storyKey] = story;
}
return carry;
},
{}
);
importMap[`${root}/${filename.substring(2)}`] = stories;
} else {
console.log(`Unexpected error while loading ${filename}: could not find title`);
}
});
} catch (error) {
const errorString = error.message && error.stack ? `${error.message}
${error.stack}` : error.toString();
console.error(`Unexpected error while loading ${filename}: ${errorString}`);
}
});
});
const sortableStories = Object.values(index.entries);
(0, import_preview_api2.sortStoriesV7)(
sortableStories,
storySort,
Object.values(index.entries).map((entry) => entry.importPath)
);
const sorted = sortableStories.reduce(
(acc, item) => {
acc[item.id] = item;
return acc;
},
{}
);
return { index: { v: 5, entries: sorted }, importMap };
}
var getProjectAnnotations = (view, annotations) => async () => (0, import_preview_api2.composeConfigs)([
{
renderToCanvas: (context) => {
view._setStory(context.storyContext);
},
render: (args, context) => {
const { id, component: Component } = context;
if (!Component) {
throw new Error(
`Unable to render story ${id} as the component annotation is missing from the default export`
);
}
return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Component, { ...args });
}
},
...annotations
]);
function start({
annotations,
storyEntries,
options
}) {
const composedAnnotations = (0, import_preview_api2.composeConfigs)(annotations);
const { index, importMap } = prepareStories({
storyEntries,
op