@teambit/component 0.0.565 → 0.0.569

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/aspect.section.tsx +16 -0
  2. package/component-map/component-map.ts +106 -0
  3. package/component-map/index.ts +1 -0
  4. package/component.ui.runtime.tsx +216 -0
  5. package/dependencies/dependencies.ts +74 -0
  6. package/dependencies/index.ts +1 -0
  7. package/dist/component.js +7 -13
  8. package/dist/component.js.map +1 -1
  9. package/exceptions/could-not-find-latest.ts +8 -0
  10. package/exceptions/host-not-found.ts +14 -0
  11. package/exceptions/index.ts +4 -0
  12. package/exceptions/nothing-to-snap.ts +1 -0
  13. package/host/component-host-model.ts +9 -0
  14. package/host/index.ts +2 -0
  15. package/host/use-component-host.ts +39 -0
  16. package/package-tar/teambit-component-0.0.569.tgz +0 -0
  17. package/package.json +34 -49
  18. package/section/index.ts +1 -0
  19. package/section/section.tsx +8 -0
  20. package/show/extensions.fragment.ts +23 -0
  21. package/show/files.fragment.ts +24 -0
  22. package/show/id.fragment.ts +20 -0
  23. package/show/index.ts +8 -0
  24. package/show/main-file.fragment.ts +13 -0
  25. package/show/name.fragment.ts +13 -0
  26. package/show/scope.fragment.ts +15 -0
  27. package/show/show-fragment.ts +44 -0
  28. package/show/show.cmd.ts +85 -0
  29. package/snap/author.ts +19 -0
  30. package/snap/index.ts +2 -0
  31. package/snap/snap.ts +63 -0
  32. package/tag/index.ts +1 -0
  33. package/tag/tag.ts +37 -0
  34. package/types/asset.d.ts +29 -0
  35. package/types/style.d.ts +42 -0
  36. package/ui/aspect-page/aspect-page.tsx +64 -0
  37. package/ui/aspect-page/index.ts +1 -0
  38. package/ui/component-error/component-error.tsx +22 -0
  39. package/ui/component-error/index.ts +1 -0
  40. package/ui/component-model/component-model.ts +169 -0
  41. package/ui/component-model/index.ts +1 -0
  42. package/ui/component.tsx +48 -0
  43. package/ui/context/component-context.ts +5 -0
  44. package/ui/context/component-provider.tsx +20 -0
  45. package/ui/context/index.ts +2 -0
  46. package/ui/index.ts +3 -0
  47. package/ui/menu/index.ts +2 -0
  48. package/ui/menu/menu-nav.tsx +37 -0
  49. package/ui/menu/menu.tsx +94 -0
  50. package/ui/menu/nav-plugin.tsx +9 -0
  51. package/ui/top-bar-nav/index.ts +1 -0
  52. package/ui/top-bar-nav/top-bar-nav.tsx +26 -0
  53. package/ui/use-component-query.ts +195 -0
  54. package/ui/use-component.tsx +34 -0
@@ -0,0 +1,16 @@
1
+ import React from 'react';
2
+ import { MenuWidgetIcon } from '@teambit/ui-foundation.ui.menu-widget-icon';
3
+ import { Section } from './section';
4
+ import { AspectPage } from './ui/aspect-page';
5
+
6
+ export class AspectSection implements Section {
7
+ route = {
8
+ path: '~aspect',
9
+ children: <AspectPage />,
10
+ };
11
+ navigationLink = {
12
+ href: '~aspect',
13
+ children: <MenuWidgetIcon icon="configuration" tooltipContent="Configuration" />,
14
+ };
15
+ order = 50;
16
+ }
@@ -0,0 +1,106 @@
1
+ import { ComponentID } from '@teambit/component-id';
2
+ import { Component } from '../component';
3
+
4
+ /**
5
+ * allows to index components -> values.
6
+ */
7
+ export class ComponentMap<T> {
8
+ constructor(readonly hashMap: Map<string, [Component, T]>) {}
9
+
10
+ /**
11
+ * @deprecated please use `get` instead
12
+ */
13
+ byComponent(component: Component) {
14
+ return this.hashMap.get(component.id.toString());
15
+ }
16
+
17
+ get components() {
18
+ return this.toArray().map(([component]) => component);
19
+ }
20
+
21
+ /**
22
+ * get a value for a component.
23
+ */
24
+ get(component: Component) {
25
+ return this.hashMap.get(component.id.toString());
26
+ }
27
+
28
+ /**
29
+ * get a value by the component-id
30
+ */
31
+ getValueByComponentId(componentId: ComponentID): T | null {
32
+ const tuple = this.hashMap.get(componentId.toString());
33
+ if (!tuple) return null;
34
+ return tuple[1];
35
+ }
36
+
37
+ /**
38
+ * returns an array.
39
+ */
40
+ toArray() {
41
+ return Array.from(this.hashMap.values());
42
+ }
43
+
44
+ /**
45
+ * map entries and return a new component map.
46
+ */
47
+ map<NewType>(predicate: (value: T, component: Component) => NewType): ComponentMap<NewType> {
48
+ const tuples: [string, [Component, NewType]][] = this.toArray().map(([component, value]) => {
49
+ const newValue = predicate(value, component);
50
+ return [component.id.toString(), [component, newValue]];
51
+ });
52
+
53
+ return new ComponentMap(new Map(tuples));
54
+ }
55
+ /**
56
+ * flatten values of all components into a single array.
57
+ */
58
+ flattenValue(): T[] {
59
+ return this.toArray().reduce((acc: T[], [, value]) => {
60
+ acc = acc.concat(value);
61
+ return acc;
62
+ }, []);
63
+ }
64
+
65
+ /**
66
+ * filter all components with empty values and return a new map.
67
+ */
68
+ filter(predicate: (value: T) => boolean): ComponentMap<T> {
69
+ const tuples = this.toArray().filter(([, value]) => {
70
+ return predicate(value);
71
+ });
72
+
73
+ const asMap: [string, [Component, T]][] = tuples.map(([component, value]) => {
74
+ return [component.id.toString(), [component, value]];
75
+ });
76
+
77
+ return new ComponentMap(new Map(asMap));
78
+ }
79
+
80
+ /**
81
+ * get all component ids.
82
+ */
83
+ keys() {
84
+ return this.hashMap.keys();
85
+ }
86
+
87
+ static create<U>(rawMap: [Component, U][]) {
88
+ const newMap: [string, [Component, U]][] = rawMap.map(([component, data]) => {
89
+ return [component.id.toString(), [component, data]];
90
+ });
91
+ return new ComponentMap(new Map(newMap));
92
+ }
93
+
94
+ /**
95
+ * create a component map from components and a value predicate.
96
+ * @param components components to zip into the map.
97
+ * @param predicate predicate for returning desired value.
98
+ */
99
+ static as<U>(components: Component[], predicate: (component: Component) => U): ComponentMap<U> {
100
+ const tuples: [string, [Component, U]][] = components.map((component) => {
101
+ return [component.id.toString(), [component, predicate(component)]];
102
+ });
103
+
104
+ return new ComponentMap(new Map(tuples));
105
+ }
106
+ }
@@ -0,0 +1 @@
1
+ export { ComponentMap } from './component-map';
@@ -0,0 +1,216 @@
1
+ import PubsubAspect, { PubsubUI, BitBaseEvent } from '@teambit/pubsub';
2
+ import PreviewAspect, { ClickInsideAnIframeEvent } from '@teambit/preview';
3
+ import { MenuItemSlot, MenuItem } from '@teambit/ui-foundation.ui.main-dropdown';
4
+ import { Slot } from '@teambit/harmony';
5
+ import { NavigationSlot, RouteSlot } from '@teambit/ui-foundation.ui.react-router.slot-router';
6
+ import { NavLinkProps } from '@teambit/base-ui.routing.nav-link';
7
+ import { UIRuntime } from '@teambit/ui';
8
+ import { isBrowser } from '@teambit/ui-foundation.ui.is-browser';
9
+ import React from 'react';
10
+ import { RouteProps } from 'react-router-dom';
11
+ import CommandBarAspect, { CommandBarUI, CommandEntry } from '@teambit/command-bar';
12
+ import copy from 'copy-to-clipboard';
13
+ import { ComponentAspect } from './component.aspect';
14
+ import { Component, ComponentPageElement, ComponentPageSlot } from './ui/component';
15
+ import { Menu, NavPlugin, OrderedNavigationSlot } from './ui/menu';
16
+ import { AspectSection } from './aspect.section';
17
+ import { ComponentModel } from './ui';
18
+
19
+ export type Server = {
20
+ env: string;
21
+ url: string;
22
+ };
23
+
24
+ export type ComponentMeta = {
25
+ id: string;
26
+ };
27
+
28
+ export const componentIdUrlRegex = '[\\w\\/-]*[\\w-]';
29
+
30
+ export class ComponentUI {
31
+ readonly routePath = `/:componentId(${componentIdUrlRegex})`;
32
+
33
+ constructor(
34
+ /**
35
+ * Pubsub aspects
36
+ */
37
+ private pubsub: PubsubUI,
38
+
39
+ private routeSlot: RouteSlot,
40
+
41
+ private navSlot: OrderedNavigationSlot,
42
+
43
+ /**
44
+ * slot for registering a new widget to the menu.
45
+ */
46
+ private widgetSlot: OrderedNavigationSlot,
47
+
48
+ private menuItemSlot: MenuItemSlot,
49
+
50
+ private pageItemSlot: ComponentPageSlot,
51
+
52
+ private commandBarUI: CommandBarUI
53
+ ) {
54
+ if (isBrowser) this.registerPubSub();
55
+ }
56
+
57
+ /**
58
+ * the current visible component
59
+ */
60
+ private activeComponent?: ComponentModel;
61
+
62
+ private copyNpmId = () => {
63
+ const packageName = this.activeComponent?.packageName;
64
+ if (packageName) {
65
+ const version = this.activeComponent?.id.version;
66
+ const versionString = version ? `@${version}` : '';
67
+ copy(`${packageName}${versionString}`);
68
+ }
69
+ };
70
+
71
+ /**
72
+ * key bindings used by component aspect
73
+ */
74
+ private keyBindings: CommandEntry[] = [
75
+ {
76
+ id: 'component.copyBitId', // TODO - extract to a component!
77
+ handler: () => {
78
+ copy(this.activeComponent?.id.toString() || '');
79
+ },
80
+ displayName: 'Copy component ID',
81
+ keybinding: '.',
82
+ },
83
+ {
84
+ id: 'component.copyNpmId', // TODO - extract to a component!
85
+ handler: this.copyNpmId,
86
+ displayName: 'Copy component package name',
87
+ keybinding: ',',
88
+ },
89
+ ];
90
+
91
+ private menuItems: MenuItem[] = [
92
+ {
93
+ category: 'general',
94
+ title: 'Open command bar',
95
+ keyChar: 'mod+k',
96
+ handler: () => this.commandBarUI?.run('command-bar.open'),
97
+ },
98
+ {
99
+ category: 'general',
100
+ title: 'Toggle component list',
101
+ keyChar: 'alt+s',
102
+ handler: () => this.commandBarUI?.run('sidebar.toggle'),
103
+ },
104
+ {
105
+ category: 'workflow',
106
+ title: 'Copy component ID',
107
+ keyChar: '.',
108
+ handler: () => this.commandBarUI?.run('component.copyBitId'),
109
+ },
110
+ {
111
+ category: 'workflow',
112
+ title: 'Copy component package name',
113
+ keyChar: ',',
114
+ handler: () => this.commandBarUI?.run('component.copyNpmId'),
115
+ },
116
+ ];
117
+
118
+ registerPubSub() {
119
+ this.pubsub.sub(PreviewAspect.id, (be: BitBaseEvent<any>) => {
120
+ if (be.type === ClickInsideAnIframeEvent.TYPE) {
121
+ const event = new MouseEvent('mousedown', {
122
+ view: window,
123
+ bubbles: true,
124
+ cancelable: true,
125
+ });
126
+
127
+ const body = document.body;
128
+ body?.dispatchEvent(event);
129
+ }
130
+ });
131
+ }
132
+
133
+ handleComponentChange = (activeComponent?: ComponentModel) => {
134
+ this.activeComponent = activeComponent;
135
+ };
136
+
137
+ getComponentUI(host: string) {
138
+ return (
139
+ <Component
140
+ routeSlot={this.routeSlot}
141
+ containerSlot={this.pageItemSlot}
142
+ onComponentChange={this.handleComponentChange}
143
+ host={host}
144
+ />
145
+ );
146
+ }
147
+
148
+ getMenu(host: string) {
149
+ return (
150
+ <Menu navigationSlot={this.navSlot} widgetSlot={this.widgetSlot} host={host} menuItemSlot={this.menuItemSlot} />
151
+ );
152
+ }
153
+
154
+ registerRoute(route: RouteProps) {
155
+ this.routeSlot.register(route);
156
+ return this;
157
+ }
158
+
159
+ registerNavigation(nav: NavLinkProps, order?: number) {
160
+ this.navSlot.register({
161
+ props: nav,
162
+ order,
163
+ });
164
+ }
165
+
166
+ registerWidget(widget: NavLinkProps, order?: number) {
167
+ this.widgetSlot.register({ props: widget, order });
168
+ }
169
+
170
+ registerMenuItem = (menuItems: MenuItem[]) => {
171
+ this.menuItemSlot.register(menuItems);
172
+ };
173
+
174
+ registerPageItem = (...items: ComponentPageElement[]) => {
175
+ this.pageItemSlot.register(items);
176
+ };
177
+
178
+ static dependencies = [PubsubAspect, CommandBarAspect];
179
+
180
+ static runtime = UIRuntime;
181
+
182
+ static slots = [
183
+ Slot.withType<RouteProps>(),
184
+ Slot.withType<NavPlugin>(),
185
+ Slot.withType<NavigationSlot>(),
186
+ Slot.withType<MenuItemSlot>(),
187
+ Slot.withType<ComponentPageSlot>(),
188
+ ];
189
+
190
+ static async provider(
191
+ [pubsub, commandBarUI]: [PubsubUI, CommandBarUI],
192
+ config,
193
+ [routeSlot, navSlot, widgetSlot, menuItemSlot, pageSlot]: [
194
+ RouteSlot,
195
+ OrderedNavigationSlot,
196
+ OrderedNavigationSlot,
197
+ MenuItemSlot,
198
+ ComponentPageSlot
199
+ ]
200
+ ) {
201
+ // TODO: refactor ComponentHost to a separate extension (including sidebar, host, graphql, etc.)
202
+ // TODO: add contextual hook for ComponentHost @uri/@oded
203
+ const componentUI = new ComponentUI(pubsub, routeSlot, navSlot, widgetSlot, menuItemSlot, pageSlot, commandBarUI);
204
+ const section = new AspectSection();
205
+
206
+ componentUI.commandBarUI.addCommand(...componentUI.keyBindings);
207
+ componentUI.registerMenuItem(componentUI.menuItems);
208
+ componentUI.registerRoute(section.route);
209
+ componentUI.registerWidget(section.navigationLink, section.order);
210
+ return componentUI;
211
+ }
212
+ }
213
+
214
+ export default ComponentUI;
215
+
216
+ ComponentAspect.addRuntime(ComponentUI);
@@ -0,0 +1,74 @@
1
+ /* eslint-disable max-classes-per-file */
2
+ import { BitError } from '@teambit/bit-error';
3
+ import { BitId } from '@teambit/legacy-bit-id';
4
+
5
+ const DEV_ENV = 'development';
6
+ const RUNTIME_ENV = 'runtime';
7
+
8
+ // type Environment = DEV_ENV | RUNTIME_ENV;
9
+ type Environment = 'development' | 'runtime';
10
+ // type WrappingMethod = 'component' | 'package';
11
+
12
+ export class DependencyId extends BitId {}
13
+
14
+ export class Dependency {
15
+ constructor(public id: DependencyId) {}
16
+ }
17
+
18
+ export class PackageDependency extends Dependency {}
19
+
20
+ export class ComponentDependency extends Dependency {}
21
+
22
+ export class DependencyList extends Array<Dependency> {
23
+ /**
24
+ * Get only package dependencies
25
+ *
26
+ * @readonly
27
+ * @memberof DependencyList
28
+ */
29
+ get packages(): PackageDependency[] {
30
+ return this.filter((dep) => dep instanceof PackageDependency);
31
+ }
32
+
33
+ get components(): ComponentDependency[] {
34
+ return this.filter((dep) => dep instanceof ComponentDependency);
35
+ }
36
+
37
+ static fromArray(dependencies: Dependency[]): DependencyList {
38
+ return new DependencyList(...dependencies);
39
+ }
40
+ }
41
+
42
+ export class Dependencies {
43
+ constructor(public runtime: DependencyList, public dev: DependencyList, public peer: DependencyList) {}
44
+
45
+ private getByEnvironment(env: Environment): DependencyList {
46
+ if (env === DEV_ENV) {
47
+ return DependencyList.fromArray(this.runtime.concat(this.dev).concat(this.peer));
48
+ }
49
+ if (env === RUNTIME_ENV) {
50
+ return DependencyList.fromArray(this.runtime.concat(this.peer));
51
+ }
52
+ throw new BitError(`env ${env} is not supported`);
53
+ }
54
+
55
+ /**
56
+ * Get dependencies needed for development environnement such as runtime, dev and peer
57
+ *
58
+ * @returns {DependencyList}
59
+ * @memberof Dependencies
60
+ */
61
+ computeDev(): DependencyList {
62
+ return this.getByEnvironment(DEV_ENV);
63
+ }
64
+
65
+ /**
66
+ * Get dependencies needed for runtime environnement such as runtime and peer
67
+ *
68
+ * @returns {DependencyList}
69
+ * @memberof Dependencies
70
+ */
71
+ computeRuntime(): DependencyList {
72
+ return this.getByEnvironment(RUNTIME_ENV);
73
+ }
74
+ }
@@ -0,0 +1 @@
1
+ export { Dependencies } from './dependencies';
package/dist/component.js CHANGED
@@ -1,11 +1,11 @@
1
1
  "use strict";
2
2
 
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
-
5
3
  require("core-js/modules/es.symbol.description.js");
6
4
 
7
5
  require("core-js/modules/es.symbol.async-iterator.js");
8
6
 
7
+ require("core-js/modules/es.array.iterator.js");
8
+
9
9
  require("core-js/modules/es.promise.js");
10
10
 
11
11
  require("core-js/modules/es.regexp.exec.js");
@@ -15,16 +15,6 @@ Object.defineProperty(exports, "__esModule", {
15
15
  });
16
16
  exports.Component = void 0;
17
17
 
18
- function _asyncIterator2() {
19
- const data = _interopRequireDefault(require("@babel/runtime/helpers/asyncIterator"));
20
-
21
- _asyncIterator2 = function () {
22
- return data;
23
- };
24
-
25
- return data;
26
- }
27
-
28
18
  function _toolboxString() {
29
19
  const data = require("@teambit/toolbox.string.capitalize");
30
20
 
@@ -65,6 +55,10 @@ function _exceptions() {
65
55
  return data;
66
56
  }
67
57
 
58
+ function _asyncIterator(iterable) { var method, async, sync, retry = 2; if (typeof Symbol !== "undefined") { async = Symbol.asyncIterator; sync = Symbol.iterator; } while (retry--) { if (async && (method = iterable[async]) != null) { return method.call(iterable); } if (sync && (method = iterable[sync]) != null) { return new AsyncFromSyncIterator(method.call(iterable)); } async = "@@asyncIterator"; sync = "@@iterator"; } throw new TypeError("Object is not async iterable"); }
59
+
60
+ function AsyncFromSyncIterator(s) { AsyncFromSyncIterator = function (s) { this.s = s; this.n = s.next; }; AsyncFromSyncIterator.prototype = { s: null, n: null, next: function () { return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments)); }, return: function (value) { var ret = this.s.return; if (ret === undefined) { return Promise.resolve({ value: value, done: true }); } return AsyncFromSyncIteratorContinuation(ret.apply(this.s, arguments)); }, throw: function (value) { var thr = this.s.return; if (thr === undefined) return Promise.reject(value); return AsyncFromSyncIteratorContinuation(thr.apply(this.s, arguments)); } }; function AsyncFromSyncIteratorContinuation(r) { if (Object(r) !== r) { return Promise.reject(new TypeError(r + " is not an object.")); } var done = r.done; return Promise.resolve(r.value).then(function (value) { return { value: value, done: done }; }); } return new AsyncFromSyncIterator(s); }
61
+
68
62
  /**
69
63
  * in-memory representation of a component.
70
64
  */
@@ -312,7 +306,7 @@ class Component {
312
306
  var _iteratorError;
313
307
 
314
308
  try {
315
- for (var _iterator = (0, _asyncIterator2().default)(iterable), _step; _iteratorAbruptCompletion = !(_step = await _iterator.next()).done; _iteratorAbruptCompletion = false) {
309
+ for (var _iterator = _asyncIterator(iterable), _step; _iteratorAbruptCompletion = !(_step = await _iterator.next()).done; _iteratorAbruptCompletion = false) {
316
310
  const snap = _step.value;
317
311
  snaps.push(snap);
318
312
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["component.ts"],"names":["Component","constructor","id","head","_state","tags","TagMap","factory","state","config","filesystem","buildStatus","_consumer","headTag","undefined","byHash","hash","latest","getLatest","err","CouldNotFindLatest","toString","stringify","JSON","displayName","tokens","name","split","map","token","join","tag","version","isModified","Promise","resolve","isOutdated","latestTag","byVersion","isNew","loadState","snapId","getState","loadSnap","snapToGet","BitError","getSnap","snapsIterable","options","snapToStart","nextSnaps","done","iterator","next","value","currSnapId","shift","snap","parents","length","firstParentOnly","push","concat","stopFn","Symbol","asyncIterator","getClosestTag","snapToStartFrom","tagsHashMap","getHashMap","has","iterable","snaps","hashOfLastSnap","get","checkout","write","path","fs","equals","component"],"mappings":";;;;;;;;;;;;;;;;;;;;;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AAAzB,KAApC,CAAjB;AACA,UAAMS,KAAa,GAAG,EAAtB;AATsE;AAAA;;AAAA;;AAAA;AAUtE,0DAAyBD,QAAzB,iHAAmC;AAAA,cAAlBd,IAAkB;AACjCe,QAAAA,KAAK,CAACX,IAAN,CAAWJ,IAAX;AACD;AAZqE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAatE,QAAIe,KAAK,CAACb,MAAV,EAAkB;AAChB,YAAMc,cAAc,GAAGD,KAAK,CAACA,KAAK,CAACb,MAAN,GAAe,CAAhB,CAAL,CAAwB3C,IAA/C;AACA,aAAOoD,WAAW,CAACM,GAAZ,CAAgBD,cAAhB,CAAP;AACD;;AACD,WAAO3D,SAAP;AACD;AAED;AACF;AACA;AACE;;;AACA6D,EAAAA,QAAQ,CAAC3C,OAAD,EAAkB,CAAE;AAE5B;AACF;AACA;AACE;;AAEA;AACF;AACA;AACE;;AAEA;AACF;AACA;AACA;AACA;AACE;;;AACA4C,EAAAA,KAAK,CAACC,IAAD,EAAeC,EAAf,EAA2B,CAAE;AAElC;AACF;AACA;AACA;AACA;AACA;AACA;AACE;;;AACAC,EAAAA,MAAM,CAACC,SAAD,EAAgC;AACpC,WAAOA,SAAS,CAAC9E,EAAV,CAAamB,QAAb,OAA4B,KAAKnB,EAAL,CAAQmB,QAAR,EAAnC;AACD;;AAvPoB","sourcesContent":["import { AnyFS } from '@teambit/any-fs';\nimport { capitalize } from '@teambit/toolbox.string.capitalize';\nimport { SemVer } from 'semver';\nimport { ComponentID } from '@teambit/component-id';\nimport { BitError } from '@teambit/bit-error';\nimport { BuildStatus } from '@teambit/legacy/dist/constants';\n\nimport { ComponentFactory } from './component-factory';\nimport ComponentFS from './component-fs';\n// import { NothingToSnap } from './exceptions';\nimport ComponentConfig from './config';\n// eslint-disable-next-line import/no-cycle\nimport { Snap } from './snap';\nimport { State } from './state';\nimport { TagMap } from './tag-map';\nimport { Tag } from './tag';\nimport { CouldNotFindLatest } from './exceptions';\n// import { Author } from './types';\n\ntype SnapsIterableOpts = {\n firstParentOnly?: boolean;\n stopFn?: (snap: Snap) => Promise<boolean>;\n};\n\nexport type InvalidComponent = { id: ComponentID; err: Error };\n\n/**\n * in-memory representation of a component.\n */\nexport class Component {\n constructor(\n /**\n * component ID represented by the `ComponentId` type.\n */\n readonly id: ComponentID,\n\n /**\n * head version of the component. can be `null` for new components.\n */\n readonly head: Snap | null = null,\n\n /**\n * state of the component.\n */\n private _state: State,\n\n /**\n * tags of the component.\n */\n readonly tags: TagMap = new TagMap(),\n\n /**\n * the component factory\n */\n private factory: ComponentFactory\n ) {}\n\n get state(): State {\n return this._state;\n }\n\n set state(state: State) {\n this._state = state;\n }\n\n /**\n * component configuration which is later generated to a component `package.json` and `bit.json`.\n */\n get config(): ComponentConfig {\n return this.state.config;\n }\n\n /**\n * in-memory representation of the component current filesystem.\n */\n get filesystem(): ComponentFS {\n return this.state.filesystem;\n }\n\n /**\n * build status of the component\n */\n get buildStatus(): BuildStatus {\n return this._state._consumer.buildStatus;\n }\n\n get headTag() {\n if (!this.head) return undefined;\n return this.tags.byHash(this.head.hash);\n }\n\n get latest(): string | undefined {\n if (!this.head) return undefined;\n try {\n return this.tags.getLatest();\n } catch (err: any) {\n if (err instanceof CouldNotFindLatest) {\n return this.head.toString();\n }\n throw err;\n }\n }\n\n stringify(): string {\n return JSON.stringify({\n id: this.id,\n head: this.head,\n });\n }\n\n /**\n * record component changes in the `Scope`.\n */\n // snap(author: Author, message = '') {\n // if (!this.isModified()) throw new NothingToSnap();\n // const snap = new Snap(this, author, message);\n\n // return new Component(this.id, snap, snap.state);\n // }\n\n /**\n * display name of the component.\n */\n get displayName() {\n const tokens = this.id.name.split('-').map((token) => capitalize(token));\n return tokens.join(' ');\n }\n\n /**\n * tag a component `Snap` with a semantic version. we follow SemVer specs as defined [here](https://semver.org/)).\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n tag(version: SemVer) {\n // const snap = this.snap();\n // const tag = new Tag(version, snap);\n // this.tags.set(tag);\n }\n\n /**\n * determines whether this component is modified in the workspace.\n */\n isModified(): Promise<boolean> {\n if (!this.head) return Promise.resolve(true);\n return Promise.resolve(this.state.isModified);\n // return Promise.resolve(this.state.hash !== this.head.hash);\n }\n\n /**\n * is component isOutdated\n */\n isOutdated(): boolean {\n if (!this.latest) return false;\n const latestTag = this.tags.byVersion(this.latest);\n if (!latestTag) return false;\n if (this.head?.hash !== latestTag?.hash) return true;\n return false;\n }\n\n /**\n * determines whether this component is new.\n */\n isNew(): Promise<boolean> {\n return Promise.resolve(this.head === null);\n }\n\n // TODO: @david after snap we need to make sure to refactor here.\n loadState(snapId: string): Promise<State> {\n return this.factory.getState(this.id, snapId);\n }\n\n loadSnap(snapId?: string): Promise<Snap> {\n const snapToGet = snapId || this.head?.hash;\n if (!snapToGet) {\n throw new BitError('could not load snap for new components');\n }\n return this.factory.getSnap(this.id, snapToGet);\n }\n\n /**\n * Get iterable which iterate over snap parents lazily\n * @param snapId\n * @param options\n */\n snapsIterable(snapId?: string, options: SnapsIterableOpts = {}): AsyncIterable<Snap> {\n const snapToStart = snapId || this.head?.hash;\n let nextSnaps = [snapToStart];\n let done;\n if (!snapToStart) {\n done = true;\n }\n\n const iterator: AsyncIterator<Snap> = {\n next: async () => {\n if (done) {\n return { value: undefined, done };\n }\n const currSnapId = nextSnaps.shift();\n const snap = await this.loadSnap(currSnapId);\n if (snap.parents && snap.parents.length) {\n if (options.firstParentOnly) {\n nextSnaps.push(snap.parents[0]);\n } else {\n nextSnaps = nextSnaps.concat(snap.parents);\n }\n }\n if (!nextSnaps.length) {\n done = true;\n } else if (options.stopFn) {\n done = await options.stopFn(snap);\n }\n return { value: snap, done: undefined };\n },\n };\n return {\n [Symbol.asyncIterator]: () => iterator,\n };\n }\n\n /**\n * traverse recursively from the provided snap (or head) upwards until it finds a tag\n * @param snapToStartFrom\n */\n async getClosestTag(snapToStartFrom?: string): Promise<Tag | undefined> {\n const tagsHashMap = this.tags.getHashMap();\n const stopFn = async (snap: Snap) => {\n if (tagsHashMap.has(snap.hash)) {\n return true;\n }\n return false;\n };\n const iterable = this.snapsIterable(snapToStartFrom, { firstParentOnly: true, stopFn });\n const snaps: Snap[] = [];\n for await (const snap of iterable) {\n snaps.push(snap);\n }\n if (snaps.length) {\n const hashOfLastSnap = snaps[snaps.length - 1].hash;\n return tagsHashMap.get(hashOfLastSnap);\n }\n return undefined;\n }\n\n /**\n * checkout the component to a different version in its working tree.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n checkout(version: SemVer) {}\n\n /**\n * examine difference between two components.\n */\n // diff(other: Component): Difference {}\n\n /**\n * merge two different components\n */\n // merge(other: Component): Component {}\n\n /**\n * write a component to a given file system.\n * @param path root path to write the component\n * @param fs instance of any fs to use.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n write(path: string, fs?: AnyFS) {}\n\n /**\n *\n * Check if 2 components are equal\n * @param {Component} component\n * @returns {boolean}\n * @memberof Component\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n equals(component: Component): boolean {\n return component.id.toString() === this.id.toString();\n }\n}\n"]}
1
+ {"version":3,"sources":["component.ts"],"names":["Component","constructor","id","head","_state","tags","TagMap","factory","state","config","filesystem","buildStatus","_consumer","headTag","undefined","byHash","hash","latest","getLatest","err","CouldNotFindLatest","toString","stringify","JSON","displayName","tokens","name","split","map","token","join","tag","version","isModified","Promise","resolve","isOutdated","latestTag","byVersion","isNew","loadState","snapId","getState","loadSnap","snapToGet","BitError","getSnap","snapsIterable","options","snapToStart","nextSnaps","done","iterator","next","value","currSnapId","shift","snap","parents","length","firstParentOnly","push","concat","stopFn","Symbol","asyncIterator","getClosestTag","snapToStartFrom","tagsHashMap","getHashMap","has","iterable","snaps","hashOfLastSnap","get","checkout","write","path","fs","equals","component"],"mappings":";;;;;;;;;;;;;;;;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAGA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AATsE;AAAA;;AAAA;;AAAA;AAUtE,0CAAyBD,QAAzB,iHAAmC;AAAA,cAAlBd,IAAkB;AACjCe,QAAAA,KAAK,CAACX,IAAN,CAAWJ,IAAX;AACD;AAZqE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAatE,QAAIe,KAAK,CAACb,MAAV,EAAkB;AAChB,YAAMc,cAAc,GAAGD,KAAK,CAACA,KAAK,CAACb,MAAN,GAAe,CAAhB,CAAL,CAAwB3C,IAA/C;AACA,aAAOoD,WAAW,CAACM,GAAZ,CAAgBD,cAAhB,CAAP;AACD;;AACD,WAAO3D,SAAP;AACD;AAED;AACF;AACA;AACE;;;AACA6D,EAAAA,QAAQ,CAAC3C,OAAD,EAAkB,CAAE;AAE5B;AACF;AACA;AACE;;AAEA;AACF;AACA;AACE;;AAEA;AACF;AACA;AACA;AACA;AACE;;;AACA4C,EAAAA,KAAK,CAACC,IAAD,EAAeC,EAAf,EAA2B,CAAE;AAElC;AACF;AACA;AACA;AACA;AACA;AACA;AACE;;;AACAC,EAAAA,MAAM,CAACC,SAAD,EAAgC;AACpC,WAAOA,SAAS,CAAC9E,EAAV,CAAamB,QAAb,OAA4B,KAAKnB,EAAL,CAAQmB,QAAR,EAAnC;AACD;;AAvPoB","sourcesContent":["import { AnyFS } from '@teambit/any-fs';\nimport { capitalize } from '@teambit/toolbox.string.capitalize';\nimport { SemVer } from 'semver';\nimport { ComponentID } from '@teambit/component-id';\nimport { BitError } from '@teambit/bit-error';\nimport { BuildStatus } from '@teambit/legacy/dist/constants';\n\nimport { ComponentFactory } from './component-factory';\nimport ComponentFS from './component-fs';\n// import { NothingToSnap } from './exceptions';\nimport ComponentConfig from './config';\n// eslint-disable-next-line import/no-cycle\nimport { Snap } from './snap';\nimport { State } from './state';\nimport { TagMap } from './tag-map';\nimport { Tag } from './tag';\nimport { CouldNotFindLatest } from './exceptions';\n// import { Author } from './types';\n\ntype SnapsIterableOpts = {\n firstParentOnly?: boolean;\n stopFn?: (snap: Snap) => Promise<boolean>;\n};\n\nexport type InvalidComponent = { id: ComponentID; err: Error };\n\n/**\n * in-memory representation of a component.\n */\nexport class Component {\n constructor(\n /**\n * component ID represented by the `ComponentId` type.\n */\n readonly id: ComponentID,\n\n /**\n * head version of the component. can be `null` for new components.\n */\n readonly head: Snap | null = null,\n\n /**\n * state of the component.\n */\n private _state: State,\n\n /**\n * tags of the component.\n */\n readonly tags: TagMap = new TagMap(),\n\n /**\n * the component factory\n */\n private factory: ComponentFactory\n ) {}\n\n get state(): State {\n return this._state;\n }\n\n set state(state: State) {\n this._state = state;\n }\n\n /**\n * component configuration which is later generated to a component `package.json` and `bit.json`.\n */\n get config(): ComponentConfig {\n return this.state.config;\n }\n\n /**\n * in-memory representation of the component current filesystem.\n */\n get filesystem(): ComponentFS {\n return this.state.filesystem;\n }\n\n /**\n * build status of the component\n */\n get buildStatus(): BuildStatus {\n return this._state._consumer.buildStatus;\n }\n\n get headTag() {\n if (!this.head) return undefined;\n return this.tags.byHash(this.head.hash);\n }\n\n get latest(): string | undefined {\n if (!this.head) return undefined;\n try {\n return this.tags.getLatest();\n } catch (err: any) {\n if (err instanceof CouldNotFindLatest) {\n return this.head.toString();\n }\n throw err;\n }\n }\n\n stringify(): string {\n return JSON.stringify({\n id: this.id,\n head: this.head,\n });\n }\n\n /**\n * record component changes in the `Scope`.\n */\n // snap(author: Author, message = '') {\n // if (!this.isModified()) throw new NothingToSnap();\n // const snap = new Snap(this, author, message);\n\n // return new Component(this.id, snap, snap.state);\n // }\n\n /**\n * display name of the component.\n */\n get displayName() {\n const tokens = this.id.name.split('-').map((token) => capitalize(token));\n return tokens.join(' ');\n }\n\n /**\n * tag a component `Snap` with a semantic version. we follow SemVer specs as defined [here](https://semver.org/)).\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n tag(version: SemVer) {\n // const snap = this.snap();\n // const tag = new Tag(version, snap);\n // this.tags.set(tag);\n }\n\n /**\n * determines whether this component is modified in the workspace.\n */\n isModified(): Promise<boolean> {\n if (!this.head) return Promise.resolve(true);\n return Promise.resolve(this.state.isModified);\n // return Promise.resolve(this.state.hash !== this.head.hash);\n }\n\n /**\n * is component isOutdated\n */\n isOutdated(): boolean {\n if (!this.latest) return false;\n const latestTag = this.tags.byVersion(this.latest);\n if (!latestTag) return false;\n if (this.head?.hash !== latestTag?.hash) return true;\n return false;\n }\n\n /**\n * determines whether this component is new.\n */\n isNew(): Promise<boolean> {\n return Promise.resolve(this.head === null);\n }\n\n // TODO: @david after snap we need to make sure to refactor here.\n loadState(snapId: string): Promise<State> {\n return this.factory.getState(this.id, snapId);\n }\n\n loadSnap(snapId?: string): Promise<Snap> {\n const snapToGet = snapId || this.head?.hash;\n if (!snapToGet) {\n throw new BitError('could not load snap for new components');\n }\n return this.factory.getSnap(this.id, snapToGet);\n }\n\n /**\n * Get iterable which iterate over snap parents lazily\n * @param snapId\n * @param options\n */\n snapsIterable(snapId?: string, options: SnapsIterableOpts = {}): AsyncIterable<Snap> {\n const snapToStart = snapId || this.head?.hash;\n let nextSnaps = [snapToStart];\n let done;\n if (!snapToStart) {\n done = true;\n }\n\n const iterator: AsyncIterator<Snap> = {\n next: async () => {\n if (done) {\n return { value: undefined, done };\n }\n const currSnapId = nextSnaps.shift();\n const snap = await this.loadSnap(currSnapId);\n if (snap.parents && snap.parents.length) {\n if (options.firstParentOnly) {\n nextSnaps.push(snap.parents[0]);\n } else {\n nextSnaps = nextSnaps.concat(snap.parents);\n }\n }\n if (!nextSnaps.length) {\n done = true;\n } else if (options.stopFn) {\n done = await options.stopFn(snap);\n }\n return { value: snap, done: undefined };\n },\n };\n return {\n [Symbol.asyncIterator]: () => iterator,\n };\n }\n\n /**\n * traverse recursively from the provided snap (or head) upwards until it finds a tag\n * @param snapToStartFrom\n */\n async getClosestTag(snapToStartFrom?: string): Promise<Tag | undefined> {\n const tagsHashMap = this.tags.getHashMap();\n const stopFn = async (snap: Snap) => {\n if (tagsHashMap.has(snap.hash)) {\n return true;\n }\n return false;\n };\n const iterable = this.snapsIterable(snapToStartFrom, { firstParentOnly: true, stopFn });\n const snaps: Snap[] = [];\n for await (const snap of iterable) {\n snaps.push(snap);\n }\n if (snaps.length) {\n const hashOfLastSnap = snaps[snaps.length - 1].hash;\n return tagsHashMap.get(hashOfLastSnap);\n }\n return undefined;\n }\n\n /**\n * checkout the component to a different version in its working tree.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n checkout(version: SemVer) {}\n\n /**\n * examine difference between two components.\n */\n // diff(other: Component): Difference {}\n\n /**\n * merge two different components\n */\n // merge(other: Component): Component {}\n\n /**\n * write a component to a given file system.\n * @param path root path to write the component\n * @param fs instance of any fs to use.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n write(path: string, fs?: AnyFS) {}\n\n /**\n *\n * Check if 2 components are equal\n * @param {Component} component\n * @returns {boolean}\n * @memberof Component\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n equals(component: Component): boolean {\n return component.id.toString() === this.id.toString();\n }\n}\n"]}
@@ -0,0 +1,8 @@
1
+ export class CouldNotFindLatest extends Error {
2
+ constructor(semverArray: string[]) {
3
+ super(`could not find latest semver in array: ${semverArray.join(', ')}`);
4
+ }
5
+ report() {
6
+ return this.message;
7
+ }
8
+ }
@@ -0,0 +1,14 @@
1
+ export class HostNotFound extends Error {
2
+ constructor(
3
+ /**
4
+ * name of the host.
5
+ */
6
+ private hostName: string
7
+ ) {
8
+ super();
9
+ }
10
+
11
+ toString() {
12
+ return `[component] error: host '${this.hostName}' was not found`;
13
+ }
14
+ }
@@ -0,0 +1,4 @@
1
+ // eslint-disable-next-line import/prefer-default-export
2
+ export { default as NothingToSnap } from './nothing-to-snap';
3
+ export { HostNotFound } from './host-not-found';
4
+ export { CouldNotFindLatest } from './could-not-find-latest';
@@ -0,0 +1 @@
1
+ export default class NothingToSnap extends Error {}
@@ -0,0 +1,9 @@
1
+ import { ComponentModel } from '../ui';
2
+
3
+ export class ComponentHostModel {
4
+ constructor(readonly name: string, readonly components: ComponentModel[]) {}
5
+
6
+ static from(data: any) {
7
+ return new ComponentHostModel(data.getHost.name, ComponentModel.fromArray(data.getHost.list));
8
+ }
9
+ }
package/host/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export { useComponentHost } from './use-component-host';
2
+ export * from './component-host-model';
@@ -0,0 +1,39 @@
1
+ import { useDataQuery } from '@teambit/ui-foundation.ui.hooks.use-data-query';
2
+ import { gql } from '@apollo/client';
3
+
4
+ import { ComponentHostModel } from './component-host-model';
5
+
6
+ const COMPONENT_HOST = gql`
7
+ {
8
+ getHost {
9
+ id # used for GQL caching
10
+ name
11
+ list {
12
+ id {
13
+ name
14
+ version
15
+ scope
16
+ }
17
+ deprecation {
18
+ isDeprecate
19
+ }
20
+ env {
21
+ id
22
+ icon
23
+ }
24
+ }
25
+ }
26
+ }
27
+ `;
28
+
29
+ export function useComponentHost() {
30
+ const { data, loading } = useDataQuery(COMPONENT_HOST);
31
+
32
+ if (!data || loading) {
33
+ return {};
34
+ }
35
+
36
+ const host = ComponentHostModel.from(data);
37
+
38
+ return { host };
39
+ }