@storybook/react-native
Version:
A better way to develop React Native Components for your app
1,371 lines (1,368 loc) • 60 kB
JavaScript
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const require_chunk = require("./chunk-Ble4zEEl.js");
let _storybook_react_native_theming = require("@storybook/react-native-theming");
let react_native = require("react-native");
let storybook_internal_preview_api = require("storybook/internal/preview-api");
let storybook_manager_api = require("storybook/manager-api");
let storybook_internal_channels = require("storybook/internal/channels");
let _storybook_react_native_ui_common = require("@storybook/react-native-ui-common");
let dedent = require("dedent");
dedent = require_chunk.__toESM(dedent);
let deepmerge = require("deepmerge");
deepmerge = require_chunk.__toESM(deepmerge);
let react = require("react");
let react$1 = require_chunk.__toESM(react, 1);
react = require_chunk.__toESM(react);
let react_native_safe_area_context = require("react-native-safe-area-context");
let storybook_internal_core_events = require("storybook/internal/core-events");
let storybook_internal_csf = require("storybook/internal/csf");
let react_jsx_runtime = require("react/jsx-runtime");
//#region src/polyfill.ts
if (react_native.Platform.OS !== "web") try {
new URLSearchParams({ test: "1" }).get("test");
} catch {
const { setupURLPolyfill } = require("react-native-url-polyfill");
setupURLPolyfill();
}
if (react_native.Platform.OS === "web" && typeof globalThis.setImmediate === "undefined") require("setimmediate");
//#endregion
//#region src/patchChannelForRN.ts
/**
* React Native still pools synthetic events (unlike React DOM 17+).
* Storybook's serializeArg only recognises web SyntheticBaseEvent, so RN
* events pass through raw. When anything reads their properties after the
* current call-stack (render, transport stringify), the event has already
* been returned to the pool and every getter throws the "reused for
* performance reasons" warning.
*
* Instead of calling persist() (which keeps the event alive and retains
* references to native views), we snapshot the event into a plain object.
* This is safe for later access, serialization, and deep-equality checks.
*/
function snapshotValue(value, depth = 0) {
if (depth > 3) return "[...]";
if (value === null || value === void 0) return value;
if (typeof value === "function") return void 0;
if (typeof value !== "object") return value;
if (Array.isArray(value)) return value.map((item) => snapshotValue(item, depth + 1));
const result = {};
for (const key of Object.keys(value)) try {
result[key] = snapshotValue(value[key], depth + 1);
} catch {
result[key] = "[Error]";
}
return result;
}
function isSyntheticEvent(value) {
return value !== null && typeof value === "object" && typeof value.persist === "function" && "nativeEvent" in value;
}
function sanitizeActionArgs(value) {
if (isSyntheticEvent(value)) return snapshotValue(value);
if (Array.isArray(value)) return value.map(sanitizeActionArgs);
return value;
}
/**
* Patch a Channel so that action-event payloads have their RN synthetic
* events replaced with plain-object snapshots synchronously, before React
* recycles them back into the event pool.
*/
function patchChannelForRN(channel) {
/**
* Limit WebSocket serialization depth to avoid circular reference errors
* when action args contain React fiber nodes or other deep object graphs.
* The default maxDepth of 15 is too deep and causes blocking + crashes.
*/
globalThis.CHANNEL_OPTIONS = { maxDepth: 5 };
const originalEmit = channel.emit.bind(channel);
channel.emit = (eventName, ...args) => {
if (eventName === "storybook/actions/action-event") {
const actionDisplay = args[0];
if (actionDisplay?.data?.args != null) actionDisplay.data.args = sanitizeActionArgs(actionDisplay.data.args);
}
return originalEmit(eventName, ...args);
};
}
//#endregion
//#region ../../node_modules/jotai/esm/vanilla/internals.mjs
function hasInitialValue(atom) {
return "init" in atom;
}
function isActuallyWritableAtom(atom) {
return typeof atom.write === "function";
}
function hasOnMount(atom) {
return !!atom.onMount;
}
function isAtomStateInitialized(atomState) {
return "v" in atomState || "e" in atomState;
}
function returnAtomValue(atomState) {
if ("e" in atomState) throw atomState.e;
if (({}.env ? {}.env.MODE : void 0) !== "production" && !("v" in atomState)) throw new Error("[Bug] atom state is not initialized");
return atomState.v;
}
function isPromiseLike$1(p) {
return typeof (p == null ? void 0 : p.then) === "function";
}
function addPendingPromiseToDependency(atom, promise, dependencyAtomState) {
if (!dependencyAtomState.p.has(atom)) {
dependencyAtomState.p.add(atom);
const cleanup = () => dependencyAtomState.p.delete(atom);
promise.then(cleanup, cleanup);
}
}
function getMountedOrPendingDependents(atom, atomState, mountedMap) {
const mounted = mountedMap.get(atom);
const mountedDependents = mounted == null ? void 0 : mounted.t;
const pendingDependents = atomState.p;
if (!(mountedDependents == null ? void 0 : mountedDependents.size)) return pendingDependents;
if (!pendingDependents.size) return mountedDependents;
const dependents = new Set(mountedDependents);
for (const a of pendingDependents) dependents.add(a);
return dependents;
}
function hasOnInit(atom) {
return !!atom.INTERNAL_onInit;
}
const BUILDING_BLOCK_atomRead = (_buildingBlocks, _store, atom, ...params) => atom.read(...params);
const BUILDING_BLOCK_atomWrite = (_buildingBlocks, _store, atom, ...params) => atom.write(...params);
const BUILDING_BLOCK_atomOnInit = (_buildingBlocks, store, atom) => atom.INTERNAL_onInit(store);
const BUILDING_BLOCK_atomOnMount = (_buildingBlocks, _store, atom, setAtom) => {
var _a;
return (_a = atom.onMount) == null ? void 0 : _a.call(atom, setAtom);
};
const BUILDING_BLOCK_ensureAtomState = (buildingBlocks, store, atom) => {
var _a;
const atomStateMap = buildingBlocks[0];
let atomState = atomStateMap.get(atom);
if (!atomState) {
const storeHooks = buildingBlocks[6];
const atomOnInit = buildingBlocks[9];
atomState = {
d: /* @__PURE__ */ new Map(),
p: /* @__PURE__ */ new Set(),
n: 0
};
atomStateMap.set(atom, atomState);
(_a = storeHooks.i) == null || _a.call(storeHooks, atom);
if (hasOnInit(atom)) atomOnInit(buildingBlocks, store, atom);
}
return atomState;
};
const BUILDING_BLOCK_flushCallbacks = (buildingBlocks, store) => {
var _a;
const mountedMap = buildingBlocks[1];
const changedAtoms = buildingBlocks[3];
const mountCallbacks = buildingBlocks[4];
const unmountCallbacks = buildingBlocks[5];
const storeHooks = buildingBlocks[6];
const recomputeInvalidatedAtoms = buildingBlocks[13];
if (!storeHooks.f && !changedAtoms.size && !mountCallbacks.size && !unmountCallbacks.size) return;
const errors = [];
const call = (fn) => {
try {
fn();
} catch (e) {
errors.push(e);
}
};
do {
if (storeHooks.f) call(storeHooks.f);
const callbacks = /* @__PURE__ */ new Set();
for (const atom of changedAtoms) {
const listeners = (_a = mountedMap.get(atom)) == null ? void 0 : _a.l;
if (listeners) for (const listener of listeners) callbacks.add(listener);
}
changedAtoms.clear();
for (const fn of unmountCallbacks) callbacks.add(fn);
unmountCallbacks.clear();
for (const fn of mountCallbacks) callbacks.add(fn);
mountCallbacks.clear();
for (const fn of callbacks) call(fn);
if (changedAtoms.size) recomputeInvalidatedAtoms(buildingBlocks, store);
} while (changedAtoms.size || unmountCallbacks.size || mountCallbacks.size);
if (errors.length) throw new AggregateError(errors);
};
const BUILDING_BLOCK_recomputeInvalidatedAtoms = (buildingBlocks, 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];
if (!changedAtoms.size) return;
const sortedReversedAtoms = [];
const sortedReversedStates = [];
const visiting = /* @__PURE__ */ new WeakSet();
const visited = /* @__PURE__ */ new WeakSet();
const stackAtoms = [];
const stackStates = [];
for (const atom of changedAtoms) {
stackAtoms.push(atom);
stackStates.push(ensureAtomState(buildingBlocks, store, atom));
}
while (stackAtoms.length) {
const top = stackAtoms.length - 1;
const a = stackAtoms[top];
const aState = stackStates[top];
if (visited.has(a)) {
stackAtoms.pop();
stackStates.pop();
continue;
}
if (visiting.has(a)) {
if (invalidatedAtoms.get(a) === aState.n) {
sortedReversedAtoms.push(a);
sortedReversedStates.push(aState);
} else if (({}.env ? {}.env.MODE : void 0) !== "production" && invalidatedAtoms.has(a)) throw new Error("[Bug] invalidated atom exists");
visited.add(a);
stackAtoms.pop();
stackStates.pop();
continue;
}
visiting.add(a);
for (const d of getMountedOrPendingDependents(a, aState, mountedMap)) if (!visiting.has(d)) {
stackAtoms.push(d);
stackStates.push(ensureAtomState(buildingBlocks, store, d));
}
}
for (let i = sortedReversedAtoms.length - 1; i >= 0; --i) {
const a = sortedReversedAtoms[i];
const aState = sortedReversedStates[i];
let hasChangedDeps = false;
for (const dep of aState.d.keys()) if (dep !== a && changedAtoms.has(dep)) {
hasChangedDeps = true;
break;
}
if (hasChangedDeps) {
invalidatedAtoms.set(a, aState.n);
readAtomState(buildingBlocks, store, a);
mountDependencies(buildingBlocks, store, a);
}
invalidatedAtoms.delete(a);
}
};
const storeMutationSet = /* @__PURE__ */ new WeakSet();
const BUILDING_BLOCK_readAtomState = (buildingBlocks, store, atom) => {
var _a, _b;
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 registerAbortHandler = buildingBlocks[26];
const storeEpochHolder = buildingBlocks[28];
const atomState = ensureAtomState(buildingBlocks, store, atom);
const storeEpochNumber = storeEpochHolder[0];
if (isAtomStateInitialized(atomState)) {
if (mountedMap.has(atom) && invalidatedAtoms.get(atom) !== atomState.n || atomState.m === storeEpochNumber) {
atomState.m = storeEpochNumber;
return atomState;
}
let hasChangedDeps = false;
for (const [a, n] of atomState.d) if (readAtomState(buildingBlocks, store, a).n !== n) {
hasChangedDeps = true;
break;
}
if (!hasChangedDeps) {
atomState.m = storeEpochNumber;
return atomState;
}
}
let isSync = true;
const prevDeps = new Set(atomState.d.keys());
const pruneDependencies = () => {
for (const a of prevDeps) atomState.d.delete(a);
};
const mountDependenciesIfAsync = () => {
if (mountedMap.has(atom)) {
const shouldRecompute = !changedAtoms.size;
mountDependencies(buildingBlocks, store, atom);
if (shouldRecompute) {
recomputeInvalidatedAtoms(buildingBlocks, store);
flushCallbacks(buildingBlocks, store);
}
}
};
const getter = (a) => {
var _a2;
if (a === atom) {
const aState2 = ensureAtomState(buildingBlocks, store, a);
if (!isAtomStateInitialized(aState2)) if (hasInitialValue(a)) setAtomStateValueOrPromise(buildingBlocks, store, a, a.init);
else throw new Error("no atom init");
return returnAtomValue(aState2);
}
const aState = readAtomState(buildingBlocks, store, a);
try {
return returnAtomValue(aState);
} finally {
prevDeps.delete(a);
atomState.d.set(a, aState.n);
if (isPromiseLike$1(atomState.v)) addPendingPromiseToDependency(atom, atomState.v, aState);
if (mountedMap.has(atom)) (_a2 = mountedMap.get(a)) == null || _a2.t.add(atom);
if (!isSync) mountDependenciesIfAsync();
}
};
let controller;
let setSelf;
const options = {
get signal() {
if (!controller) controller = new AbortController();
return controller.signal;
},
get setSelf() {
if (({}.env ? {}.env.MODE : void 0) !== "production") console.warn("[DEPRECATED] setSelf is deprecated and will be removed in v3.");
if (({}.env ? {}.env.MODE : void 0) !== "production" && !isActuallyWritableAtom(atom)) console.warn("setSelf function cannot be used with read-only atom");
if (!setSelf && isActuallyWritableAtom(atom)) setSelf = (...args) => {
if (({}.env ? {}.env.MODE : void 0) !== "production" && isSync) console.warn("setSelf function cannot be called in sync");
if (!isSync) try {
return writeAtomState(buildingBlocks, store, atom, args);
} finally {
recomputeInvalidatedAtoms(buildingBlocks, store);
flushCallbacks(buildingBlocks, store);
}
};
return setSelf;
}
};
const prevEpochNumber = atomState.n;
const prevInvalidated = invalidatedAtoms.get(atom) === prevEpochNumber;
try {
if (({}.env ? {}.env.MODE : void 0) !== "production") storeMutationSet.delete(store);
const valueOrPromise = atomRead(buildingBlocks, store, atom, getter, options);
if (({}.env ? {}.env.MODE : void 0) !== "production" && storeMutationSet.has(store)) console.warn("Detected store mutation during atom read. This is not supported.");
setAtomStateValueOrPromise(buildingBlocks, store, atom, valueOrPromise);
if (isPromiseLike$1(valueOrPromise)) {
registerAbortHandler(buildingBlocks, store, valueOrPromise, () => controller == null ? void 0 : controller.abort());
const settle = () => {
pruneDependencies();
mountDependenciesIfAsync();
};
valueOrPromise.then(settle, settle);
} else pruneDependencies();
(_a = storeHooks.r) == null || _a.call(storeHooks, atom);
atomState.m = storeEpochNumber;
return atomState;
} catch (error) {
delete atomState.v;
atomState.e = error;
++atomState.n;
atomState.m = storeEpochNumber;
return atomState;
} finally {
isSync = false;
if (atomState.n !== prevEpochNumber && prevInvalidated) {
invalidatedAtoms.set(atom, atomState.n);
changedAtoms.add(atom);
(_b = storeHooks.c) == null || _b.call(storeHooks, atom);
}
}
};
const BUILDING_BLOCK_invalidateDependents = (buildingBlocks, store, atom) => {
const mountedMap = buildingBlocks[1];
const invalidatedAtoms = buildingBlocks[2];
const ensureAtomState = buildingBlocks[11];
const stack = [atom];
while (stack.length) {
const a = stack.pop();
const aState = ensureAtomState(buildingBlocks, store, a);
for (const d of getMountedOrPendingDependents(a, aState, mountedMap)) {
const dState = ensureAtomState(buildingBlocks, store, d);
if (invalidatedAtoms.get(d) !== dState.n) {
invalidatedAtoms.set(d, dState.n);
stack.push(d);
}
}
}
};
const BUILDING_BLOCK_writeAtomState = (buildingBlocks, store, atom, args) => {
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];
const storeEpochHolder = buildingBlocks[28];
let isSync = true;
const getter = (a) => returnAtomValue(readAtomState(buildingBlocks, store, a));
const setter = (a, ...args2) => {
var _a;
const aState = ensureAtomState(buildingBlocks, store, a);
try {
if (a === atom) {
if (!hasInitialValue(a)) throw new Error("atom not writable");
if (({}.env ? {}.env.MODE : void 0) !== "production") storeMutationSet.add(store);
const prevEpochNumber = aState.n;
const v = args2[0];
setAtomStateValueOrPromise(buildingBlocks, store, a, v);
mountDependencies(buildingBlocks, store, a);
if (prevEpochNumber !== aState.n) {
++storeEpochHolder[0];
changedAtoms.add(a);
invalidateDependents(buildingBlocks, store, a);
(_a = storeHooks.c) == null || _a.call(storeHooks, a);
}
return;
} else return writeAtomState(buildingBlocks, store, a, args2);
} finally {
if (!isSync) {
recomputeInvalidatedAtoms(buildingBlocks, store);
flushCallbacks(buildingBlocks, store);
}
}
};
try {
return atomWrite(buildingBlocks, store, atom, getter, setter, ...args);
} finally {
isSync = false;
}
};
const BUILDING_BLOCK_mountDependencies = (buildingBlocks, store, atom) => {
var _a;
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(buildingBlocks, store, atom);
const mounted = mountedMap.get(atom);
if (mounted && atomState.d.size > 0) {
for (const [a, n] of atomState.d) if (!mounted.d.has(a)) {
const aState = ensureAtomState(buildingBlocks, store, a);
mountAtom(buildingBlocks, store, a).t.add(atom);
mounted.d.add(a);
if (n !== aState.n) {
changedAtoms.add(a);
invalidateDependents(buildingBlocks, store, a);
(_a = storeHooks.c) == null || _a.call(storeHooks, a);
}
}
for (const a of mounted.d) if (!atomState.d.has(a)) {
mounted.d.delete(a);
unmountAtom(buildingBlocks, store, a)?.t.delete(atom);
}
}
};
const BUILDING_BLOCK_mountAtom = (buildingBlocks, store, atom) => {
var _a;
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(buildingBlocks, store, atom);
let mounted = mountedMap.get(atom);
if (!mounted) {
readAtomState(buildingBlocks, store, atom);
for (const a of atomState.d.keys()) mountAtom(buildingBlocks, store, a).t.add(atom);
mounted = {
l: /* @__PURE__ */ new Set(),
d: new Set(atomState.d.keys()),
t: /* @__PURE__ */ new Set()
};
mountedMap.set(atom, mounted);
if (isActuallyWritableAtom(atom) && hasOnMount(atom)) {
const processOnMount = () => {
let isSync = true;
const setAtom = (...args) => {
try {
return writeAtomState(buildingBlocks, store, atom, args);
} finally {
if (!isSync) {
recomputeInvalidatedAtoms(buildingBlocks, store);
flushCallbacks(buildingBlocks, store);
}
}
};
try {
const onUnmount = atomOnMount(buildingBlocks, store, atom, setAtom);
if (onUnmount) mounted.u = () => {
isSync = true;
try {
onUnmount();
} finally {
isSync = false;
}
};
} finally {
isSync = false;
}
};
mountCallbacks.add(processOnMount);
}
(_a = storeHooks.m) == null || _a.call(storeHooks, atom);
}
return mounted;
};
const BUILDING_BLOCK_unmountAtom = (buildingBlocks, store, atom) => {
var _a, _b;
const mountedMap = buildingBlocks[1];
const unmountCallbacks = buildingBlocks[5];
const storeHooks = buildingBlocks[6];
const ensureAtomState = buildingBlocks[11];
const unmountAtom = buildingBlocks[19];
const atomState = ensureAtomState(buildingBlocks, store, atom);
let mounted = mountedMap.get(atom);
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(atom)) {
isDependent = true;
break;
}
if (!isDependent) {
if (mounted.u) unmountCallbacks.add(mounted.u);
mounted = void 0;
mountedMap.delete(atom);
for (const a of atomState.d.keys()) unmountAtom(buildingBlocks, store, a)?.t.delete(atom);
(_b = storeHooks.u) == null || _b.call(storeHooks, atom);
return;
}
return mounted;
};
const BUILDING_BLOCK_setAtomStateValueOrPromise = (buildingBlocks, store, atom, valueOrPromise) => {
const ensureAtomState = buildingBlocks[11];
const abortPromise = buildingBlocks[27];
const atomState = ensureAtomState(buildingBlocks, store, atom);
const hasPrevValue = "v" in atomState;
const prevValue = atomState.v;
if (isPromiseLike$1(valueOrPromise)) for (const a of atomState.d.keys()) addPendingPromiseToDependency(atom, valueOrPromise, ensureAtomState(buildingBlocks, store, a));
atomState.v = valueOrPromise;
delete atomState.e;
if (!hasPrevValue || !Object.is(prevValue, atomState.v)) {
++atomState.n;
if (isPromiseLike$1(prevValue)) abortPromise(buildingBlocks, store, prevValue);
}
};
const BUILDING_BLOCK_storeGet = (buildingBlocks, store, atom) => {
const readAtomState = buildingBlocks[14];
return returnAtomValue(readAtomState(buildingBlocks, store, atom));
};
const BUILDING_BLOCK_storeSet = (buildingBlocks, store, atom, ...args) => {
const changedAtoms = buildingBlocks[3];
const flushCallbacks = buildingBlocks[12];
const recomputeInvalidatedAtoms = buildingBlocks[13];
const writeAtomState = buildingBlocks[16];
const prevChangedAtomsSize = changedAtoms.size;
try {
return writeAtomState(buildingBlocks, store, atom, args);
} finally {
if (changedAtoms.size !== prevChangedAtomsSize) {
recomputeInvalidatedAtoms(buildingBlocks, store);
flushCallbacks(buildingBlocks, store);
}
}
};
const BUILDING_BLOCK_storeSub = (buildingBlocks, store, atom, listener) => {
const flushCallbacks = buildingBlocks[12];
const mountAtom = buildingBlocks[18];
const unmountAtom = buildingBlocks[19];
const listeners = mountAtom(buildingBlocks, store, atom).l;
listeners.add(listener);
flushCallbacks(buildingBlocks, store);
return () => {
listeners.delete(listener);
unmountAtom(buildingBlocks, store, atom);
flushCallbacks(buildingBlocks, store);
};
};
const BUILDING_BLOCK_registerAbortHandler = (buildingBlocks, _store, promise, abortHandler) => {
const abortHandlersMap = buildingBlocks[25];
let abortHandlers = abortHandlersMap.get(promise);
if (!abortHandlers) {
abortHandlers = /* @__PURE__ */ new Set();
abortHandlersMap.set(promise, abortHandlers);
const cleanup = () => abortHandlersMap.delete(promise);
promise.then(cleanup, cleanup);
}
abortHandlers.add(abortHandler);
};
const BUILDING_BLOCK_abortPromise = (buildingBlocks, _store, promise) => {
buildingBlocks[25].get(promise)?.forEach((fn) => fn());
};
const buildingBlockMap = /* @__PURE__ */ new WeakMap();
function getBuildingBlocks(store) {
const buildingBlocks = buildingBlockMap.get(store);
if (({}.env ? {}.env.MODE : void 0) !== "production" && !buildingBlocks) throw new Error("Store must be created by buildStore to read its building blocks");
const enhanceBuildingBlocks = buildingBlocks[24];
if (enhanceBuildingBlocks) return enhanceBuildingBlocks(buildingBlocks, store);
return buildingBlocks;
}
function buildStore(...partialBuildingBlocks) {
const store = {
get(atom) {
return storeGet(buildingBlocks, store, atom);
},
set(atom, ...args) {
return storeSet(buildingBlocks, store, atom, ...args);
},
sub(atom, listener) {
return storeSub(buildingBlocks, store, atom, listener);
}
};
const buildingBlocks = [
/* @__PURE__ */ new WeakMap(),
/* @__PURE__ */ new WeakMap(),
/* @__PURE__ */ new WeakMap(),
/* @__PURE__ */ new Set(),
/* @__PURE__ */ new Set(),
/* @__PURE__ */ new Set(),
{},
BUILDING_BLOCK_atomRead,
BUILDING_BLOCK_atomWrite,
BUILDING_BLOCK_atomOnInit,
BUILDING_BLOCK_atomOnMount,
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,
/* @__PURE__ */ new WeakMap(),
BUILDING_BLOCK_registerAbortHandler,
BUILDING_BLOCK_abortPromise,
[0]
].map((fn, i) => partialBuildingBlocks[i] || fn);
buildingBlockMap.set(store, Object.freeze(buildingBlocks));
const storeGet = buildingBlocks[21];
const storeSet = buildingBlocks[22];
const storeSub = buildingBlocks[23];
return store;
}
//#endregion
//#region ../../node_modules/jotai/esm/vanilla.mjs
let keyCount = 0;
function atom(read, write) {
const key = `atom${++keyCount}`;
const config = { toString() {
return ({}.env ? {}.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);
}
function createStore() {
return buildStore();
}
let defaultStore;
function getDefaultStore() {
if (!defaultStore) {
defaultStore = createStore();
if (({}.env ? {}.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;
}
//#endregion
//#region ../../node_modules/jotai/esm/react.mjs
const StoreContext = (0, react$1.createContext)(void 0);
function useStore(options) {
const store = (0, react$1.useContext)(StoreContext);
return (options == null ? void 0 : options.store) || store || getDefaultStore();
}
const isPromiseLike = (x) => typeof (x == null ? void 0 : x.then) === "function";
const attachPromiseStatus = (promise) => {
if (!promise.status) {
promise.status = "pending";
promise.then((v) => {
promise.status = "fulfilled";
promise.value = v;
}, (e) => {
promise.status = "rejected";
promise.reason = e;
});
}
};
const use = react$1.default.use || ((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;
}
});
const continuablePromiseMap = /* @__PURE__ */ new WeakMap();
const createContinuablePromise = (store, promise, getValue) => {
const buildingBlocks = getBuildingBlocks(store);
const registerAbortHandler = buildingBlocks[26];
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 (isPromiseLike(nextValue)) {
continuablePromiseMap.set(nextValue, continuablePromise);
curr = nextValue;
nextValue.then(onFulfilled(nextValue), onRejected(nextValue));
registerAbortHandler(buildingBlocks, store, nextValue, onAbort);
} else resolve(nextValue);
} catch (e) {
reject(e);
}
};
promise.then(onFulfilled(promise), onRejected(promise));
registerAbortHandler(buildingBlocks, store, promise, onAbort);
});
continuablePromiseMap.set(promise, continuablePromise);
}
return continuablePromise;
};
function useAtomValue(atom, options) {
const { delay, unstable_promiseStatus: promiseStatus = !react$1.default.use } = options || {};
const store = useStore(options);
const [[valueFromReducer, storeFromReducer, atomFromReducer], rerender] = (0, react$1.useReducer)((prev) => {
const nextValue = store.get(atom);
if (Object.is(prev[0], nextValue) && prev[1] === store && prev[2] === atom) return prev;
return [
nextValue,
store,
atom
];
}, void 0, () => [
store.get(atom),
store,
atom
]);
let value = valueFromReducer;
if (storeFromReducer !== store || atomFromReducer !== atom) {
rerender();
value = store.get(atom);
}
(0, react$1.useEffect)(() => {
const unsub = store.sub(atom, () => {
if (promiseStatus) try {
const value2 = store.get(atom);
if (isPromiseLike(value2)) attachPromiseStatus(createContinuablePromise(store, value2, () => store.get(atom)));
} catch (e) {}
if (typeof delay === "number") {
console.warn(`[DEPRECATED] delay option is deprecated and will be removed in v3.
Migration guide:
Create a custom hook like the following.
function useAtomValueWithDelay<Value>(
atom: Atom<Value>,
options: { delay: number },
): Value {
const { delay } = options
const store = useStore(options)
const [value, setValue] = useState(() => store.get(atom))
useEffect(() => {
const unsub = store.sub(atom, () => {
setTimeout(() => setValue(store.get(atom)), delay)
})
return unsub
}, [store, atom, delay])
return value
}
`);
setTimeout(rerender, delay);
return;
}
rerender();
});
rerender();
return unsub;
}, [
store,
atom,
delay,
promiseStatus
]);
(0, react$1.useDebugValue)(value);
if (isPromiseLike(value)) {
const promise = createContinuablePromise(store, value, () => store.get(atom));
if (promiseStatus) attachPromiseStatus(promise);
return use(promise);
}
return value;
}
function useSetAtom(atom, options) {
const store = useStore(options);
return (0, react$1.useCallback)((...args) => {
if (({}.env ? {}.env.MODE : void 0) !== "production" && !("write" in atom)) throw new Error("not writable atom");
return store.set(atom, ...args);
}, [store, atom]);
}
//#endregion
//#region src/hooks.tsx
const store = createStore();
const storyContextAtom = atom(null);
/**
* Hook that returns a function to set the current story context.
*/
function useSetStoryContext() {
return useSetAtom(storyContextAtom, { store });
}
/**
* Hook to read the current story context.
*/
function useStoryContext() {
return useAtomValue(storyContextAtom, { store });
}
//#endregion
//#region src/components/StoryView/ErrorBoundary.tsx
var ErrorBoundary = class extends react.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, react_jsx_runtime.jsx)(react_native.View, {
style: {
margin: 16,
padding: 16,
borderColor: "red",
borderWidth: 2,
alignItems: "center",
justifyContent: "center",
borderRadius: 4
},
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_native.Text, {
style: { fontWeight: "bold" },
children: "Something went wrong rendering your story"
})
});
return this.props.children;
}
};
//#endregion
//#region src/components/StoryView/StoryView.tsx
/**
* This is a handler for `onStartShouldSetResponder`, which dismisses the
* keyboard as a side effect but then responds with `false` to the responder
* system, so as not to start actually handling the touch.
*
* The objective here is to dismiss the keyboard when the story view is tapped,
* but in a way that won't interfere with presses or swipes. Using a
* `Touchable...` component as a wrapper will start to handle the touch, which
* will swallow swipe gestures that should have gone on to a child view, such
* as `ScrollView`.
*/
function dismissOnStartResponder() {
react_native.Keyboard.dismiss();
return false;
}
const Text = _storybook_react_native_theming.styled.Text(({ theme }) => ({ color: theme?.color?.defaultText }));
const errorContainerStyle = {
flex: 1,
padding: 16,
alignItems: "center",
justifyContent: "center"
};
const layoutStyles = {
padded: { padding: 8 },
centered: {
alignItems: "center",
justifyContent: "center"
},
fullscreen: {}
};
const StoryView = ({ useWrapper = true, storyBackgroundColor }) => {
const context = useStoryContext();
const id = context?.id;
const theme = (0, _storybook_react_native_theming.useTheme)();
const containerStyle = (0, react.useMemo)(() => {
const layout = context?.parameters?.layout;
const layoutStyle = typeof layout === "string" && layout in layoutStyles ? layoutStyles[layout] : {};
return {
flex: 1,
backgroundColor: storyBackgroundColor || theme.background?.content,
overflow: "hidden",
...layoutStyle
};
}, [
theme.background?.content,
context?.parameters?.layout,
storyBackgroundColor
]);
const onError = (0, react.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, react_jsx_runtime.jsx)(react_native.View, {
style: containerStyle,
testID: id,
accessibilityLabel: id,
importantForAccessibility: "no",
onStartShouldSetResponder: dismissOnStartResponder,
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ErrorBoundary, {
onError,
children: StoryComponent && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(StoryComponent, { ...context })
})
}, id);
return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ErrorBoundary, {
onError,
children: StoryComponent && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(StoryComponent, { ...context })
});
}
return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_native.View, {
style: errorContainerStyle,
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Text, { children: "Please select a story to preview." })
});
};
var StoryView_default = react.default.memo(StoryView);
//#endregion
//#region src/constants.ts
const RN_STORYBOOK_STORAGE_KEY = "lastOpenedStory";
const RN_STORYBOOK_EVENTS = {
RN_GET_INDEX: "RN_GET_INDEX",
RN_GET_INDEX_RESPONSE: "RN_GET_INDEX_RESPONSE"
};
const STORYBOOK_STORY_ID_PARAM = "STORYBOOK_STORY_ID";
//#endregion
//#region src/View.tsx
function resolveStoryBackgroundColor(story) {
const backgroundGlobal = story?.globals?.backgrounds?.value;
const bgParams = story?.parameters?.backgrounds;
const backgroundName = backgroundGlobal;
if (!backgroundName) return void 0;
if (bgParams?.options?.[backgroundName]?.value) return bgParams.options[backgroundName].value;
if (backgroundName.startsWith("#")) return backgroundName;
}
var View$1 = class {
_storyIndex;
_setStory = () => {};
_forceRerender = () => {};
_ready = false;
_preview;
_asyncStorageStoryId = null;
_webUrl;
_storage;
_channel;
_options;
_idToPrepared = {};
constructor(preview, channel, options) {
this._preview = preview;
this._channel = channel;
this._options = options ?? {};
}
_storyIdExists = (storyId) => {
return Object.keys(this._storyIndex.entries).includes(storyId);
};
_selectInitialStory = async ({ selectionSpecifier, storyIdFromUrl }) => {
this._preview.selectionStore.selectionSpecifier = storyIdFromUrl ? {
storySpecifier: storyIdFromUrl,
viewMode: "story"
} : selectionSpecifier;
this._preview.selectionStore.selection = void 0;
await this._preview.selectSpecifiedStory();
};
_getInitialStory = async ({ initialSelection, shouldPersistSelection = true } = {}) => {
if (initialSelection) if (typeof initialSelection === "string") return {
storySpecifier: initialSelection,
viewMode: "story"
};
else return {
storySpecifier: (0, storybook_internal_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);
if (!value) {
await new Promise((resolve) => setTimeout(resolve, 100));
value = await this._storage.getItem(RN_STORYBOOK_STORAGE_KEY);
}
this._asyncStorageStoryId = value;
}
return {
storySpecifier: (value && this._storyIdExists(value) ? value : void 0) ?? "*",
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 react_native.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;
};
_isSecureConnection = (params = {}) => {
if (typeof params.secured === "boolean") return params.secured;
return globalThis.STORYBOOK_WEBSOCKET?.secured ?? false;
};
_getServerChannel = (params = {}) => {
const host = this._getHost(params);
const port = `:${this.__getPort(params)}`;
const query = params.query || "";
const channel = new storybook_internal_channels.Channel({
async: true,
transport: new storybook_internal_channels.WebsocketTransport({
url: `${this._isSecureConnection(params) ? "wss" : "ws"}://${host}${port}/${query}`,
onError: (e) => {
console.log(`WebsocketTransport error ${JSON.stringify(e)}`);
}
})
});
patchChannelForRN(channel);
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 { enableWebsockets = !!globalThis.STORYBOOK_WEBSOCKET, CustomUIComponent, hasStoryWrapper: storyViewWrapper = true } = params;
const storage = params.storage ?? {
getItem: async (key) => null,
setItem: async (key, value) => {}
};
const onDeviceUI = this._options?.disableUI ? false : params.onDeviceUI ?? true;
const shouldPersistSelection = this._options.disableUI ? false : params.shouldPersistSelection ?? true;
const getFullUI = (enabled) => {
if (enabled) try {
const { FullUI } = require("@storybook/react-native-ui");
return FullUI;
} catch (error) {
console.warn("storybook-log: error loading UI", error);
}
const PlaceholderUI = ({ children }) => children;
return PlaceholderUI;
};
const FullUI = getFullUI(onDeviceUI && !CustomUIComponent);
this._storage = storage ?? {
getItem: async (key) => null,
setItem: async (key, value) => {}
};
if (enableWebsockets) {
const channel = this._getServerChannel(params);
storybook_manager_api.addons.setChannel(channel);
storybook_internal_preview_api.addons.setChannel(channel);
this._channel = channel;
this._preview.channel = channel;
this._preview.setupListeners();
channel.emit(storybook_internal_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 });
});
storybook_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, react_native.useColorScheme)();
const [update, forceUpdate] = (0, react.useReducer)((x) => x + 1, 0);
const [ready, setReady] = (0, react.useState)(false);
const appliedTheme = (0, react.useMemo)(() => (0, deepmerge.default)(colorScheme === "dark" ? _storybook_react_native_theming.darkTheme : _storybook_react_native_theming.theme, params.theme ?? {}), [colorScheme]);
(0, react.useEffect)(() => {
const listener = react_native.Linking.addEventListener("url", ({ url }) => {
if (typeof url === "string") {
const storyId = new URL(url).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(storybook_internal_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, react.useEffect)(() => {
self.createPreparedStoryMapping().then(() => react_native.Linking.getInitialURL().then((url) => {
if (url && typeof url === "string") {
const storyId = new URL(url).searchParams.get(STORYBOOK_STORY_ID_PARAM);
const hasStoryId = 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;
}
return null;
})).then((initialStoryIdFromUrl) => self._getInitialStory(params).then((st) => {
if (initialStoryIdFromUrl) console.log(`STORYBOOK: Setting initial story from Linking event, storyId: ${initialStoryIdFromUrl}`);
return self._selectInitialStory({
selectionSpecifier: st,
storyIdFromUrl: initialStoryIdFromUrl
});
})).then(() => {
const currentStoryId = self._preview.currentSelection?.storyId;
const preparedStory = currentStoryId ? self._idToPrepared[currentStoryId] : void 0;
if (preparedStory) setContext(self._preview.getStoryContext(preparedStory));
self._ready = true;
setReady(true);
}).catch((e) => console.error(e));
self._setStory = (newStory) => {
setContext(newStory);
if (shouldPersistSelection && !params.storage) console.warn(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._ready) try {
self._asyncStorageStoryId = newStory.id;
const ret = self._storage.setItem(RN_STORYBOOK_STORAGE_KEY, newStory.id);
if (ret && typeof ret.then === "function") ret.catch((e) => {
console.warn("storybook-log: error writing to async storage", e);
});
} catch (e) {
console.warn("storybook-log: error writing to async storage", e);
}
};
self._forceRerender = () => forceUpdate();
}, []);
const storyHash = (0, react.useMemo)(() => {
if (!ready) return {};
return (0, _storybook_react_native_ui_common.transformStoryIndexToStoriesHash)(self._storyIndex, {
docsOptions: {
docsMode: false,
defaultName: ""
},
filters: {},
allStatuses: {},
provider: {
handleAPI: () => ({}),
getConfig: () => ({})
}
});
}, [ready, update]);
if (!ready) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_native.View, {
style: {
position: "absolute",
top: 0,
left: 0,
right: 0,
bottom: 0,
alignItems: "center",
justifyContent: "center"
},
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_native.ActivityIndicator, {
animating: true,
size: "large"
})
});
const storyBackgroundColor = globalThis.FEATURES?.ondeviceBackgrounds ? resolveStoryBackgroundColor(story) : void 0;
if (onDeviceUI) {
if (CustomUIComponent) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CustomUIComponent, {
story,
storyHash,
setStory: (newStoryId) => self._channel.emit(storybook_internal_core_events.SET_CURRENT_STORY, { storyId: newStoryId }),
storage,
theme: appliedTheme,
storyBackgroundColor,
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(StoryView_default, {
useWrapper: storyViewWrapper,
storyBackgroundColor
})
});
return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(FullUI, {
storage,
theme: appliedTheme,
storyHash,
story,
setStory: (newStoryId) => self._channel.emit(storybook_internal_core_events.SET_CURRENT_STORY, { storyId: newStoryId }),
storyBackgroundColor,
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(StoryView_default, {
useWrapper: storyViewWrapper,
storyBackgroundColor
})
});
} else return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_native_safe_area_context.SafeAreaProvider, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_native.StatusBar, { hidden: true }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(WithSafeArea, {
id: story?.id ?? "",
safeAreaEnabled: !(story?.parameters?.noSafeArea ?? false),
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(StoryView_default, {
useWrapper: storyViewWrapper,
storyBackgroundColor
})
})] });
};
};
};
const WithSafeArea = ({ children, id, safeAreaEnabled }) => {
const insets = (0, react_native_safe_area_context.useSafeAreaInsets)();
return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_native.View, {
style: {
flex: 1,
paddingTop: safeAreaEnabled ? insets.top : 0,
paddingBottom: safeAreaEnabled ? insets.bottom : 0
},
accessibilityLabel: id,
testID: id,
accessible: true,
children
});
};
//#endregion
//#region src/prepareStories.ts
function prepareStories({ storyEntries, options, storySort }) {
let index = {
v: 5,
entries: {}
};
let importMap = {};
const makeTitle = (fileName, specifier, userTitle) => {
const title = (0, storybook_internal_preview_api.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, storybook_internal_csf.isExportStory)(key, fileExports.default)) return;
const exportValue = fileExports[key];
if (!exportValue) return;
const title = makeTitle(filename, specifier, meta.title);
if (title) {
const nameFromExport = (0, storybook_internal_csf.storyNameFromExport)(key);
const id = (0, storybook_internal_csf.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)}`,
tags: ["story"],
subtype: "story"
};
const importedStories = req(filename);
const stories = Object.entries(importedStories).reduce((carry, [storyKey, story]) => {
if (!(0, storybook_internal_csf.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 typedError = error;
const errorString = typedError.message && typedError.stack ? `${typedError.message}\n ${typedError.stack}` : typedError.toString();
console.error(`Unexpected error while loading ${filename}: ${errorString}`);
}
});
});
const sortableStories = Object.values(index.entries);
(0, storybook_internal_preview_api.sortStoriesV7)(sortableStories, storySort, Object.values(index.entries).map((entry) => entry.importPath));
return {
index: {
v: 5,
entries: sortableStories.reduce((acc, item) => {
acc[item.id] = item;
return acc;
}, {})
},
importMap
};
}
//#endregion
//#region src/backgrounds/Swatch.tsx
var PressableSwatch, ColorSwatch, ValueContainer, NameText, ValueText, Swatch;
var init_Swatch = require_chunk.__esmMin((() => {
PressableSwatch = _storybook_react_native_theming.styled.TouchableOpacity(({ theme }) => ({
marginBottom: 10,
borderWidth: 1,
borderColor: theme.appBorderColor,
borderRadius: 6,
backgroundColor: theme.background.content,
paddingVertical: 4,
paddingHorizontal: 4
}));
ColorSwatch = _storybook_react_native_theming.styled.View(({ color, theme }) => ({
heig