UNPKG

43.3 kBJavaScriptView Raw
1var __create = Object.create;
2var __defProp = Object.defineProperty;
3var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4var __getOwnPropNames = Object.getOwnPropertyNames;
5var __getProtoOf = Object.getPrototypeOf;
6var __hasOwnProp = Object.prototype.hasOwnProperty;
7var __export = (target, all) => {
8 for (var name in all)
9 __defProp(target, name, { get: all[name], enumerable: true });
10};
11var __copyProps = (to, from, except, desc) => {
12 if (from && typeof from === "object" || typeof from === "function") {
13 for (let key of __getOwnPropNames(from))
14 if (!__hasOwnProp.call(to, key) && key !== except)
15 __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16 }
17 return to;
18};
19var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20 // If the importer is in node compatibility mode or this is not an ESM
21 // file that has been converted to a CommonJS file using a Babel-
22 // compatible transform (i.e. "__esModule" has not been set), then set
23 // "default" to the CommonJS "module.exports" for node compatibility.
24 isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25 mod
26));
27var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
29// src/index.ts
30var src_exports = {};
31__export(src_exports, {
32 darkTheme: () => import_react_native_theming3.darkTheme,
33 getProjectAnnotations: () => getProjectAnnotations,
34 prepareStories: () => prepareStories,
35 start: () => start,
36 theme: () => import_react_native_theming3.theme,
37 updateView: () => updateView
38});
39module.exports = __toCommonJS(src_exports);
40var import_react_native_theming3 = require("@storybook/react-native-theming");
41
42// src/Start.tsx
43var import_react_native4 = require("react-native");
44var import_manager_api2 = require("@storybook/core/manager-api");
45var import_preview_api2 = require("@storybook/core/preview-api");
46var import_csf2 = require("@storybook/csf");
47var import_channels2 = require("@storybook/core/channels");
48
49// src/View.tsx
50var import_bottom_sheet = require("@gorhom/bottom-sheet");
51var import_channels = require("@storybook/core/channels");
52var import_core_events = __toESM(require("@storybook/core/core-events"));
53var import_csf = require("@storybook/csf");
54var import_manager_api = require("@storybook/core/manager-api");
55var import_preview_api = require("@storybook/core/preview-api");
56var import_react_native_theming2 = require("@storybook/react-native-theming");
57var import_react_native_ui = require("@storybook/react-native-ui");
58var import_dedent = __toESM(require("dedent"));
59var import_deepmerge = __toESM(require("deepmerge"));
60var import_react4 = require("react");
61var import_react_native3 = require("react-native");
62var import_react_native_gesture_handler = require("react-native-gesture-handler");
63var import_react_native_safe_area_context = require("react-native-safe-area-context");
64
65// src/components/StoryView/StoryView.tsx
66var import_react3 = __toESM(require("react"));
67var import_react_native_theming = require("@storybook/react-native-theming");
68var import_react_native2 = require("react-native");
69
70// ../../node_modules/jotai/esm/vanilla.mjs
71var import_meta = {};
72var keyCount = 0;
73function atom(read, write) {
74 const key = `atom${++keyCount}`;
75 const config = {
76 toString: () => key
77 };
78 if (typeof read === "function") {
79 config.read = read;
80 } else {
81 config.init = read;
82 config.read = function(get) {
83 return get(this);
84 };
85 config.write = function(get, set, arg) {
86 return set(
87 this,
88 typeof arg === "function" ? arg(get(this)) : arg
89 );
90 };
91 }
92 if (write) {
93 config.write = write;
94 }
95 return config;
96}
97var hasInitialValue = (atom2) => "init" in atom2;
98var isActuallyWritableAtom = (atom2) => !!atom2.write;
99var cancelPromiseMap = /* @__PURE__ */ new WeakMap();
100var registerCancelPromise = (promise, cancel) => {
101 cancelPromiseMap.set(promise, cancel);
102 promise.catch(() => {
103 }).finally(() => cancelPromiseMap.delete(promise));
104};
105var cancelPromise = (promise, next) => {
106 const cancel = cancelPromiseMap.get(promise);
107 if (cancel) {
108 cancelPromiseMap.delete(promise);
109 cancel(next);
110 }
111};
112var resolvePromise = (promise, value) => {
113 promise.status = "fulfilled";
114 promise.value = value;
115};
116var rejectPromise = (promise, e) => {
117 promise.status = "rejected";
118 promise.reason = e;
119};
120var isPromiseLike = (x) => typeof (x == null ? void 0 : x.then) === "function";
121var isEqualAtomValue = (a, b) => !!a && "v" in a && "v" in b && Object.is(a.v, b.v);
122var isEqualAtomError = (a, b) => !!a && "e" in a && "e" in b && Object.is(a.e, b.e);
123var hasPromiseAtomValue = (a) => !!a && "v" in a && a.v instanceof Promise;
124var isEqualPromiseAtomValue = (a, b) => "v" in a && "v" in b && a.v.orig && a.v.orig === b.v.orig;
125var returnAtomValue = (atomState) => {
126 if ("e" in atomState) {
127 throw atomState.e;
128 }
129 return atomState.v;
130};
131var createStore = () => {
132 const atomStateMap = /* @__PURE__ */ new WeakMap();
133 const mountedMap = /* @__PURE__ */ new WeakMap();
134 const pendingMap = /* @__PURE__ */ new Map();
135 let storeListenersRev2;
136 let mountedAtoms;
137 if ((import_meta.env ? import_meta.env.MODE : void 0) !== "production") {
138 storeListenersRev2 = /* @__PURE__ */ new Set();
139 mountedAtoms = /* @__PURE__ */ new Set();
140 }
141 const getAtomState = (atom2) => atomStateMap.get(atom2);
142 const setAtomState = (atom2, atomState) => {
143 if ((import_meta.env ? import_meta.env.MODE : void 0) !== "production") {
144 Object.freeze(atomState);
145 }
146 const prevAtomState = atomStateMap.get(atom2);
147 atomStateMap.set(atom2, atomState);
148 if (!pendingMap.has(atom2)) {
149 pendingMap.set(atom2, prevAtomState);
150 }
151 if (hasPromiseAtomValue(prevAtomState)) {
152 const next = "v" in atomState ? atomState.v instanceof Promise ? atomState.v : Promise.resolve(atomState.v) : Promise.reject(atomState.e);
153 if (prevAtomState.v !== next) {
154 cancelPromise(prevAtomState.v, next);
155 }
156 }
157 };
158 const updateDependencies = (atom2, nextAtomState, nextDependencies) => {
159 const dependencies = /* @__PURE__ */ new Map();
160 let changed = false;
161 nextDependencies.forEach((aState, a) => {
162 if (!aState && a === atom2) {
163 aState = nextAtomState;
164 }
165 if (aState) {
166 dependencies.set(a, aState);
167 if (nextAtomState.d.get(a) !== aState) {
168 changed = true;
169 }
170 } else if ((import_meta.env ? import_meta.env.MODE : void 0) !== "production") {
171 console.warn("[Bug] atom state not found");
172 }
173 });
174 if (changed || nextAtomState.d.size !== dependencies.size) {
175 nextAtomState.d = dependencies;
176 }
177 };
178 const setAtomValue = (atom2, value, nextDependencies) => {
179 const prevAtomState = getAtomState(atom2);
180 const nextAtomState = {
181 d: (prevAtomState == null ? void 0 : prevAtomState.d) || /* @__PURE__ */ new Map(),
182 v: value
183 };
184 if (nextDependencies) {
185 updateDependencies(atom2, nextAtomState, nextDependencies);
186 }
187 if (isEqualAtomValue(prevAtomState, nextAtomState) && prevAtomState.d === nextAtomState.d) {
188 return prevAtomState;
189 }
190 if (hasPromiseAtomValue(prevAtomState) && hasPromiseAtomValue(nextAtomState) && isEqualPromiseAtomValue(prevAtomState, nextAtomState)) {
191 if (prevAtomState.d === nextAtomState.d) {
192 return prevAtomState;
193 } else {
194 nextAtomState.v = prevAtomState.v;
195 }
196 }
197 setAtomState(atom2, nextAtomState);
198 return nextAtomState;
199 };
200 const setAtomValueOrPromise = (atom2, valueOrPromise, nextDependencies, abortPromise) => {
201 if (isPromiseLike(valueOrPromise)) {
202 let continuePromise;
203 const updatePromiseDependencies = () => {
204 const prevAtomState = getAtomState(atom2);
205 if (!hasPromiseAtomValue(prevAtomState) || prevAtomState.v !== promise) {
206 return;
207 }
208 const nextAtomState = setAtomValue(
209 atom2,
210 promise,
211 nextDependencies
212 );
213 if (mountedMap.has(atom2) && prevAtomState.d !== nextAtomState.d) {
214 mountDependencies(atom2, nextAtomState, prevAtomState.d);
215 }
216 };
217 const promise = new Promise((resolve, reject) => {
218 let settled = false;
219 valueOrPromise.then(
220 (v) => {
221 if (!settled) {
222 settled = true;
223 resolvePromise(promise, v);
224 resolve(v);
225 updatePromiseDependencies();
226 }
227 },
228 (e) => {
229 if (!settled) {
230 settled = true;
231 rejectPromise(promise, e);
232 reject(e);
233 updatePromiseDependencies();
234 }
235 }
236 );
237 continuePromise = (next) => {
238 if (!settled) {
239 settled = true;
240 next.then(
241 (v) => resolvePromise(promise, v),
242 (e) => rejectPromise(promise, e)
243 );
244 resolve(next);
245 }
246 };
247 });
248 promise.orig = valueOrPromise;
249 promise.status = "pending";
250 registerCancelPromise(promise, (next) => {
251 if (next) {
252 continuePromise(next);
253 }
254 abortPromise == null ? void 0 : abortPromise();
255 });
256 return setAtomValue(atom2, promise, nextDependencies);
257 }
258 return setAtomValue(atom2, valueOrPromise, nextDependencies);
259 };
260 const setAtomError = (atom2, error, nextDependencies) => {
261 const prevAtomState = getAtomState(atom2);
262 const nextAtomState = {
263 d: (prevAtomState == null ? void 0 : prevAtomState.d) || /* @__PURE__ */ new Map(),
264 e: error
265 };
266 if (nextDependencies) {
267 updateDependencies(atom2, nextAtomState, nextDependencies);
268 }
269 if (isEqualAtomError(prevAtomState, nextAtomState) && prevAtomState.d === nextAtomState.d) {
270 return prevAtomState;
271 }
272 setAtomState(atom2, nextAtomState);
273 return nextAtomState;
274 };
275 const readAtomState = (atom2, force) => {
276 const atomState = getAtomState(atom2);
277 if (!force && atomState) {
278 if (mountedMap.has(atom2)) {
279 return atomState;
280 }
281 if (Array.from(atomState.d).every(([a, s]) => {
282 if (a === atom2) {
283 return true;
284 }
285 const aState = readAtomState(a);
286 return aState === s || isEqualAtomValue(aState, s);
287 })) {
288 return atomState;
289 }
290 }
291 const nextDependencies = /* @__PURE__ */ new Map();
292 let isSync = true;
293 const getter = (a) => {
294 if (a === atom2) {
295 const aState2 = getAtomState(a);
296 if (aState2) {
297 nextDependencies.set(a, aState2);
298 return returnAtomValue(aState2);
299 }
300 if (hasInitialValue(a)) {
301 nextDependencies.set(a, void 0);
302 return a.init;
303 }
304 throw new Error("no atom init");
305 }
306 const aState = readAtomState(a);
307 nextDependencies.set(a, aState);
308 return returnAtomValue(aState);
309 };
310 let controller;
311 let setSelf;
312 const options = {
313 get signal() {
314 if (!controller) {
315 controller = new AbortController();
316 }
317 return controller.signal;
318 },
319 get setSelf() {
320 if ((import_meta.env ? import_meta.env.MODE : void 0) !== "production" && !isActuallyWritableAtom(atom2)) {
321 console.warn("setSelf function cannot be used with read-only atom");
322 }
323 if (!setSelf && isActuallyWritableAtom(atom2)) {
324 setSelf = (...args) => {
325 if ((import_meta.env ? import_meta.env.MODE : void 0) !== "production" && isSync) {
326 console.warn("setSelf function cannot be called in sync");
327 }
328 if (!isSync) {
329 return writeAtom(atom2, ...args);
330 }
331 };
332 }
333 return setSelf;
334 }
335 };
336 try {
337 const valueOrPromise = atom2.read(getter, options);
338 return setAtomValueOrPromise(
339 atom2,
340 valueOrPromise,
341 nextDependencies,
342 () => controller == null ? void 0 : controller.abort()
343 );
344 } catch (error) {
345 return setAtomError(atom2, error, nextDependencies);
346 } finally {
347 isSync = false;
348 }
349 };
350 const readAtom = (atom2) => returnAtomValue(readAtomState(atom2));
351 const addAtom = (atom2) => {
352 let mounted = mountedMap.get(atom2);
353 if (!mounted) {
354 mounted = mountAtom(atom2);
355 }
356 return mounted;
357 };
358 const canUnmountAtom = (atom2, mounted) => !mounted.l.size && (!mounted.t.size || mounted.t.size === 1 && mounted.t.has(atom2));
359 const delAtom = (atom2) => {
360 const mounted = mountedMap.get(atom2);
361 if (mounted && canUnmountAtom(atom2, mounted)) {
362 unmountAtom(atom2);
363 }
364 };
365 const recomputeDependents = (atom2) => {
366 const dependencyMap = /* @__PURE__ */ new Map();
367 const dirtyMap = /* @__PURE__ */ new WeakMap();
368 const getDependents = (a) => {
369 var _a;
370 const dependents = new Set((_a = mountedMap.get(a)) == null ? void 0 : _a.t);
371 pendingMap.forEach((_, pendingAtom) => {
372 var _a2;
373 if ((_a2 = getAtomState(pendingAtom)) == null ? void 0 : _a2.d.has(a)) {
374 dependents.add(pendingAtom);
375 }
376 });
377 return dependents;
378 };
379 const loop1 = (a) => {
380 getDependents(a).forEach((dependent) => {
381 if (dependent !== a) {
382 dependencyMap.set(
383 dependent,
384 (dependencyMap.get(dependent) || /* @__PURE__ */ new Set()).add(a)
385 );
386 dirtyMap.set(dependent, (dirtyMap.get(dependent) || 0) + 1);
387 loop1(dependent);
388 }
389 });
390 };
391 loop1(atom2);
392 const loop2 = (a) => {
393 getDependents(a).forEach((dependent) => {
394 var _a;
395 if (dependent !== a) {
396 let dirtyCount = dirtyMap.get(dependent);
397 if (dirtyCount) {
398 dirtyMap.set(dependent, --dirtyCount);
399 }
400 if (!dirtyCount) {
401 let isChanged = !!((_a = dependencyMap.get(dependent)) == null ? void 0 : _a.size);
402 if (isChanged) {
403 const prevAtomState = getAtomState(dependent);
404 const nextAtomState = readAtomState(dependent, true);
405 isChanged = !isEqualAtomValue(prevAtomState, nextAtomState);
406 }
407 if (!isChanged) {
408 dependencyMap.forEach((s) => s.delete(dependent));
409 }
410 }
411 loop2(dependent);
412 }
413 });
414 };
415 loop2(atom2);
416 };
417 const writeAtomState = (atom2, ...args) => {
418 let isSync = true;
419 const getter = (a) => returnAtomValue(readAtomState(a));
420 const setter = (a, ...args2) => {
421 let r;
422 if (a === atom2) {
423 if (!hasInitialValue(a)) {
424 throw new Error("atom not writable");
425 }
426 const prevAtomState = getAtomState(a);
427 const nextAtomState = setAtomValueOrPromise(a, args2[0]);
428 if (!isEqualAtomValue(prevAtomState, nextAtomState)) {
429 recomputeDependents(a);
430 }
431 } else {
432 r = writeAtomState(a, ...args2);
433 }
434 if (!isSync) {
435 const flushed = flushPending();
436 if ((import_meta.env ? import_meta.env.MODE : void 0) !== "production") {
437 storeListenersRev2.forEach(
438 (l) => l({ type: "async-write", flushed })
439 );
440 }
441 }
442 return r;
443 };
444 const result = atom2.write(getter, setter, ...args);
445 isSync = false;
446 return result;
447 };
448 const writeAtom = (atom2, ...args) => {
449 const result = writeAtomState(atom2, ...args);
450 const flushed = flushPending();
451 if ((import_meta.env ? import_meta.env.MODE : void 0) !== "production") {
452 storeListenersRev2.forEach(
453 (l) => l({ type: "write", flushed })
454 );
455 }
456 return result;
457 };
458 const mountAtom = (atom2, initialDependent, onMountQueue) => {
459 var _a;
460 const queue = onMountQueue || [];
461 (_a = getAtomState(atom2)) == null ? void 0 : _a.d.forEach((_, a) => {
462 const aMounted = mountedMap.get(a);
463 if (aMounted) {
464 aMounted.t.add(atom2);
465 } else {
466 if (a !== atom2) {
467 mountAtom(a, atom2, queue);
468 }
469 }
470 });
471 readAtomState(atom2);
472 const mounted = {
473 t: new Set(initialDependent && [initialDependent]),
474 l: /* @__PURE__ */ new Set()
475 };
476 mountedMap.set(atom2, mounted);
477 if ((import_meta.env ? import_meta.env.MODE : void 0) !== "production") {
478 mountedAtoms.add(atom2);
479 }
480 if (isActuallyWritableAtom(atom2) && atom2.onMount) {
481 const { onMount } = atom2;
482 queue.push(() => {
483 const onUnmount = onMount((...args) => writeAtom(atom2, ...args));
484 if (onUnmount) {
485 mounted.u = onUnmount;
486 }
487 });
488 }
489 if (!onMountQueue) {
490 queue.forEach((f) => f());
491 }
492 return mounted;
493 };
494 const unmountAtom = (atom2) => {
495 var _a;
496 const onUnmount = (_a = mountedMap.get(atom2)) == null ? void 0 : _a.u;
497 if (onUnmount) {
498 onUnmount();
499 }
500 mountedMap.delete(atom2);
501 if ((import_meta.env ? import_meta.env.MODE : void 0) !== "production") {
502 mountedAtoms.delete(atom2);
503 }
504 const atomState = getAtomState(atom2);
505 if (atomState) {
506 if (hasPromiseAtomValue(atomState)) {
507 cancelPromise(atomState.v);
508 }
509 atomState.d.forEach((_, a) => {
510 if (a !== atom2) {
511 const mounted = mountedMap.get(a);
512 if (mounted) {
513 mounted.t.delete(atom2);
514 if (canUnmountAtom(a, mounted)) {
515 unmountAtom(a);
516 }
517 }
518 }
519 });
520 } else if ((import_meta.env ? import_meta.env.MODE : void 0) !== "production") {
521 console.warn("[Bug] could not find atom state to unmount", atom2);
522 }
523 };
524 const mountDependencies = (atom2, atomState, prevDependencies) => {
525 const depSet = new Set(atomState.d.keys());
526 const maybeUnmountAtomSet = /* @__PURE__ */ new Set();
527 prevDependencies == null ? void 0 : prevDependencies.forEach((_, a) => {
528 if (depSet.has(a)) {
529 depSet.delete(a);
530 return;
531 }
532 maybeUnmountAtomSet.add(a);
533 const mounted = mountedMap.get(a);
534 if (mounted) {
535 mounted.t.delete(atom2);
536 }
537 });
538 depSet.forEach((a) => {
539 const mounted = mountedMap.get(a);
540 if (mounted) {
541 mounted.t.add(atom2);
542 } else if (mountedMap.has(atom2)) {
543 mountAtom(a, atom2);
544 }
545 });
546 maybeUnmountAtomSet.forEach((a) => {
547 const mounted = mountedMap.get(a);
548 if (mounted && canUnmountAtom(a, mounted)) {
549 unmountAtom(a);
550 }
551 });
552 };
553 const flushPending = () => {
554 let flushed;
555 if ((import_meta.env ? import_meta.env.MODE : void 0) !== "production") {
556 flushed = /* @__PURE__ */ new Set();
557 }
558 while (pendingMap.size) {
559 const pending = Array.from(pendingMap);
560 pendingMap.clear();
561 pending.forEach(([atom2, prevAtomState]) => {
562 const atomState = getAtomState(atom2);
563 if (atomState) {
564 const mounted = mountedMap.get(atom2);
565 if (mounted && atomState.d !== (prevAtomState == null ? void 0 : prevAtomState.d)) {
566 mountDependencies(atom2, atomState, prevAtomState == null ? void 0 : prevAtomState.d);
567 }
568 if (mounted && !// TODO This seems pretty hacky. Hope to fix it.
569 // Maybe we could `mountDependencies` in `setAtomState`?
570 (!hasPromiseAtomValue(prevAtomState) && (isEqualAtomValue(prevAtomState, atomState) || isEqualAtomError(prevAtomState, atomState)))) {
571 mounted.l.forEach((listener) => listener());
572 if ((import_meta.env ? import_meta.env.MODE : void 0) !== "production") {
573 flushed.add(atom2);
574 }
575 }
576 } else if ((import_meta.env ? import_meta.env.MODE : void 0) !== "production") {
577 console.warn("[Bug] no atom state to flush");
578 }
579 });
580 }
581 if ((import_meta.env ? import_meta.env.MODE : void 0) !== "production") {
582 return flushed;
583 }
584 };
585 const subscribeAtom = (atom2, listener) => {
586 const mounted = addAtom(atom2);
587 const flushed = flushPending();
588 const listeners = mounted.l;
589 listeners.add(listener);
590 if ((import_meta.env ? import_meta.env.MODE : void 0) !== "production") {
591 storeListenersRev2.forEach(
592 (l) => l({ type: "sub", flushed })
593 );
594 }
595 return () => {
596 listeners.delete(listener);
597 delAtom(atom2);
598 if ((import_meta.env ? import_meta.env.MODE : void 0) !== "production") {
599 storeListenersRev2.forEach((l) => l({ type: "unsub" }));
600 }
601 };
602 };
603 if ((import_meta.env ? import_meta.env.MODE : void 0) !== "production") {
604 return {
605 get: readAtom,
606 set: writeAtom,
607 sub: subscribeAtom,
608 // store dev methods (these are tentative and subject to change without notice)
609 dev_subscribe_store: (l, rev) => {
610 if (rev !== 2) {
611 throw new Error("The current StoreListener revision is 2.");
612 }
613 storeListenersRev2.add(l);
614 return () => {
615 storeListenersRev2.delete(l);
616 };
617 },
618 dev_get_mounted_atoms: () => mountedAtoms.values(),
619 dev_get_atom_state: (a) => atomStateMap.get(a),
620 dev_get_mounted: (a) => mountedMap.get(a),
621 dev_restore_atoms: (values) => {
622 for (const [atom2, valueOrPromise] of values) {
623 if (hasInitialValue(atom2)) {
624 setAtomValueOrPromise(atom2, valueOrPromise);
625 recomputeDependents(atom2);
626 }
627 }
628 const flushed = flushPending();
629 storeListenersRev2.forEach(
630 (l) => l({ type: "restore", flushed })
631 );
632 }
633 };
634 }
635 return {
636 get: readAtom,
637 set: writeAtom,
638 sub: subscribeAtom
639 };
640};
641var defaultStore;
642if ((import_meta.env ? import_meta.env.MODE : void 0) !== "production") {
643 if (typeof globalThis.__NUMBER_OF_JOTAI_INSTANCES__ === "number") {
644 ++globalThis.__NUMBER_OF_JOTAI_INSTANCES__;
645 } else {
646 globalThis.__NUMBER_OF_JOTAI_INSTANCES__ = 1;
647 }
648}
649var getDefaultStore = () => {
650 if (!defaultStore) {
651 defaultStore = createStore();
652 }
653 return defaultStore;
654};
655
656// ../../node_modules/jotai/esm/react.mjs
657var import_react = __toESM(require("react"), 1);
658var import_meta2 = {};
659var StoreContext = (0, import_react.createContext)(void 0);
660var useStore = (options) => {
661 const store = (0, import_react.useContext)(StoreContext);
662 return (options == null ? void 0 : options.store) || store || getDefaultStore();
663};
664var isPromiseLike2 = (x) => typeof (x == null ? void 0 : x.then) === "function";
665var use = import_react.default.use || ((promise) => {
666 if (promise.status === "pending") {
667 throw promise;
668 } else if (promise.status === "fulfilled") {
669 return promise.value;
670 } else if (promise.status === "rejected") {
671 throw promise.reason;
672 } else {
673 promise.status = "pending";
674 promise.then(
675 (v) => {
676 promise.status = "fulfilled";
677 promise.value = v;
678 },
679 (e) => {
680 promise.status = "rejected";
681 promise.reason = e;
682 }
683 );
684 throw promise;
685 }
686});
687function useAtomValue(atom2, options) {
688 const store = useStore(options);
689 const [[valueFromReducer, storeFromReducer, atomFromReducer], rerender] = (0, import_react.useReducer)(
690 (prev) => {
691 const nextValue = store.get(atom2);
692 if (Object.is(prev[0], nextValue) && prev[1] === store && prev[2] === atom2) {
693 return prev;
694 }
695 return [nextValue, store, atom2];
696 },
697 void 0,
698 () => [store.get(atom2), store, atom2]
699 );
700 let value = valueFromReducer;
701 if (storeFromReducer !== store || atomFromReducer !== atom2) {
702 rerender();
703 value = store.get(atom2);
704 }
705 const delay = options == null ? void 0 : options.delay;
706 (0, import_react.useEffect)(() => {
707 const unsub = store.sub(atom2, () => {
708 if (typeof delay === "number") {
709 setTimeout(rerender, delay);
710 return;
711 }
712 rerender();
713 });
714 rerender();
715 return unsub;
716 }, [store, atom2, delay]);
717 (0, import_react.useDebugValue)(value);
718 return isPromiseLike2(value) ? use(value) : value;
719}
720function useSetAtom(atom2, options) {
721 const store = useStore(options);
722 const setAtom = (0, import_react.useCallback)(
723 (...args) => {
724 if ((import_meta2.env ? import_meta2.env.MODE : void 0) !== "production" && !("write" in atom2)) {
725 throw new Error("not writable atom");
726 }
727 return store.set(atom2, ...args);
728 },
729 [store, atom2]
730 );
731 return setAtom;
732}
733
734// src/hooks.tsx
735var storyContextAtom = atom(null);
736function useSetStoryContext() {
737 return useSetAtom(storyContextAtom);
738}
739function useStoryContext() {
740 return useAtomValue(storyContextAtom);
741}
742
743// src/components/StoryView/ErrorBoundary.tsx
744var import_react2 = __toESM(require("react"));
745var import_react_native = require("react-native");
746var import_jsx_runtime = require("react/jsx-runtime");
747var ErrorBoundary = class extends import_react2.default.Component {
748 constructor(props) {
749 super(props);
750 this.state = { hasError: false };
751 }
752 static getDerivedStateFromError(_error) {
753 return { hasError: true };
754 }
755 componentDidCatch(error, info) {
756 this.props.onError(error, info.componentStack);
757 }
758 render() {
759 if (this.state.hasError) {
760 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
761 import_react_native.View,
762 {
763 style: {
764 margin: 16,
765 padding: 16,
766 borderColor: "red",
767 borderWidth: 2,
768 alignItems: "center",
769 justifyContent: "center",
770 borderRadius: 4
771 },
772 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_native.Text, { style: { fontWeight: "bold" }, children: "Something went wrong rendering your story" })
773 }
774 );
775 }
776 return this.props.children;
777 }
778};
779
780// src/components/StoryView/StoryView.tsx
781var import_jsx_runtime2 = require("react/jsx-runtime");
782function dismissOnStartResponder() {
783 import_react_native2.Keyboard.dismiss();
784 return false;
785}
786var Text2 = import_react_native_theming.styled.Text(({ theme: theme3 }) => ({
787 color: theme3?.color?.defaultText
788}));
789var StoryView = () => {
790 const context = useStoryContext();
791 const id = context?.id;
792 const theme3 = (0, import_react_native_theming.useTheme)();
793 if (context && context.unboundStoryFn) {
794 const { unboundStoryFn: StoryComponent } = context;
795 return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
796 import_react_native2.View,
797 {
798 style: { flex: 1, backgroundColor: theme3.background?.content },
799 testID: id,
800 onStartShouldSetResponder: dismissOnStartResponder,
801 children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
802 ErrorBoundary,
803 {
804 onError: () => {
805 console.log(`Error rendering story for ${context.title} ${context.name}`);
806 },
807 children: StoryComponent && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(StoryComponent, { ...context })
808 }
809 )
810 },
811 id
812 );
813 }
814 return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_react_native2.View, { style: { flex: 1, padding: 16, alignItems: "center", justifyContent: "center" }, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Text2, { children: "Please open the sidebar and select a story to preview." }) });
815};
816var StoryView_default = import_react3.default.memo(StoryView);
817
818// src/rn-host-detect.js
819function getByRemoteConfig(hostname) {
820 var remoteModuleConfig = window?.__fbBatchedBridgeConfig?.remoteModuleConfig;
821 if (!Array.isArray(remoteModuleConfig) || hostname !== "localhost" && hostname !== "127.0.0.1") {
822 return { hostname, passed: false };
823 }
824 var constants = (remoteModuleConfig.find(getConstants) || [])[1];
825 if (constants) {
826 var serverHost = constants.ServerHost || hostname;
827 return { hostname: serverHost.split(":")[0], passed: true };
828 }
829 return { hostname, passed: false };
830}
831function getConstants(config) {
832 return config && (config[0] === "AndroidConstants" || config[0] === "PlatformConstants");
833}
834function getByRNRequirePolyfill(hostname) {
835 var NativeModules;
836 var PlatformConstants;
837 var AndroidConstants;
838 if (typeof window === "undefined" || !window.__DEV__ || typeof window.require !== "function" || // RN >= 0.56
839 // TODO: Get NativeModules for RN >= 0.56
840 window.require.name === "metroRequire") {
841 return hostname;
842 }
843 NativeModules = window.require("NativeModules");
844 if (!NativeModules || !NativeModules.PlatformConstants && !NativeModules.AndroidConstants) {
845 return hostname;
846 }
847 PlatformConstants = NativeModules.PlatformConstants;
848 AndroidConstants = NativeModules.AndroidConstants;
849 var serverHost = (PlatformConstants ? PlatformConstants.ServerHost : AndroidConstants.ServerHost) || hostname;
850 return serverHost.split(":")[0];
851}
852function getHost(hostname) {
853 if (typeof __fbBatchedBridge !== "object" || hostname !== "localhost" && hostname !== "127.0.0.1") {
854 return hostname;
855 }
856 var result = getByRemoteConfig(hostname);
857 if (result.passed) {
858 return result.hostname;
859 }
860 return getByRNRequirePolyfill(hostname);
861}
862
863// src/View.tsx
864var import_jsx_runtime3 = require("react/jsx-runtime");
865var STORAGE_KEY = "lastOpenedStory";
866var View3 = class {
867 _storyIndex;
868 _setStory = () => {
869 };
870 _forceRerender = () => {
871 };
872 _ready = false;
873 _preview;
874 _asyncStorageStoryId;
875 _webUrl;
876 _storage;
877 _channel;
878 _idToPrepared = {};
879 constructor(preview, channel) {
880 this._preview = preview;
881 this._channel = channel;
882 }
883 _getInitialStory = async ({
884 initialSelection,
885 shouldPersistSelection = true
886 } = {}) => {
887 if (initialSelection) {
888 if (typeof initialSelection === "string") {
889 return { storySpecifier: initialSelection, viewMode: "story" };
890 } else {
891 return {
892 storySpecifier: (0, import_csf.toId)(initialSelection.kind, initialSelection.name),
893 viewMode: "story"
894 };
895 }
896 }
897 if (shouldPersistSelection) {
898 try {
899 let value = this._asyncStorageStoryId;
900 if (!value && this._storage != null) {
901 value = await this._storage.getItem(STORAGE_KEY);
902 this._asyncStorageStoryId = value;
903 }
904 const exists = value && Object.keys(this._storyIndex.entries).includes(value);
905 if (!exists)
906 console.log("Storybook: could not find persisted story");
907 return { storySpecifier: exists ? value : "*", viewMode: "story" };
908 } catch (e) {
909 console.warn("storybook-log: error reading from async storage", e);
910 }
911 }
912 return { storySpecifier: "*", viewMode: "story" };
913 };
914 _getServerChannel = (params = {}) => {
915 const host = getHost(params.host || "localhost");
916 const port = `:${params.port || 7007}`;
917 const query = params.query || "";
918 const websocketType = params.secured ? "wss" : "ws";
919 const url = `${websocketType}://${host}${port}/${query}`;
920 const channel = new import_channels.Channel({
921 transport: new import_channels.WebsocketTransport({
922 url,
923 onError: (e) => {
924 console.log(`WebsocketTransport error ${JSON.stringify(e)}`);
925 }
926 }),
927 async: true
928 });
929 return channel;
930 };
931 createPreparedStoryMapping = async () => {
932 await this._preview.ready().then(
933 () => Promise.all(
934 Object.keys(this._storyIndex.entries).map(async (storyId) => {
935 this._idToPrepared[storyId] = await this._preview.loadStory({ storyId });
936 })
937 )
938 );
939 };
940 getStorybookUI = (params = {}) => {
941 const {
942 shouldPersistSelection = true,
943 onDeviceUI = true,
944 enableWebsockets = false,
945 storage
946 } = params;
947 this._storage = storage;
948 const initialStory = this._getInitialStory(params);
949 if (enableWebsockets) {
950 const channel = this._getServerChannel(params);
951 import_manager_api.addons.setChannel(channel);
952 import_preview_api.addons.setChannel(channel);
953 this._channel = channel;
954 this._preview.channel = channel;
955 this._preview.setupListeners();
956 channel.emit(import_core_events.default.CHANNEL_CREATED);
957 this._preview.ready().then(() => this._preview.onStoryIndexChanged());
958 }
959 import_manager_api.addons.loadAddons({
960 store: () => ({
961 fromId: (id) => {
962 if (!this._ready) {
963 throw new Error("Storybook is not ready yet");
964 }
965 return this._preview.getStoryContext(this._idToPrepared[id]);
966 },
967 getSelection: () => {
968 return this._preview.currentSelection;
969 },
970 _channel: this._channel
971 })
972 });
973 const self = this;
974 return () => {
975 const setContext = useSetStoryContext();
976 const story = useStoryContext();
977 const colorScheme = (0, import_react_native3.useColorScheme)();
978 const [update, forceUpdate] = (0, import_react4.useReducer)((x) => x + 1, 0);
979 const [ready, setReady] = (0, import_react4.useState)(false);
980 const appliedTheme = (0, import_react4.useMemo)(
981 () => (0, import_deepmerge.default)(colorScheme === "dark" ? import_react_native_theming2.darkTheme : import_react_native_theming2.theme, params.theme ?? {}),
982 [colorScheme]
983 );
984 (0, import_react4.useEffect)(() => {
985 this.createPreparedStoryMapping().then(() => {
986 this._ready = true;
987 setReady(true);
988 initialStory.then((st) => {
989 self._preview.selectionStore.selectionSpecifier = st;
990 self._preview.selectSpecifiedStory();
991 });
992 }).catch((e) => console.error(e));
993 self._setStory = (newStory) => {
994 setContext(newStory);
995 if (shouldPersistSelection && !storage) {
996 console.warn(import_dedent.default`Please set storage in getStorybookUI like this:
997 const StorybookUIRoot = view.getStorybookUI({
998 storage: {
999 getItem: AsyncStorage.getItem,
1000 setItem: AsyncStorage.setItem,
1001 },
1002 });
1003 `);
1004 }
1005 if (shouldPersistSelection && !!this._storage) {
1006 this._storage.setItem(STORAGE_KEY, newStory.id).catch((e) => {
1007 console.warn("storybook-log: error writing to async storage", e);
1008 });
1009 }
1010 };
1011 self._forceRerender = () => forceUpdate();
1012 }, []);
1013 const storyHash = (0, import_react4.useMemo)(() => {
1014 if (!ready) {
1015 return {};
1016 }
1017 return (0, import_react_native_ui.transformStoryIndexToStoriesHash)(this._storyIndex, {
1018 docsOptions: { docsMode: false, autodocs: false, defaultName: "" },
1019 filters: {},
1020 status: {},
1021 provider: {
1022 handleAPI: () => ({}),
1023 getConfig: () => ({})
1024 }
1025 });
1026 }, [ready, update]);
1027 if (!ready) {
1028 return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
1029 import_react_native3.View,
1030 {
1031 style: {
1032 ...import_react_native3.StyleSheet.absoluteFillObject,
1033 alignItems: "center",
1034 justifyContent: "center"
1035 },
1036 children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_react_native3.ActivityIndicator, { animating: true, size: "large" })
1037 }
1038 );
1039 }
1040 if (onDeviceUI) {
1041 return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_react_native_theming2.ThemeProvider, { theme: appliedTheme, children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_react_native_safe_area_context.SafeAreaProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_react_native_gesture_handler.GestureHandlerRootView, { style: { flex: 1 }, children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_bottom_sheet.BottomSheetModalProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_react_native_ui.LayoutProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_react_native_ui.Layout, { storyHash, story, children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(StoryView_default, {}) }) }) }) }) }) });
1042 } else {
1043 return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(StoryView_default, {});
1044 }
1045 };
1046 };
1047};
1048
1049// src/Start.tsx
1050var import_jsx_runtime4 = require("react/jsx-runtime");
1051if (import_react_native4.Platform.OS !== "web") {
1052 try {
1053 let params = new URLSearchParams({ test: "1" });
1054 params.get("test");
1055 } catch {
1056 const { setupURLPolyfill } = require("react-native-url-polyfill");
1057 setupURLPolyfill();
1058 }
1059}
1060if (import_react_native4.Platform.OS === "web" && typeof globalThis.setImmediate === "undefined") {
1061 require("setimmediate");
1062}
1063function prepareStories({
1064 storyEntries,
1065 options
1066}) {
1067 let index = {
1068 v: 4,
1069 entries: {}
1070 };
1071 let importMap = {};
1072 const makeTitle = (fileName, specifier, userTitle) => {
1073 const title = (0, import_preview_api2.userOrAutoTitleFromSpecifier)(fileName, specifier, userTitle);
1074 if (title) {
1075 return title.replace("./", "");
1076 } else {
1077 console.log({
1078 fileName,
1079 userTitle,
1080 storyEntries: storyEntries.map((entry) => {
1081 return { ...entry, importPathMatcher: entry.importPathMatcher.source };
1082 }),
1083 title: title ?? ""
1084 });
1085 throw new Error("Could not generate title");
1086 }
1087 };
1088 storyEntries.forEach((specifier) => {
1089 const { req, directory: root } = specifier;
1090 req.keys().forEach((filename) => {
1091 try {
1092 const fileExports = req(filename);
1093 if (!fileExports.default)
1094 return;
1095 const meta = fileExports.default;
1096 Object.keys(fileExports).forEach((key) => {
1097 if (key === "default")
1098 return;
1099 if (!(0, import_csf2.isExportStory)(key, fileExports.default))
1100 return;
1101 const exportValue = fileExports[key];
1102 if (!exportValue)
1103 return;
1104 const name = (0, import_csf2.storyNameFromExport)(key);
1105 const title = makeTitle(filename, specifier, meta.title);
1106 if (title) {
1107 const id = (0, import_csf2.toId)(title, name);
1108 index.entries[id] = {
1109 type: "story",
1110 id,
1111 name,
1112 title,
1113 importPath: `${root}/${filename.substring(2)}`,
1114 // FIXME: use normalize function here
1115 tags: ["story"]
1116 };
1117 const importedStories = req(filename);
1118 const stories = Object.entries(importedStories).reduce(
1119 (carry, [storyKey, story]) => {
1120 if (!(0, import_csf2.isExportStory)(storyKey, fileExports.default))
1121 return carry;
1122 if (story.play && !options?.playFn) {
1123 carry[storyKey] = { ...story, play: void 0 };
1124 } else {
1125 carry[storyKey] = story;
1126 }
1127 return carry;
1128 },
1129 {}
1130 );
1131 importMap[`${root}/${filename.substring(2)}`] = stories;
1132 } else {
1133 console.log(`Unexpected error while loading ${filename}: could not find title`);
1134 }
1135 });
1136 } catch (error) {
1137 const errorString = error.message && error.stack ? `${error.message}
1138 ${error.stack}` : error.toString();
1139 console.error(`Unexpected error while loading ${filename}: ${errorString}`);
1140 }
1141 });
1142 });
1143 return { index, importMap };
1144}
1145var getProjectAnnotations = (view, annotations) => async () => (0, import_preview_api2.composeConfigs)([
1146 {
1147 renderToCanvas: (context) => {
1148 view._setStory(context.storyContext);
1149 },
1150 render: (args, context) => {
1151 const { id, component: Component } = context;
1152 if (!Component) {
1153 throw new Error(
1154 `Unable to render story ${id} as the component annotation is missing from the default export`
1155 );
1156 }
1157 return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Component, { ...args });
1158 }
1159 },
1160 ...annotations
1161]);
1162function start({
1163 annotations,
1164 storyEntries,
1165 options
1166}) {
1167 const { index, importMap } = prepareStories({ storyEntries, options });
1168 const channel = (0, import_channels2.createBrowserChannel)({ page: "preview" });
1169 import_manager_api2.addons.setChannel(channel);
1170 import_preview_api2.addons.setChannel(channel);
1171 const previewView = {
1172 prepareForStory: () => {
1173 return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(import_jsx_runtime4.Fragment, {});
1174 },
1175 prepareForDocs: () => {
1176 },
1177 showErrorDisplay: (e) => {
1178 console.log(e);
1179 },
1180 showDocs: () => {
1181 },
1182 showMain: () => {
1183 },
1184 showNoPreview: () => {
1185 },
1186 showPreparingDocs: () => {
1187 },
1188 showPreparingStory: () => {
1189 },
1190 showStory: () => {
1191 },
1192 showStoryDuringRender: () => {
1193 }
1194 // TODO what happened to this type?
1195 };
1196 const selectionStore = {
1197 selection: null,
1198 selectionSpecifier: null,
1199 setQueryParams: () => {
1200 },
1201 setSelection: (selection) => {
1202 preview.selectionStore.selection = selection;
1203 }
1204 };
1205 const getProjectAnnotationsInitial = async () => (0, import_preview_api2.composeConfigs)([
1206 {
1207 renderToCanvas: (context) => {
1208 view._setStory(context.storyContext);
1209 },
1210 render: (args, context) => {
1211 const { id, component: Component } = context;
1212 if (!Component) {
1213 throw new Error(
1214 `Unable to render story ${id} as the component annotation is missing from the default export`
1215 );
1216 }
1217 return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Component, { ...args });
1218 }
1219 },
1220 ...annotations
1221 ]);
1222 const preview = new import_preview_api2.PreviewWithSelection(
1223 async (importPath) => importMap[importPath],
1224 getProjectAnnotationsInitial,
1225 selectionStore,
1226 previewView
1227 );
1228 const view = new View3(preview, channel);
1229 if (global) {
1230 global.__STORYBOOK_ADDONS_CHANNEL__ = channel;
1231 global.__STORYBOOK_PREVIEW__ = preview;
1232 }
1233 view._storyIndex = index;
1234 preview.getStoryIndexFromServer = async () => view._storyIndex;
1235 return view;
1236}
1237function updateView(viewInstance, annotations, normalizedStories, options) {
1238 const { importMap, index } = prepareStories({ storyEntries: normalizedStories, options });
1239 viewInstance._preview.onStoriesChanged({
1240 importFn: async (importPath) => importMap[importPath]
1241 });
1242 viewInstance._preview.onGetProjectAnnotationsChanged({
1243 getProjectAnnotations: getProjectAnnotations(viewInstance, annotations)
1244 });
1245 viewInstance._storyIndex = index;
1246 viewInstance._preview.onStoryIndexChanged().then(() => {
1247 viewInstance.createPreparedStoryMapping().then(() => viewInstance._forceRerender());
1248 });
1249}
1250// Annotate the CommonJS export names for ESM import in node:
12510 && (module.exports = {
1252 darkTheme,
1253 getProjectAnnotations,
1254 prepareStories,
1255 start,
1256 theme,
1257 updateView
1258});