@teambit/preview 0.0.844 → 0.0.847

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.
@@ -11,8 +11,6 @@ export function html(title: string) {
11
11
  // Allow to use react dev-tools inside the examples
12
12
  try { window.__REACT_DEVTOOLS_GLOBAL_HOOK__ = window.parent.__REACT_DEVTOOLS_GLOBAL_HOOK__; } catch {}
13
13
  </script>
14
- <!-- minimal css resets -->
15
- <style> html { height: 100%; } body { margin: 0; height: 100%; } #root { height: 100%; } </style>
16
14
  </head>
17
15
  <body>
18
16
  <div id="root"></div>
@@ -18,8 +18,6 @@ function html(title) {
18
18
  // Allow to use react dev-tools inside the examples
19
19
  try { window.__REACT_DEVTOOLS_GLOBAL_HOOK__ = window.parent.__REACT_DEVTOOLS_GLOBAL_HOOK__; } catch {}
20
20
  </script>
21
- <!-- minimal css resets -->
22
- <style> html { height: 100%; } body { margin: 0; height: 100%; } #root { height: 100%; } </style>
23
21
  </head>
24
22
  <body>
25
23
  <div id="root"></div>
@@ -1 +1 @@
1
- {"version":3,"names":["html","title"],"sources":["html-template.ts"],"sourcesContent":["/** html template for Previews (docs, compositions, etc) */\nexport function html(title: string) {\n return `\n <!DOCTYPE html>\n <html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>${title}</title>\n <script>\n // Allow to use react dev-tools inside the examples\n try { window.__REACT_DEVTOOLS_GLOBAL_HOOK__ = window.parent.__REACT_DEVTOOLS_GLOBAL_HOOK__; } catch {}\n </script>\n <!-- minimal css resets -->\n <style> html { height: 100%; } body { margin: 0; height: 100%; } #root { height: 100%; } </style>\n </head>\n <body>\n <div id=\"root\"></div>\n </body>\n </html>\n `;\n}\n"],"mappings":";;;;;;;AAAA;AACO,SAASA,IAAT,CAAcC,KAAd,EAA6B;EAClC,OAAQ;AACV;AACA;AACA;AACA;AACA;AACA,eAAeA,KAAM;AACrB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAlBE;AAmBD"}
1
+ {"version":3,"names":["html","title"],"sources":["html-template.ts"],"sourcesContent":["/** html template for Previews (docs, compositions, etc) */\nexport function html(title: string) {\n return `\n <!DOCTYPE html>\n <html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>${title}</title>\n <script>\n // Allow to use react dev-tools inside the examples\n try { window.__REACT_DEVTOOLS_GLOBAL_HOOK__ = window.parent.__REACT_DEVTOOLS_GLOBAL_HOOK__; } catch {}\n </script>\n </head>\n <body>\n <div id=\"root\"></div>\n </body>\n </html>\n `;\n}\n"],"mappings":";;;;;;;AAAA;AACO,SAASA,IAAT,CAAcC,KAAd,EAA6B;EAClC,OAAQ;AACV;AACA;AACA;AACA;AACA;AACA,eAAeA,KAAM;AACrB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAhBE;AAiBD"}
@@ -0,0 +1,2 @@
1
+ import { ComponentPreview } from '@teambit/preview.ui.component-preview';
2
+ export { ComponentPreview };
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ Object.defineProperty(exports, "ComponentPreview", {
7
+ enumerable: true,
8
+ get: function () {
9
+ return _previewUi().ComponentPreview;
10
+ }
11
+ });
12
+
13
+ function _previewUi() {
14
+ const data = require("@teambit/preview.ui.component-preview");
15
+
16
+ _previewUi = function () {
17
+ return data;
18
+ };
19
+
20
+ return data;
21
+ }
22
+
23
+ //# sourceMappingURL=component-preview.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":[],"sources":["component-preview.ts"],"sourcesContent":["import { ComponentPreview } from '@teambit/preview.ui.component-preview';\n\nexport { ComponentPreview };\n"],"mappings":";;;;;;;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA"}
@@ -12,6 +12,9 @@ export declare function previewSchema(previewExtension: PreviewMain): {
12
12
  includesEnvTemplate: ({ component }: {
13
13
  component: any;
14
14
  }) => Promise<boolean>;
15
+ isScaling: ({ component }: {
16
+ component: any;
17
+ }) => Promise<boolean>;
15
18
  legacyHeader: ({ component }: {
16
19
  component: any;
17
20
  }) => Promise<boolean>;
@@ -22,6 +22,7 @@ function previewSchema(previewExtension) {
22
22
  typeDefs: (0, _graphqlTag().default)`
23
23
  type Preview {
24
24
  # url: String!
25
+ isScaling: Boolean
25
26
  includesEnvTemplate: Boolean
26
27
  legacyHeader: Boolean
27
28
  }
@@ -45,6 +46,11 @@ function previewSchema(previewExtension) {
45
46
  }) => {
46
47
  return previewExtension.isBundledWithEnv(component);
47
48
  },
49
+ isScaling: ({
50
+ component
51
+ }) => {
52
+ return previewExtension.isScaling(component);
53
+ },
48
54
  legacyHeader: ({
49
55
  component
50
56
  }) => {
@@ -1 +1 @@
1
- {"version":3,"names":["previewSchema","previewExtension","typeDefs","gql","resolvers","Component","preview","component","Preview","includesEnvTemplate","isBundledWithEnv","legacyHeader","isLegacyHeader"],"sources":["preview.graphql.ts"],"sourcesContent":["import { Component } from '@teambit/component';\nimport gql from 'graphql-tag';\n\nimport { PreviewMain } from './preview.main.runtime';\n\nexport function previewSchema(previewExtension: PreviewMain) {\n return {\n typeDefs: gql`\n type Preview {\n # url: String!\n includesEnvTemplate: Boolean\n legacyHeader: Boolean\n }\n\n extend type Component {\n preview: Preview\n }\n `,\n resolvers: {\n Component: {\n preview: (component: Component) => {\n // return previewExtension.getPreview(component);\n return { component };\n },\n },\n Preview: {\n includesEnvTemplate: ({ component }) => {\n return previewExtension.isBundledWithEnv(component);\n },\n legacyHeader: ({ component }) => {\n return previewExtension.isLegacyHeader(component);\n },\n },\n },\n };\n}\n"],"mappings":";;;;;;;;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAIO,SAASA,aAAT,CAAuBC,gBAAvB,EAAsD;EAC3D,OAAO;IACLC,QAAQ,EAAE,IAAAC,qBAAA,CAAI;AAClB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAXS;IAYLC,SAAS,EAAE;MACTC,SAAS,EAAE;QACTC,OAAO,EAAGC,SAAD,IAA0B;UACjC;UACA,OAAO;YAAEA;UAAF,CAAP;QACD;MAJQ,CADF;MAOTC,OAAO,EAAE;QACPC,mBAAmB,EAAE,CAAC;UAAEF;QAAF,CAAD,KAAmB;UACtC,OAAON,gBAAgB,CAACS,gBAAjB,CAAkCH,SAAlC,CAAP;QACD,CAHM;QAIPI,YAAY,EAAE,CAAC;UAAEJ;QAAF,CAAD,KAAmB;UAC/B,OAAON,gBAAgB,CAACW,cAAjB,CAAgCL,SAAhC,CAAP;QACD;MANM;IAPA;EAZN,CAAP;AA6BD"}
1
+ {"version":3,"names":["previewSchema","previewExtension","typeDefs","gql","resolvers","Component","preview","component","Preview","includesEnvTemplate","isBundledWithEnv","isScaling","legacyHeader","isLegacyHeader"],"sources":["preview.graphql.ts"],"sourcesContent":["import { Component } from '@teambit/component';\nimport gql from 'graphql-tag';\n\nimport { PreviewMain } from './preview.main.runtime';\n\nexport function previewSchema(previewExtension: PreviewMain) {\n return {\n typeDefs: gql`\n type Preview {\n # url: String!\n isScaling: Boolean\n includesEnvTemplate: Boolean\n legacyHeader: Boolean\n }\n\n extend type Component {\n preview: Preview\n }\n `,\n resolvers: {\n Component: {\n preview: (component: Component) => {\n // return previewExtension.getPreview(component);\n return { component };\n },\n },\n Preview: {\n includesEnvTemplate: ({ component }) => {\n return previewExtension.isBundledWithEnv(component);\n },\n isScaling: ({ component }) => {\n return previewExtension.isScaling(component);\n },\n legacyHeader: ({ component }) => {\n return previewExtension.isLegacyHeader(component);\n },\n },\n },\n };\n}\n"],"mappings":";;;;;;;;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAIO,SAASA,aAAT,CAAuBC,gBAAvB,EAAsD;EAC3D,OAAO;IACLC,QAAQ,EAAE,IAAAC,qBAAA,CAAI;AAClB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAZS;IAaLC,SAAS,EAAE;MACTC,SAAS,EAAE;QACTC,OAAO,EAAGC,SAAD,IAA0B;UACjC;UACA,OAAO;YAAEA;UAAF,CAAP;QACD;MAJQ,CADF;MAOTC,OAAO,EAAE;QACPC,mBAAmB,EAAE,CAAC;UAAEF;QAAF,CAAD,KAAmB;UACtC,OAAON,gBAAgB,CAACS,gBAAjB,CAAkCH,SAAlC,CAAP;QACD,CAHM;QAIPI,SAAS,EAAE,CAAC;UAAEJ;QAAF,CAAD,KAAmB;UAC5B,OAAON,gBAAgB,CAACU,SAAjB,CAA2BJ,SAA3B,CAAP;QACD,CANM;QAOPK,YAAY,EAAE,CAAC;UAAEL;QAAF,CAAD,KAAmB;UAC/B,OAAON,gBAAgB,CAACY,cAAjB,CAAgCN,SAAhC,CAAP;QACD;MATM;IAPA;EAbN,CAAP;AAiCD"}
@@ -94,6 +94,10 @@ export declare class PreviewMain {
94
94
  * @returns
95
95
  */
96
96
  isBundledWithEnv(component: Component): Promise<boolean>;
97
+ /**
98
+ * can the current component preview scale in size for different preview sizes.
99
+ */
100
+ isScaling(component: Component): Promise<boolean>;
97
101
  /**
98
102
  * Check if the component preview bundle contain the header inside of it (legacy)
99
103
  * today we are not including the header inside anymore
@@ -495,6 +495,17 @@ class PreviewMain {
495
495
  if (!artifacts || !artifacts.length) return true;
496
496
  return false;
497
497
  }
498
+ /**
499
+ * can the current component preview scale in size for different preview sizes.
500
+ */
501
+
502
+
503
+ async isScaling(component) {
504
+ var _component$state$aspe;
505
+
506
+ const previewData = (_component$state$aspe = component.state.aspects.get(_preview().PreviewAspect.id)) === null || _component$state$aspe === void 0 ? void 0 : _component$state$aspe.data;
507
+ return previewData === null || previewData === void 0 ? void 0 : previewData.scaling;
508
+ }
498
509
  /**
499
510
  * Check if the component preview bundle contain the header inside of it (legacy)
500
511
  * today we are not including the header inside anymore
@@ -774,6 +785,12 @@ class PreviewMain {
774
785
 
775
786
  if (workspace) {
776
787
  workspace.registerOnComponentAdd(c => preview.handleComponentChange(c, currentComponents => currentComponents.add(c)));
788
+ workspace.onComponentLoad(async () => {
789
+ return {
790
+ // used for backward compatibility. can be removed in the future.
791
+ scaling: true
792
+ };
793
+ });
777
794
  workspace.registerOnComponentChange(c => preview.handleComponentChange(c, currentComponents => currentComponents.update(c)));
778
795
  workspace.registerOnComponentRemove(cId => preview.handleComponentRemoval(cId));
779
796
  }
@@ -1 +1 @@
1
- {"version":3,"names":["noopResult","results","toString","DEFAULT_TEMP_DIR","join","CACHE_ROOT","PreviewAspect","id","PreviewMain","constructor","harmony","previewSlot","ui","envs","componentAspect","pkg","aspectLoader","config","bundlingStrategySlot","builder","workspace","logger","dependencyResolver","Map","Date","now","c","updater","env","getEnv","envId","executionRef","executionRefs","get","warn","updateLinkFiles","currentComponents","executionCtx","cId","component","forEach","components","found","Promise","resolve","handleComponentChange","remove","tempFolder","getTempDir","getComponentBundleSize","data","getDataByAspect","undefined","COMPONENT_STRATEGY_SIZE_KEY_NAME","getPreview","artifacts","getArtifactsVinylByAspectAndTaskName","PREVIEW_TASK_NAME","PreviewArtifact","getPreviewFiles","isBundledWithEnv","files","getPaths","getArtifactsVinylByAspectAndName","COMPONENT_STRATEGY_ARTIFACT_NAME","length","isLegacyHeader","ENV_WITH_LEGACY_DOCS","ENV_STRATEGY_ARTIFACT_NAME","envType","getEnvData","type","includes","getEnvTemplate","GENERATE_ENV_TEMPLATE_TASK_NAME","getCoreEnvTemplate","coreEnvDir","getAspectDir","artifactDef","getEnvTemplateArtifactDef","artifactFactory","ArtifactFactory","rootDir","getRootDir","existsSync","coreEnvDirFromBvm","getAspectDirFromBvm","paths","resolvePaths","artifactFiles","ArtifactFiles","populateVinylsFromPaths","vinyls","getEnvTemplateFromComponentEnv","getEnvId","getEnvTemplateByEnvId","isCoreEnv","host","getHost","resolvedEnvId","resolveComponentId","envComponent","BitError","getDefs","values","writeLink","prefix","moduleMap","defaultModule","dirName","isSplitComponentBundle","contents","generateLink","writeLinkContents","targetDir","hash","objectHash","targetPath","timestamp","writeHash","writeFileSync","set","getPreviewTarget","context","relatedContexts","ctxId","ExecutionRef","previewRuntime","writePreviewRuntime","linkFiles","previews","map","previewDef","templatePath","renderTemplatePath","getModuleMap","getEnvPreviewConfig","splitComponentBundle","withPaths","environment","compilerInstance","getCompiler","modulePath","getPreviewComponentRootPath","getRuntimeModulePath","file","path","distRelativePath","getDistPathBySrcPath","relative","dirPath","mkdirSync","recursive","link","all","aspectsIdsToNotFilterOut","name","uiRoot","getUi","resolvedAspects","resolveAspects","PreviewRuntime","filteredAspects","filterAspectsByExecutionContext","filePath","generateRoot","runtimeName","componentIds","opts","root","MainRuntime","Error","aspects","allComponentContextAspects","reduce","acc","curr","concat","state","ids","hostAspects","Object","keys","toObject","allAspectsToInclude","uniq","filtered","filter","aspect","getId","isCoreAspect","getDefaultStrategies","EnvBundlingStrategy","ComponentBundlingStrategy","getPreviewConfig","getBundlingStrategy","defaultStrategies","envPreviewConfig","strategyFromEnv","strategyName","bundlingStrategy","strategies","selected","find","strategy","BundlingStrategyNotFound","registerBundlingStrategy","register","registerDefinition","provider","bundler","componentExtension","uiMain","pubsub","loggerMain","graphql","createLogger","preview","registerStartPlugin","PreviewStartPlugin","registerRoute","PreviewRoute","ComponentPreviewRoute","EnvTemplateRoute","PreviewAssetsRoute","registerTarget","entry","bind","disabled","registerBuildTasks","EnvPreviewTemplateTask","PreviewTask","registerOnComponentAdd","add","registerOnComponentChange","update","registerOnComponentRemove","handleComponentRemoval","previewSchema","Slot","withType","BundlerAspect","BuilderAspect","ComponentAspect","UIAspect","EnvsAspect","WorkspaceAspect","PkgAspect","PubsubAspect","AspectLoaderAspect","LoggerAspect","DependencyResolverAspect","GraphqlAspect","addRuntime"],"sources":["preview.main.runtime.tsx"],"sourcesContent":["import { ArtifactFactory, BuilderAspect } from '@teambit/builder';\nimport type { BuilderMain } from '@teambit/builder';\nimport { Asset, BundlerAspect, BundlerMain } from '@teambit/bundler';\nimport { PubsubAspect, PubsubMain } from '@teambit/pubsub';\nimport { MainRuntime } from '@teambit/cli';\nimport {\n Component,\n ComponentAspect,\n ComponentMain,\n ComponentMap,\n ComponentID,\n ResolveAspectsOptions,\n} from '@teambit/component';\nimport { EnvsAspect } from '@teambit/envs';\nimport type { EnvsMain, ExecutionContext, PreviewEnv } from '@teambit/envs';\nimport { Slot, SlotRegistry, Harmony } from '@teambit/harmony';\nimport { UIAspect, UiMain, UIRoot } from '@teambit/ui';\nimport { CACHE_ROOT } from '@teambit/legacy/dist/constants';\nimport { BitError } from '@teambit/bit-error';\nimport objectHash from 'object-hash';\nimport { uniq } from 'lodash';\nimport { writeFileSync, existsSync, mkdirSync } from 'fs-extra';\nimport { join } from 'path';\nimport { PkgAspect, PkgMain } from '@teambit/pkg';\nimport { AspectLoaderAspect, getAspectDir, getAspectDirFromBvm } from '@teambit/aspect-loader';\nimport type { AspectDefinition, AspectLoaderMain } from '@teambit/aspect-loader';\nimport WorkspaceAspect, { Workspace } from '@teambit/workspace';\nimport { LoggerAspect, LoggerMain, Logger } from '@teambit/logger';\nimport { DependencyResolverAspect } from '@teambit/dependency-resolver';\nimport type { DependencyResolverMain } from '@teambit/dependency-resolver';\nimport { ArtifactFiles } from '@teambit/legacy/dist/consumer/component/sources/artifact-files';\nimport GraphqlAspect, { GraphqlMain } from '@teambit/graphql';\nimport { BundlingStrategyNotFound } from './exceptions';\nimport { generateLink } from './generate-link';\nimport { PreviewArtifact } from './preview-artifact';\nimport { PreviewDefinition } from './preview-definition';\nimport { PreviewAspect, PreviewRuntime } from './preview.aspect';\nimport { PreviewRoute } from './preview.route';\nimport { PreviewTask, PREVIEW_TASK_NAME } from './preview.task';\nimport { BundlingStrategy } from './bundling-strategy';\nimport { EnvBundlingStrategy, ComponentBundlingStrategy } from './strategies';\nimport { ExecutionRef } from './execution-ref';\nimport { PreviewStartPlugin } from './preview.start-plugin';\nimport {\n EnvPreviewTemplateTask,\n GENERATE_ENV_TEMPLATE_TASK_NAME,\n getArtifactDef as getEnvTemplateArtifactDef,\n} from './env-preview-template.task';\nimport { EnvTemplateRoute } from './env-template.route';\nimport { ComponentPreviewRoute } from './component-preview.route';\nimport { COMPONENT_STRATEGY_ARTIFACT_NAME, COMPONENT_STRATEGY_SIZE_KEY_NAME } from './strategies/component-strategy';\nimport { ENV_STRATEGY_ARTIFACT_NAME } from './strategies/env-strategy';\nimport { previewSchema } from './preview.graphql';\nimport { PreviewAssetsRoute } from './preview-assets.route';\n\nconst noopResult = {\n results: [],\n toString: () => `updating link file`,\n};\n\nconst DEFAULT_TEMP_DIR = join(CACHE_ROOT, PreviewAspect.id);\n\nexport type PreviewDefinitionRegistry = SlotRegistry<PreviewDefinition>;\n\ntype PreviewFiles = {\n files: string[];\n isBundledWithEnv: boolean;\n};\n\nexport type ComponentPreviewSizedFile = Asset;\n\nexport type ComponentPreviewSize = {\n files: ComponentPreviewSizedFile[];\n assets: ComponentPreviewSizedFile[];\n totalFiles: number;\n compressedTotalFiles?: number;\n totalAssets: number;\n compressedTotalAssets?: number;\n total: number;\n compressedTotal?: number;\n};\n\nexport type ComponentPreviewMetaData = {\n size?: ComponentPreviewSize;\n};\n\nexport type PreviewConfig = {\n bundlingStrategy?: string;\n disabled: boolean;\n /**\n * limit concurrent components when running the bundling step for your bundler during generate components preview task.\n * this helps mitigate large memory consumption for the build pipeline. This may increase the overall time for the generate-preview task, but reduce memory footprint.\n * default - no limit.\n */\n maxChunkSize?: number;\n};\n\nexport type EnvPreviewConfig = {\n strategyName?: string;\n splitComponentBundle?: boolean;\n};\n\nexport type BundlingStrategySlot = SlotRegistry<BundlingStrategy>;\n\nexport type GenerateLinkFn = (prefix: string, componentMap: ComponentMap<string[]>, defaultModule?: string) => string;\n\nexport class PreviewMain {\n constructor(\n /**\n * harmony context.\n */\n private harmony: Harmony,\n\n /**\n * slot for preview definitions.\n */\n private previewSlot: PreviewDefinitionRegistry,\n\n private ui: UiMain,\n\n private envs: EnvsMain,\n\n private componentAspect: ComponentMain,\n\n private pkg: PkgMain,\n\n private aspectLoader: AspectLoaderMain,\n\n readonly config: PreviewConfig,\n\n private bundlingStrategySlot: BundlingStrategySlot,\n\n private builder: BuilderMain,\n\n private workspace: Workspace | undefined,\n\n private logger: Logger,\n\n private dependencyResolver: DependencyResolverMain\n ) {}\n\n get tempFolder(): string {\n return this.workspace?.getTempDir(PreviewAspect.id) || DEFAULT_TEMP_DIR;\n }\n\n getComponentBundleSize(component: Component): ComponentPreviewSize | undefined {\n const data = this.builder.getDataByAspect(component, PreviewAspect.id);\n\n if (!data) return undefined;\n return data[COMPONENT_STRATEGY_SIZE_KEY_NAME];\n }\n\n async getPreview(component: Component): Promise<PreviewArtifact | undefined> {\n const artifacts = await this.builder.getArtifactsVinylByAspectAndTaskName(\n component,\n PreviewAspect.id,\n PREVIEW_TASK_NAME\n );\n if (!artifacts) return undefined;\n return new PreviewArtifact(artifacts);\n }\n\n /**\n * Get a list of all the artifact files generated during the GeneratePreview task\n * @param component\n * @returns\n */\n async getPreviewFiles(component: Component): Promise<PreviewFiles | undefined> {\n const artifacts = await this.getPreview(component);\n const isBundledWithEnv = await this.isBundledWithEnv(component);\n if (!artifacts) return undefined;\n return {\n files: artifacts.getPaths(),\n isBundledWithEnv,\n };\n }\n\n /**\n * Check if the component preview bundle contain the env as part of the bundle or only the component code\n * (we used in the past to bundle them together, there might also be specific envs which still uses the env strategy)\n * @param component\n * @returns\n */\n async isBundledWithEnv(component: Component): Promise<boolean> {\n const artifacts = await this.builder.getArtifactsVinylByAspectAndName(\n component,\n PreviewAspect.id,\n COMPONENT_STRATEGY_ARTIFACT_NAME\n );\n if (!artifacts || !artifacts.length) return true;\n\n return false;\n }\n\n /**\n * Check if the component preview bundle contain the header inside of it (legacy)\n * today we are not including the header inside anymore\n * @param component\n * @returns\n */\n async isLegacyHeader(component: Component): Promise<boolean> {\n // these envs had header in their docs\n const ENV_WITH_LEGACY_DOCS = ['react', 'env', 'aspect', 'lit', 'html', 'node', 'mdx', 'react-native', 'readme'];\n\n const artifacts = await this.builder.getArtifactsVinylByAspectAndName(\n component,\n PreviewAspect.id,\n ENV_STRATEGY_ARTIFACT_NAME\n );\n const envType = this.envs.getEnvData(component).type;\n return !!artifacts && !!artifacts.length && ENV_WITH_LEGACY_DOCS.includes(envType);\n }\n\n /**\n * Getting the env template artifact\n * This should be called with the env itself or it will return undefined\n * If you want to get the env template from the env of the component,\n * use: getEnvTemplateFromComponentEnv below\n *\n * @param component\n * @returns\n */\n async getEnvTemplate(component: Component): Promise<PreviewArtifact | undefined> {\n const artifacts = await this.builder.getArtifactsVinylByAspectAndTaskName(\n component,\n PreviewAspect.id,\n GENERATE_ENV_TEMPLATE_TASK_NAME\n );\n if (!artifacts || !artifacts.length) return undefined;\n\n return new PreviewArtifact(artifacts);\n }\n\n /**\n * This is a special method to get a core env template\n * As the core envs doesn't exist in the scope we need to bring it from other place\n * We will bring it from the core env package files\n */\n private async getCoreEnvTemplate(envId: string): Promise<PreviewArtifact | undefined> {\n const coreEnvDir = getAspectDir(envId);\n // const finalDir = join(coreEnvDir, getEnvTemplateArtifactDirectory());\n const artifactDef = getEnvTemplateArtifactDef()[0];\n const artifactFactory = new ArtifactFactory();\n\n let rootDir = artifactFactory.getRootDir(coreEnvDir, artifactDef);\n if (!existsSync(rootDir)) {\n // fallback to the bvm folder\n const coreEnvDirFromBvm = getAspectDirFromBvm(envId);\n rootDir = artifactFactory.getRootDir(coreEnvDirFromBvm, artifactDef);\n }\n if (!existsSync(rootDir)) {\n return undefined;\n }\n const paths = artifactFactory.resolvePaths(rootDir, artifactDef);\n if (!paths || !paths.length) {\n return undefined;\n }\n const artifactFiles = new ArtifactFiles(paths);\n\n artifactFiles.populateVinylsFromPaths(rootDir);\n return new PreviewArtifact(artifactFiles.vinyls);\n }\n\n /**\n * This will fetch the component env, then will take the env template from the component env\n * @param component\n */\n async getEnvTemplateFromComponentEnv(component: Component): Promise<PreviewArtifact | undefined> {\n const envId = this.envs.getEnvId(component);\n return this.getEnvTemplateByEnvId(envId);\n }\n\n /**\n * This will fetch the component env, then will take the env template from the component env\n * @param component\n */\n async getEnvTemplateByEnvId(envId: string): Promise<PreviewArtifact | undefined> {\n // Special treatment for core envs\n if (this.aspectLoader.isCoreEnv(envId)) {\n return this.getCoreEnvTemplate(envId);\n }\n const host = this.componentAspect.getHost();\n const resolvedEnvId = await host.resolveComponentId(envId);\n const envComponent = await host.get(resolvedEnvId);\n if (!envComponent) {\n throw new BitError(`can't load env. env id is ${envId}`);\n }\n return this.getEnvTemplate(envComponent);\n }\n\n getDefs(): PreviewDefinition[] {\n return this.previewSlot.values();\n }\n\n private writeHash = new Map<string, string>();\n private timestamp = Date.now();\n\n /**\n * write a link to load custom modules dynamically.\n * @param prefix write\n * @param moduleMap map of components to module paths to require.\n * @param defaultModule\n * @param dirName\n */\n writeLink(\n prefix: string,\n moduleMap: ComponentMap<string[]>,\n defaultModule: string | undefined,\n dirName: string,\n isSplitComponentBundle: boolean\n ) {\n const contents = generateLink(prefix, moduleMap, defaultModule, isSplitComponentBundle);\n return this.writeLinkContents(contents, dirName, prefix);\n }\n\n writeLinkContents(contents: string, targetDir: string, prefix: string) {\n const hash = objectHash(contents);\n const targetPath = join(targetDir, `${prefix}-${this.timestamp}.js`);\n\n // write only if link has changed (prevents triggering fs watches)\n if (this.writeHash.get(targetPath) !== hash) {\n writeFileSync(targetPath, contents);\n this.writeHash.set(targetPath, hash);\n }\n\n return targetPath;\n }\n\n private executionRefs = new Map<string, ExecutionRef>();\n\n private async getPreviewTarget(\n /** execution context (of the specific env) */\n context: ExecutionContext\n ): Promise<string[]> {\n // store context for later link-file updates\n // also register related envs that this context is acting on their behalf\n [context.id, ...context.relatedContexts].forEach((ctxId) => {\n this.executionRefs.set(ctxId, new ExecutionRef(context));\n });\n\n const previewRuntime = await this.writePreviewRuntime(context);\n const linkFiles = await this.updateLinkFiles(context.components, context);\n\n return [...linkFiles, previewRuntime];\n }\n\n private updateLinkFiles(components: Component[] = [], context: ExecutionContext) {\n const previews = this.previewSlot.values();\n const paths = previews.map(async (previewDef) => {\n const templatePath = await previewDef.renderTemplatePath?.(context);\n\n const map = await previewDef.getModuleMap(components);\n const isSplitComponentBundle = this.getEnvPreviewConfig().splitComponentBundle ?? false;\n const withPaths = map.map<string[]>((files, component) => {\n const environment = this.envs.getEnv(component).env;\n const compilerInstance = environment.getCompiler?.();\n const modulePath =\n compilerInstance?.getPreviewComponentRootPath?.(component) || this.pkg.getRuntimeModulePath(component);\n return files.map((file) => {\n if (!this.workspace || !compilerInstance) {\n return file.path;\n }\n const distRelativePath = compilerInstance.getDistPathBySrcPath(file.relative);\n return join(this.workspace.path, modulePath, distRelativePath);\n });\n // return files.map((file) => file.path);\n });\n\n const dirPath = join(this.tempFolder, context.id);\n if (!existsSync(dirPath)) mkdirSync(dirPath, { recursive: true });\n\n const link = this.writeLink(previewDef.prefix, withPaths, templatePath, dirPath, isSplitComponentBundle);\n return link;\n });\n\n return Promise.all(paths);\n }\n\n async writePreviewRuntime(context: { components: Component[] }, aspectsIdsToNotFilterOut: string[] = []) {\n const [name, uiRoot] = this.getUi();\n const resolvedAspects = await this.resolveAspects(PreviewRuntime.name, undefined, uiRoot);\n const filteredAspects = this.filterAspectsByExecutionContext(resolvedAspects, context, aspectsIdsToNotFilterOut);\n const filePath = await this.ui.generateRoot(filteredAspects, name, 'preview', PreviewAspect.id);\n return filePath;\n }\n\n async resolveAspects(\n runtimeName?: string,\n componentIds?: ComponentID[],\n uiRoot?: UIRoot,\n opts?: ResolveAspectsOptions\n ): Promise<AspectDefinition[]> {\n const root = uiRoot || this.getUi()[1];\n runtimeName = runtimeName || MainRuntime.name;\n const resolvedAspects = await root.resolveAspects(runtimeName, componentIds, opts);\n return resolvedAspects;\n }\n\n private getUi() {\n const ui = this.ui.getUi();\n if (!ui) throw new Error('ui not found');\n return ui;\n }\n\n /**\n * Filter the aspects to have only aspects that are:\n * 1. core aspects\n * 2. configured on the host (workspace/scope)\n * 3. used by at least one component from the context\n * @param aspects\n * @param context\n */\n private filterAspectsByExecutionContext(\n aspects: AspectDefinition[],\n context: { components: Component[] },\n aspectsIdsToNotFilterOut: string[] = []\n ) {\n let allComponentContextAspects: string[] = [];\n allComponentContextAspects = context.components.reduce((acc, curr) => {\n return acc.concat(curr.state.aspects.ids);\n }, allComponentContextAspects);\n const hostAspects = Object.keys(this.harmony.config.toObject());\n const allAspectsToInclude = uniq(hostAspects.concat(allComponentContextAspects));\n const filtered = aspects.filter((aspect) => {\n if (!aspect.getId) {\n return false;\n }\n return (\n this.aspectLoader.isCoreAspect(aspect.getId) ||\n allAspectsToInclude.includes(aspect.getId) ||\n aspectsIdsToNotFilterOut.includes(aspect.getId)\n );\n });\n\n return filtered;\n }\n\n private getDefaultStrategies() {\n return [\n new EnvBundlingStrategy(this, this.pkg, this.dependencyResolver),\n new ComponentBundlingStrategy(this, this.pkg, this.dependencyResolver),\n ];\n }\n\n // TODO - executionContext should be responsible for updating components list, and emit 'update' events\n // instead we keep track of changes\n private handleComponentChange = async (c: Component, updater: (currentComponents: ExecutionRef) => void) => {\n const env = this.envs.getEnv(c);\n const envId = env.id.toString();\n\n const executionRef = this.executionRefs.get(envId);\n if (!executionRef) {\n this.logger.warn(\n `failed to update link file for component \"${c.id.toString()}\" - could not find execution context for ${envId}`\n );\n return noopResult;\n }\n\n // add / remove / etc\n updater(executionRef);\n\n await this.updateLinkFiles(executionRef.currentComponents, executionRef.executionCtx);\n\n return noopResult;\n };\n\n private handleComponentRemoval = (cId: ComponentID) => {\n let component: Component | undefined;\n this.executionRefs.forEach((components) => {\n const found = components.get(cId);\n if (found) component = found;\n });\n if (!component) return Promise.resolve(noopResult);\n\n return this.handleComponentChange(component, (currentComponents) => currentComponents.remove(cId));\n };\n\n getEnvPreviewConfig(env?: PreviewEnv): EnvPreviewConfig {\n const config = env?.getPreviewConfig && typeof env?.getPreviewConfig === 'function' ? env?.getPreviewConfig() : {};\n\n return config;\n }\n\n /**\n * return the configured bundling strategy.\n */\n getBundlingStrategy(env?: PreviewEnv): BundlingStrategy {\n const defaultStrategies = this.getDefaultStrategies();\n const envPreviewConfig = this.getEnvPreviewConfig(env);\n const strategyFromEnv = envPreviewConfig?.strategyName;\n const strategyName = strategyFromEnv || this.config.bundlingStrategy || 'env';\n const strategies = this.bundlingStrategySlot.values().concat(defaultStrategies);\n const selected = strategies.find((strategy) => {\n return strategy.name === strategyName;\n });\n\n if (!selected) throw new BundlingStrategyNotFound(strategyName);\n\n return selected;\n }\n\n /**\n * register a new bundling strategy. default available strategies are `env` and ``\n */\n registerBundlingStrategy(bundlingStrategy: BundlingStrategy) {\n this.bundlingStrategySlot.register(bundlingStrategy);\n return this;\n }\n\n /**\n * register a new preview definition.\n */\n registerDefinition(previewDef: PreviewDefinition) {\n this.previewSlot.register(previewDef);\n }\n\n static slots = [Slot.withType<PreviewDefinition>(), Slot.withType<BundlingStrategy>()];\n\n static runtime = MainRuntime;\n static dependencies = [\n BundlerAspect,\n BuilderAspect,\n ComponentAspect,\n UIAspect,\n EnvsAspect,\n WorkspaceAspect,\n PkgAspect,\n PubsubAspect,\n AspectLoaderAspect,\n LoggerAspect,\n DependencyResolverAspect,\n GraphqlAspect,\n ];\n\n static defaultConfig = {\n disabled: false,\n };\n\n static async provider(\n // eslint-disable-next-line max-len\n [\n bundler,\n builder,\n componentExtension,\n uiMain,\n envs,\n workspace,\n pkg,\n pubsub,\n aspectLoader,\n loggerMain,\n dependencyResolver,\n graphql,\n ]: [\n BundlerMain,\n BuilderMain,\n ComponentMain,\n UiMain,\n EnvsMain,\n Workspace | undefined,\n PkgMain,\n PubsubMain,\n AspectLoaderMain,\n LoggerMain,\n DependencyResolverMain,\n GraphqlMain\n ],\n config: PreviewConfig,\n [previewSlot, bundlingStrategySlot]: [PreviewDefinitionRegistry, BundlingStrategySlot],\n harmony: Harmony\n ) {\n const logger = loggerMain.createLogger(PreviewAspect.id);\n // app.registerApp(new PreviewApp());\n const preview = new PreviewMain(\n harmony,\n previewSlot,\n uiMain,\n envs,\n componentExtension,\n pkg,\n aspectLoader,\n config,\n bundlingStrategySlot,\n builder,\n workspace,\n logger,\n dependencyResolver\n );\n\n if (workspace) uiMain.registerStartPlugin(new PreviewStartPlugin(workspace, bundler, uiMain, pubsub, logger));\n\n componentExtension.registerRoute([\n new PreviewRoute(preview, logger),\n new ComponentPreviewRoute(preview, logger),\n // @ts-ignore\n new EnvTemplateRoute(preview, logger),\n new PreviewAssetsRoute(preview, logger),\n ]);\n\n bundler.registerTarget([\n {\n entry: preview.getPreviewTarget.bind(preview),\n },\n ]);\n\n if (!config.disabled)\n builder.registerBuildTasks([\n new EnvPreviewTemplateTask(preview, envs, aspectLoader, dependencyResolver, logger),\n new PreviewTask(bundler, preview, dependencyResolver, logger),\n ]);\n\n if (workspace) {\n workspace.registerOnComponentAdd((c) =>\n preview.handleComponentChange(c, (currentComponents) => currentComponents.add(c))\n );\n workspace.registerOnComponentChange((c) =>\n preview.handleComponentChange(c, (currentComponents) => currentComponents.update(c))\n );\n workspace.registerOnComponentRemove((cId) => preview.handleComponentRemoval(cId));\n }\n\n graphql.register(previewSchema(preview));\n\n return preview;\n }\n}\n\nPreviewAspect.addRuntime(PreviewMain);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAQA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EA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A1ZJxO,W,aA4ZMkK,kB;gCA5ZNlK,W,kBA6ZW,CACpByO,wBADoB,EAEpBC,wBAFoB,EAGpBC,4BAHoB,EAIpBC,cAJoB,EAKpBC,kBALoB,EAMpBC,oBANoB,EAOpBC,gBAPoB,EAQpBC,sBARoB,EASpBC,kCAToB,EAUpBC,sBAVoB,EAWpBC,8CAXoB,EAYpBC,kBAZoB,C;gCA7ZXpP,W,mBA4aY;EACrB4N,QAAQ,EAAE;AADW,C;;AA6FzB9N,wBAAA,CAAcuP,UAAd,CAAyBrP,WAAzB"}
1
+ {"version":3,"names":["noopResult","results","toString","DEFAULT_TEMP_DIR","join","CACHE_ROOT","PreviewAspect","id","PreviewMain","constructor","harmony","previewSlot","ui","envs","componentAspect","pkg","aspectLoader","config","bundlingStrategySlot","builder","workspace","logger","dependencyResolver","Map","Date","now","c","updater","env","getEnv","envId","executionRef","executionRefs","get","warn","updateLinkFiles","currentComponents","executionCtx","cId","component","forEach","components","found","Promise","resolve","handleComponentChange","remove","tempFolder","getTempDir","getComponentBundleSize","data","getDataByAspect","undefined","COMPONENT_STRATEGY_SIZE_KEY_NAME","getPreview","artifacts","getArtifactsVinylByAspectAndTaskName","PREVIEW_TASK_NAME","PreviewArtifact","getPreviewFiles","isBundledWithEnv","files","getPaths","getArtifactsVinylByAspectAndName","COMPONENT_STRATEGY_ARTIFACT_NAME","length","isScaling","previewData","state","aspects","scaling","isLegacyHeader","ENV_WITH_LEGACY_DOCS","ENV_STRATEGY_ARTIFACT_NAME","envType","getEnvData","type","includes","getEnvTemplate","GENERATE_ENV_TEMPLATE_TASK_NAME","getCoreEnvTemplate","coreEnvDir","getAspectDir","artifactDef","getEnvTemplateArtifactDef","artifactFactory","ArtifactFactory","rootDir","getRootDir","existsSync","coreEnvDirFromBvm","getAspectDirFromBvm","paths","resolvePaths","artifactFiles","ArtifactFiles","populateVinylsFromPaths","vinyls","getEnvTemplateFromComponentEnv","getEnvId","getEnvTemplateByEnvId","isCoreEnv","host","getHost","resolvedEnvId","resolveComponentId","envComponent","BitError","getDefs","values","writeLink","prefix","moduleMap","defaultModule","dirName","isSplitComponentBundle","contents","generateLink","writeLinkContents","targetDir","hash","objectHash","targetPath","timestamp","writeHash","writeFileSync","set","getPreviewTarget","context","relatedContexts","ctxId","ExecutionRef","previewRuntime","writePreviewRuntime","linkFiles","previews","map","previewDef","templatePath","renderTemplatePath","getModuleMap","getEnvPreviewConfig","splitComponentBundle","withPaths","environment","compilerInstance","getCompiler","modulePath","getPreviewComponentRootPath","getRuntimeModulePath","file","path","distRelativePath","getDistPathBySrcPath","relative","dirPath","mkdirSync","recursive","link","all","aspectsIdsToNotFilterOut","name","uiRoot","getUi","resolvedAspects","resolveAspects","PreviewRuntime","filteredAspects","filterAspectsByExecutionContext","filePath","generateRoot","runtimeName","componentIds","opts","root","MainRuntime","Error","allComponentContextAspects","reduce","acc","curr","concat","ids","hostAspects","Object","keys","toObject","allAspectsToInclude","uniq","filtered","filter","aspect","getId","isCoreAspect","getDefaultStrategies","EnvBundlingStrategy","ComponentBundlingStrategy","getPreviewConfig","getBundlingStrategy","defaultStrategies","envPreviewConfig","strategyFromEnv","strategyName","bundlingStrategy","strategies","selected","find","strategy","BundlingStrategyNotFound","registerBundlingStrategy","register","registerDefinition","provider","bundler","componentExtension","uiMain","pubsub","loggerMain","graphql","createLogger","preview","registerStartPlugin","PreviewStartPlugin","registerRoute","PreviewRoute","ComponentPreviewRoute","EnvTemplateRoute","PreviewAssetsRoute","registerTarget","entry","bind","disabled","registerBuildTasks","EnvPreviewTemplateTask","PreviewTask","registerOnComponentAdd","add","onComponentLoad","registerOnComponentChange","update","registerOnComponentRemove","handleComponentRemoval","previewSchema","Slot","withType","BundlerAspect","BuilderAspect","ComponentAspect","UIAspect","EnvsAspect","WorkspaceAspect","PkgAspect","PubsubAspect","AspectLoaderAspect","LoggerAspect","DependencyResolverAspect","GraphqlAspect","addRuntime"],"sources":["preview.main.runtime.tsx"],"sourcesContent":["import { ArtifactFactory, BuilderAspect } from '@teambit/builder';\nimport type { BuilderMain } from '@teambit/builder';\nimport { Asset, BundlerAspect, BundlerMain } from '@teambit/bundler';\nimport { PubsubAspect, PubsubMain } from '@teambit/pubsub';\nimport { MainRuntime } from '@teambit/cli';\nimport {\n Component,\n ComponentAspect,\n ComponentMain,\n ComponentMap,\n ComponentID,\n ResolveAspectsOptions,\n} from '@teambit/component';\nimport { EnvsAspect } from '@teambit/envs';\nimport type { EnvsMain, ExecutionContext, PreviewEnv } from '@teambit/envs';\nimport { Slot, SlotRegistry, Harmony } from '@teambit/harmony';\nimport { UIAspect, UiMain, UIRoot } from '@teambit/ui';\nimport { CACHE_ROOT } from '@teambit/legacy/dist/constants';\nimport { BitError } from '@teambit/bit-error';\nimport objectHash from 'object-hash';\nimport { uniq } from 'lodash';\nimport { writeFileSync, existsSync, mkdirSync } from 'fs-extra';\nimport { join } from 'path';\nimport { PkgAspect, PkgMain } from '@teambit/pkg';\nimport { AspectLoaderAspect, getAspectDir, getAspectDirFromBvm } from '@teambit/aspect-loader';\nimport type { AspectDefinition, AspectLoaderMain } from '@teambit/aspect-loader';\nimport WorkspaceAspect, { Workspace } from '@teambit/workspace';\nimport { LoggerAspect, LoggerMain, Logger } from '@teambit/logger';\nimport { DependencyResolverAspect } from '@teambit/dependency-resolver';\nimport type { DependencyResolverMain } from '@teambit/dependency-resolver';\nimport { ArtifactFiles } from '@teambit/legacy/dist/consumer/component/sources/artifact-files';\nimport GraphqlAspect, { GraphqlMain } from '@teambit/graphql';\nimport { BundlingStrategyNotFound } from './exceptions';\nimport { generateLink } from './generate-link';\nimport { PreviewArtifact } from './preview-artifact';\nimport { PreviewDefinition } from './preview-definition';\nimport { PreviewAspect, PreviewRuntime } from './preview.aspect';\nimport { PreviewRoute } from './preview.route';\nimport { PreviewTask, PREVIEW_TASK_NAME } from './preview.task';\nimport { BundlingStrategy } from './bundling-strategy';\nimport { EnvBundlingStrategy, ComponentBundlingStrategy } from './strategies';\nimport { ExecutionRef } from './execution-ref';\nimport { PreviewStartPlugin } from './preview.start-plugin';\nimport {\n EnvPreviewTemplateTask,\n GENERATE_ENV_TEMPLATE_TASK_NAME,\n getArtifactDef as getEnvTemplateArtifactDef,\n} from './env-preview-template.task';\nimport { EnvTemplateRoute } from './env-template.route';\nimport { ComponentPreviewRoute } from './component-preview.route';\nimport { COMPONENT_STRATEGY_ARTIFACT_NAME, COMPONENT_STRATEGY_SIZE_KEY_NAME } from './strategies/component-strategy';\nimport { ENV_STRATEGY_ARTIFACT_NAME } from './strategies/env-strategy';\nimport { previewSchema } from './preview.graphql';\nimport { PreviewAssetsRoute } from './preview-assets.route';\n\nconst noopResult = {\n results: [],\n toString: () => `updating link file`,\n};\n\nconst DEFAULT_TEMP_DIR = join(CACHE_ROOT, PreviewAspect.id);\n\nexport type PreviewDefinitionRegistry = SlotRegistry<PreviewDefinition>;\n\ntype PreviewFiles = {\n files: string[];\n isBundledWithEnv: boolean;\n};\n\nexport type ComponentPreviewSizedFile = Asset;\n\nexport type ComponentPreviewSize = {\n files: ComponentPreviewSizedFile[];\n assets: ComponentPreviewSizedFile[];\n totalFiles: number;\n compressedTotalFiles?: number;\n totalAssets: number;\n compressedTotalAssets?: number;\n total: number;\n compressedTotal?: number;\n};\n\nexport type ComponentPreviewMetaData = {\n size?: ComponentPreviewSize;\n};\n\nexport type PreviewConfig = {\n bundlingStrategy?: string;\n disabled: boolean;\n /**\n * limit concurrent components when running the bundling step for your bundler during generate components preview task.\n * this helps mitigate large memory consumption for the build pipeline. This may increase the overall time for the generate-preview task, but reduce memory footprint.\n * default - no limit.\n */\n maxChunkSize?: number;\n};\n\nexport type EnvPreviewConfig = {\n strategyName?: string;\n splitComponentBundle?: boolean;\n};\n\nexport type BundlingStrategySlot = SlotRegistry<BundlingStrategy>;\n\nexport type GenerateLinkFn = (prefix: string, componentMap: ComponentMap<string[]>, defaultModule?: string) => string;\n\nexport class PreviewMain {\n constructor(\n /**\n * harmony context.\n */\n private harmony: Harmony,\n\n /**\n * slot for preview definitions.\n */\n private previewSlot: PreviewDefinitionRegistry,\n\n private ui: UiMain,\n\n private envs: EnvsMain,\n\n private componentAspect: ComponentMain,\n\n private pkg: PkgMain,\n\n private aspectLoader: AspectLoaderMain,\n\n readonly config: PreviewConfig,\n\n private bundlingStrategySlot: BundlingStrategySlot,\n\n private builder: BuilderMain,\n\n private workspace: Workspace | undefined,\n\n private logger: Logger,\n\n private dependencyResolver: DependencyResolverMain\n ) {}\n\n get tempFolder(): string {\n return this.workspace?.getTempDir(PreviewAspect.id) || DEFAULT_TEMP_DIR;\n }\n\n getComponentBundleSize(component: Component): ComponentPreviewSize | undefined {\n const data = this.builder.getDataByAspect(component, PreviewAspect.id);\n\n if (!data) return undefined;\n return data[COMPONENT_STRATEGY_SIZE_KEY_NAME];\n }\n\n async getPreview(component: Component): Promise<PreviewArtifact | undefined> {\n const artifacts = await this.builder.getArtifactsVinylByAspectAndTaskName(\n component,\n PreviewAspect.id,\n PREVIEW_TASK_NAME\n );\n if (!artifacts) return undefined;\n return new PreviewArtifact(artifacts);\n }\n\n /**\n * Get a list of all the artifact files generated during the GeneratePreview task\n * @param component\n * @returns\n */\n async getPreviewFiles(component: Component): Promise<PreviewFiles | undefined> {\n const artifacts = await this.getPreview(component);\n const isBundledWithEnv = await this.isBundledWithEnv(component);\n if (!artifacts) return undefined;\n return {\n files: artifacts.getPaths(),\n isBundledWithEnv,\n };\n }\n\n /**\n * Check if the component preview bundle contain the env as part of the bundle or only the component code\n * (we used in the past to bundle them together, there might also be specific envs which still uses the env strategy)\n * @param component\n * @returns\n */\n async isBundledWithEnv(component: Component): Promise<boolean> {\n const artifacts = await this.builder.getArtifactsVinylByAspectAndName(\n component,\n PreviewAspect.id,\n COMPONENT_STRATEGY_ARTIFACT_NAME\n );\n if (!artifacts || !artifacts.length) return true;\n\n return false;\n }\n\n /**\n * can the current component preview scale in size for different preview sizes.\n */\n async isScaling(component: Component): Promise<boolean> {\n const previewData = component.state.aspects.get(PreviewAspect.id)?.data;\n return previewData?.scaling;\n }\n\n /**\n * Check if the component preview bundle contain the header inside of it (legacy)\n * today we are not including the header inside anymore\n * @param component\n * @returns\n */\n async isLegacyHeader(component: Component): Promise<boolean> {\n // these envs had header in their docs\n const ENV_WITH_LEGACY_DOCS = ['react', 'env', 'aspect', 'lit', 'html', 'node', 'mdx', 'react-native', 'readme'];\n\n const artifacts = await this.builder.getArtifactsVinylByAspectAndName(\n component,\n PreviewAspect.id,\n ENV_STRATEGY_ARTIFACT_NAME\n );\n const envType = this.envs.getEnvData(component).type;\n return !!artifacts && !!artifacts.length && ENV_WITH_LEGACY_DOCS.includes(envType);\n }\n\n /**\n * Getting the env template artifact\n * This should be called with the env itself or it will return undefined\n * If you want to get the env template from the env of the component,\n * use: getEnvTemplateFromComponentEnv below\n *\n * @param component\n * @returns\n */\n async getEnvTemplate(component: Component): Promise<PreviewArtifact | undefined> {\n const artifacts = await this.builder.getArtifactsVinylByAspectAndTaskName(\n component,\n PreviewAspect.id,\n GENERATE_ENV_TEMPLATE_TASK_NAME\n );\n if (!artifacts || !artifacts.length) return undefined;\n\n return new PreviewArtifact(artifacts);\n }\n\n /**\n * This is a special method to get a core env template\n * As the core envs doesn't exist in the scope we need to bring it from other place\n * We will bring it from the core env package files\n */\n private async getCoreEnvTemplate(envId: string): Promise<PreviewArtifact | undefined> {\n const coreEnvDir = getAspectDir(envId);\n // const finalDir = join(coreEnvDir, getEnvTemplateArtifactDirectory());\n const artifactDef = getEnvTemplateArtifactDef()[0];\n const artifactFactory = new ArtifactFactory();\n\n let rootDir = artifactFactory.getRootDir(coreEnvDir, artifactDef);\n if (!existsSync(rootDir)) {\n // fallback to the bvm folder\n const coreEnvDirFromBvm = getAspectDirFromBvm(envId);\n rootDir = artifactFactory.getRootDir(coreEnvDirFromBvm, artifactDef);\n }\n if (!existsSync(rootDir)) {\n return undefined;\n }\n const paths = artifactFactory.resolvePaths(rootDir, artifactDef);\n if (!paths || !paths.length) {\n return undefined;\n }\n const artifactFiles = new ArtifactFiles(paths);\n\n artifactFiles.populateVinylsFromPaths(rootDir);\n return new PreviewArtifact(artifactFiles.vinyls);\n }\n\n /**\n * This will fetch the component env, then will take the env template from the component env\n * @param component\n */\n async getEnvTemplateFromComponentEnv(component: Component): Promise<PreviewArtifact | undefined> {\n const envId = this.envs.getEnvId(component);\n return this.getEnvTemplateByEnvId(envId);\n }\n\n /**\n * This will fetch the component env, then will take the env template from the component env\n * @param component\n */\n async getEnvTemplateByEnvId(envId: string): Promise<PreviewArtifact | undefined> {\n // Special treatment for core envs\n if (this.aspectLoader.isCoreEnv(envId)) {\n return this.getCoreEnvTemplate(envId);\n }\n const host = this.componentAspect.getHost();\n const resolvedEnvId = await host.resolveComponentId(envId);\n const envComponent = await host.get(resolvedEnvId);\n if (!envComponent) {\n throw new BitError(`can't load env. env id is ${envId}`);\n }\n return this.getEnvTemplate(envComponent);\n }\n\n getDefs(): PreviewDefinition[] {\n return this.previewSlot.values();\n }\n\n private writeHash = new Map<string, string>();\n private timestamp = Date.now();\n\n /**\n * write a link to load custom modules dynamically.\n * @param prefix write\n * @param moduleMap map of components to module paths to require.\n * @param defaultModule\n * @param dirName\n */\n writeLink(\n prefix: string,\n moduleMap: ComponentMap<string[]>,\n defaultModule: string | undefined,\n dirName: string,\n isSplitComponentBundle: boolean\n ) {\n const contents = generateLink(prefix, moduleMap, defaultModule, isSplitComponentBundle);\n return this.writeLinkContents(contents, dirName, prefix);\n }\n\n writeLinkContents(contents: string, targetDir: string, prefix: string) {\n const hash = objectHash(contents);\n const targetPath = join(targetDir, `${prefix}-${this.timestamp}.js`);\n\n // write only if link has changed (prevents triggering fs watches)\n if (this.writeHash.get(targetPath) !== hash) {\n writeFileSync(targetPath, contents);\n this.writeHash.set(targetPath, hash);\n }\n\n return targetPath;\n }\n\n private executionRefs = new Map<string, ExecutionRef>();\n\n private async getPreviewTarget(\n /** execution context (of the specific env) */\n context: ExecutionContext\n ): Promise<string[]> {\n // store context for later link-file updates\n // also register related envs that this context is acting on their behalf\n [context.id, ...context.relatedContexts].forEach((ctxId) => {\n this.executionRefs.set(ctxId, new ExecutionRef(context));\n });\n\n const previewRuntime = await this.writePreviewRuntime(context);\n const linkFiles = await this.updateLinkFiles(context.components, context);\n\n return [...linkFiles, previewRuntime];\n }\n\n private updateLinkFiles(components: Component[] = [], context: ExecutionContext) {\n const previews = this.previewSlot.values();\n const paths = previews.map(async (previewDef) => {\n const templatePath = await previewDef.renderTemplatePath?.(context);\n\n const map = await previewDef.getModuleMap(components);\n const isSplitComponentBundle = this.getEnvPreviewConfig().splitComponentBundle ?? false;\n const withPaths = map.map<string[]>((files, component) => {\n const environment = this.envs.getEnv(component).env;\n const compilerInstance = environment.getCompiler?.();\n const modulePath =\n compilerInstance?.getPreviewComponentRootPath?.(component) || this.pkg.getRuntimeModulePath(component);\n return files.map((file) => {\n if (!this.workspace || !compilerInstance) {\n return file.path;\n }\n const distRelativePath = compilerInstance.getDistPathBySrcPath(file.relative);\n return join(this.workspace.path, modulePath, distRelativePath);\n });\n // return files.map((file) => file.path);\n });\n\n const dirPath = join(this.tempFolder, context.id);\n if (!existsSync(dirPath)) mkdirSync(dirPath, { recursive: true });\n\n const link = this.writeLink(previewDef.prefix, withPaths, templatePath, dirPath, isSplitComponentBundle);\n return link;\n });\n\n return Promise.all(paths);\n }\n\n async writePreviewRuntime(context: { components: Component[] }, aspectsIdsToNotFilterOut: string[] = []) {\n const [name, uiRoot] = this.getUi();\n const resolvedAspects = await this.resolveAspects(PreviewRuntime.name, undefined, uiRoot);\n const filteredAspects = this.filterAspectsByExecutionContext(resolvedAspects, context, aspectsIdsToNotFilterOut);\n const filePath = await this.ui.generateRoot(filteredAspects, name, 'preview', PreviewAspect.id);\n return filePath;\n }\n\n async resolveAspects(\n runtimeName?: string,\n componentIds?: ComponentID[],\n uiRoot?: UIRoot,\n opts?: ResolveAspectsOptions\n ): Promise<AspectDefinition[]> {\n const root = uiRoot || this.getUi()[1];\n runtimeName = runtimeName || MainRuntime.name;\n const resolvedAspects = await root.resolveAspects(runtimeName, componentIds, opts);\n return resolvedAspects;\n }\n\n private getUi() {\n const ui = this.ui.getUi();\n if (!ui) throw new Error('ui not found');\n return ui;\n }\n\n /**\n * Filter the aspects to have only aspects that are:\n * 1. core aspects\n * 2. configured on the host (workspace/scope)\n * 3. used by at least one component from the context\n * @param aspects\n * @param context\n */\n private filterAspectsByExecutionContext(\n aspects: AspectDefinition[],\n context: { components: Component[] },\n aspectsIdsToNotFilterOut: string[] = []\n ) {\n let allComponentContextAspects: string[] = [];\n allComponentContextAspects = context.components.reduce((acc, curr) => {\n return acc.concat(curr.state.aspects.ids);\n }, allComponentContextAspects);\n const hostAspects = Object.keys(this.harmony.config.toObject());\n const allAspectsToInclude = uniq(hostAspects.concat(allComponentContextAspects));\n const filtered = aspects.filter((aspect) => {\n if (!aspect.getId) {\n return false;\n }\n return (\n this.aspectLoader.isCoreAspect(aspect.getId) ||\n allAspectsToInclude.includes(aspect.getId) ||\n aspectsIdsToNotFilterOut.includes(aspect.getId)\n );\n });\n\n return filtered;\n }\n\n private getDefaultStrategies() {\n return [\n new EnvBundlingStrategy(this, this.pkg, this.dependencyResolver),\n new ComponentBundlingStrategy(this, this.pkg, this.dependencyResolver),\n ];\n }\n\n // TODO - executionContext should be responsible for updating components list, and emit 'update' events\n // instead we keep track of changes\n private handleComponentChange = async (c: Component, updater: (currentComponents: ExecutionRef) => void) => {\n const env = this.envs.getEnv(c);\n const envId = env.id.toString();\n\n const executionRef = this.executionRefs.get(envId);\n if (!executionRef) {\n this.logger.warn(\n `failed to update link file for component \"${c.id.toString()}\" - could not find execution context for ${envId}`\n );\n return noopResult;\n }\n\n // add / remove / etc\n updater(executionRef);\n\n await this.updateLinkFiles(executionRef.currentComponents, executionRef.executionCtx);\n\n return noopResult;\n };\n\n private handleComponentRemoval = (cId: ComponentID) => {\n let component: Component | undefined;\n this.executionRefs.forEach((components) => {\n const found = components.get(cId);\n if (found) component = found;\n });\n if (!component) return Promise.resolve(noopResult);\n\n return this.handleComponentChange(component, (currentComponents) => currentComponents.remove(cId));\n };\n\n getEnvPreviewConfig(env?: PreviewEnv): EnvPreviewConfig {\n const config = env?.getPreviewConfig && typeof env?.getPreviewConfig === 'function' ? env?.getPreviewConfig() : {};\n\n return config;\n }\n\n /**\n * return the configured bundling strategy.\n */\n getBundlingStrategy(env?: PreviewEnv): BundlingStrategy {\n const defaultStrategies = this.getDefaultStrategies();\n const envPreviewConfig = this.getEnvPreviewConfig(env);\n const strategyFromEnv = envPreviewConfig?.strategyName;\n const strategyName = strategyFromEnv || this.config.bundlingStrategy || 'env';\n const strategies = this.bundlingStrategySlot.values().concat(defaultStrategies);\n const selected = strategies.find((strategy) => {\n return strategy.name === strategyName;\n });\n\n if (!selected) throw new BundlingStrategyNotFound(strategyName);\n\n return selected;\n }\n\n /**\n * register a new bundling strategy. default available strategies are `env` and ``\n */\n registerBundlingStrategy(bundlingStrategy: BundlingStrategy) {\n this.bundlingStrategySlot.register(bundlingStrategy);\n return this;\n }\n\n /**\n * register a new preview definition.\n */\n registerDefinition(previewDef: PreviewDefinition) {\n this.previewSlot.register(previewDef);\n }\n\n static slots = [Slot.withType<PreviewDefinition>(), Slot.withType<BundlingStrategy>()];\n\n static runtime = MainRuntime;\n static dependencies = [\n BundlerAspect,\n BuilderAspect,\n ComponentAspect,\n UIAspect,\n EnvsAspect,\n WorkspaceAspect,\n PkgAspect,\n PubsubAspect,\n AspectLoaderAspect,\n LoggerAspect,\n DependencyResolverAspect,\n GraphqlAspect,\n ];\n\n static defaultConfig = {\n disabled: false,\n };\n\n static async provider(\n // eslint-disable-next-line max-len\n [\n bundler,\n builder,\n componentExtension,\n uiMain,\n envs,\n workspace,\n pkg,\n pubsub,\n aspectLoader,\n loggerMain,\n dependencyResolver,\n graphql,\n ]: [\n BundlerMain,\n BuilderMain,\n ComponentMain,\n UiMain,\n EnvsMain,\n Workspace | undefined,\n PkgMain,\n PubsubMain,\n AspectLoaderMain,\n LoggerMain,\n DependencyResolverMain,\n GraphqlMain\n ],\n config: PreviewConfig,\n [previewSlot, bundlingStrategySlot]: [PreviewDefinitionRegistry, BundlingStrategySlot],\n harmony: Harmony\n ) {\n const logger = loggerMain.createLogger(PreviewAspect.id);\n // app.registerApp(new PreviewApp());\n const preview = new PreviewMain(\n harmony,\n previewSlot,\n uiMain,\n envs,\n componentExtension,\n pkg,\n aspectLoader,\n config,\n bundlingStrategySlot,\n builder,\n workspace,\n logger,\n dependencyResolver\n );\n\n if (workspace) uiMain.registerStartPlugin(new PreviewStartPlugin(workspace, bundler, uiMain, pubsub, logger));\n\n componentExtension.registerRoute([\n new PreviewRoute(preview, logger),\n new ComponentPreviewRoute(preview, logger),\n // @ts-ignore\n new EnvTemplateRoute(preview, logger),\n new PreviewAssetsRoute(preview, logger),\n ]);\n\n bundler.registerTarget([\n {\n entry: preview.getPreviewTarget.bind(preview),\n },\n ]);\n\n if (!config.disabled)\n builder.registerBuildTasks([\n new EnvPreviewTemplateTask(preview, envs, aspectLoader, dependencyResolver, logger),\n new PreviewTask(bundler, preview, dependencyResolver, logger),\n ]);\n\n if (workspace) {\n workspace.registerOnComponentAdd((c) =>\n preview.handleComponentChange(c, (currentComponents) => currentComponents.add(c))\n );\n workspace.onComponentLoad(async () => {\n return {\n // used for backward compatibility. can be removed in the future.\n scaling: true\n };\n });\n workspace.registerOnComponentChange((c) =>\n preview.handleComponentChange(c, (currentComponents) => currentComponents.update(c))\n );\n workspace.registerOnComponentRemove((cId) => preview.handleComponentRemoval(cId));\n }\n\n graphql.register(previewSchema(preview));\n\n return preview;\n }\n}\n\nPreviewAspect.addRuntime(PreviewMain);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;A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B,CAACwM,GAAlB,CAAsBlN,CAAtB,CAAxD,CADF;MAGAN,SAAS,CAACyN,eAAV,CAA0B,YAAY;QACpC,OAAO;UACL;UACAvK,OAAO,EAAE;QAFJ,CAAP;MAID,CALD;MAMAlD,SAAS,CAAC0N,yBAAV,CAAqCpN,CAAD,IAClCkM,OAAO,CAAC/K,qBAAR,CAA8BnB,CAA9B,EAAkCU,iBAAD,IAAuBA,iBAAiB,CAAC2M,MAAlB,CAAyBrN,CAAzB,CAAxD,CADF;MAGAN,SAAS,CAAC4N,yBAAV,CAAqC1M,GAAD,IAASsL,OAAO,CAACqB,sBAAR,CAA+B3M,GAA/B,CAA7C;IACD;;IAEDoL,OAAO,CAACR,QAAR,CAAiB,IAAAgC,yBAAA,EAActB,OAAd,CAAjB;IAEA,OAAOA,OAAP;EACD;;AAphBsB;;;gCAAZpN,W,WAkaI,CAAC2O,eAAA,CAAKC,QAAL,EAAD,EAAqCD,eAAA,CAAKC,QAAL,EAArC,C;gCAlaJ5O,W,aAoaMuK,kB;gCApaNvK,W,kBAqaW,CACpB6O,wBADoB,EAEpBC,wBAFoB,EAGpBC,4BAHoB,EAIpBC,cAJoB,EAKpBC,kBALoB,EAMpBC,oBANoB,EAOpBC,gBAPoB,EAQpBC,sBARoB,EASpBC,kCAToB,EAUpBC,sBAVoB,EAWpBC,8CAXoB,EAYpBC,kBAZoB,C;gCAraXxP,W,mBAobY;EACrB+N,QAAQ,EAAE;AADW,C;;AAmGzBjO,wBAAA,CAAc2P,UAAd,CAAyBzP,WAAzB"}
@@ -41,6 +41,8 @@ export declare class PreviewPreview {
41
41
  * render the preview.
42
42
  */
43
43
  render: (rootExt?: string | undefined) => Promise<void>;
44
+ setViewport(): void;
45
+ reportSize(): void;
44
46
  getPreviewModule(previewName: string, id: ComponentID): Promise<PreviewModule>;
45
47
  fetchComponentPreview(id: ComponentID, name: string): Promise<Record<string, ModuleFile[]>>;
46
48
  private addComponentFileElement;
@@ -64,7 +66,8 @@ export declare class PreviewPreview {
64
66
  registerRenderContext(renderContext: RenderingContextProvider): this;
65
67
  getDefault(): string;
66
68
  private getPreview;
67
- private getParam;
69
+ getParam(query: string, param: string): string | null;
70
+ getQuery(): string;
68
71
  private getLocation;
69
72
  static runtime: import("@teambit/harmony").RuntimeDefinition;
70
73
  static dependencies: import("@teambit/harmony").Aspect[];
@@ -81,6 +81,16 @@ function _memoizee() {
81
81
  return data;
82
82
  }
83
83
 
84
+ function _lodash() {
85
+ const data = require("lodash");
86
+
87
+ _lodash = function () {
88
+ return data;
89
+ };
90
+
91
+ return data;
92
+ }
93
+
84
94
  function _exceptions() {
85
95
  const data = require("./exceptions");
86
96
 
@@ -151,6 +161,16 @@ function _htmlUtils() {
151
161
  return data;
152
162
  }
153
163
 
164
+ function _sizeEvent() {
165
+ const data = require("./size-event");
166
+
167
+ _sizeEvent = function () {
168
+ return data;
169
+ };
170
+
171
+ return data;
172
+ }
173
+
154
174
  // forward linkModules() for generate-link.ts
155
175
  class PreviewPreview {
156
176
  constructor(
@@ -179,6 +199,8 @@ class PreviewPreview {
179
199
  return this._setupPromise;
180
200
  });
181
201
  (0, _defineProperty2().default)(this, "render", async rootExt => {
202
+ // fit content always.
203
+ window.document.body.style.width = 'fit-content';
182
204
  const {
183
205
  previewName,
184
206
  componentId
@@ -202,7 +224,11 @@ class PreviewPreview {
202
224
  const includes = includesAll.filter(module => !!module); // during build / tag, the component is isolated, so all aspects are relevant, and do not require filtering
203
225
 
204
226
  const componentAspects = this.isDev ? await this.getComponentAspects(componentId.toString()) : undefined;
205
- return preview.render(componentId, await this.getPreviewModule(name, componentId), includes, this.getRenderingContext(componentAspects));
227
+ const previewModule = await this.getPreviewModule(name, componentId);
228
+ const render = preview.render(componentId, previewModule, includes, this.getRenderingContext(componentAspects));
229
+ this.reportSize();
230
+ this.setViewport();
231
+ return render;
206
232
  });
207
233
  (0, _defineProperty2().default)(this, "getComponentAspects", (0, _memoizee().default)(_fetchComponentAspects().fetchComponentAspects, {
208
234
  max: 100,
@@ -234,6 +260,48 @@ class PreviewPreview {
234
260
  return true;
235
261
  }
236
262
 
263
+ setViewport() {
264
+ const query = this.getQuery();
265
+ const viewPort = this.getParam(query, 'viewport');
266
+
267
+ if (!viewPort) {
268
+ window.document.body.style.width = '100%';
269
+ return;
270
+ }
271
+
272
+ window.document.body.style.maxWidth = `${viewPort}px`;
273
+ }
274
+
275
+ reportSize() {
276
+ var _window, _window2;
277
+
278
+ if (!((_window = window) !== null && _window !== void 0 && _window.parent) || !((_window2 = window) !== null && _window2 !== void 0 && _window2.document)) return; // TODO: discuss with gilad for a better way to resolve page loaded here.
279
+
280
+ const sendPubsubEvent = () => {
281
+ this.pubsub.pub(_preview().PreviewAspect.id, new (_sizeEvent().SizeEvent)({
282
+ width: window.document.body.offsetWidth,
283
+ height: window.document.body.offsetHeight
284
+ }));
285
+ };
286
+
287
+ window.addEventListener('resize', (0, _lodash().debounce)(sendPubsubEvent, 150));
288
+ let counter = 0;
289
+ const interval = setInterval(() => {
290
+ // TODO: think
291
+ counter += 1;
292
+
293
+ if (counter > 10) {
294
+ clearInterval(interval);
295
+ return;
296
+ }
297
+
298
+ this.pubsub.pub(_preview().PreviewAspect.id, new (_sizeEvent().SizeEvent)({
299
+ width: window.document.body.offsetWidth,
300
+ height: window.document.body.offsetHeight
301
+ }));
302
+ }, 200);
303
+ }
304
+
237
305
  async getPreviewModule(previewName, id) {
238
306
  const compShortId = id.fullName;
239
307
 
@@ -385,6 +453,12 @@ class PreviewPreview {
385
453
  return params.get(param);
386
454
  }
387
455
 
456
+ getQuery() {
457
+ const withoutHash = window.location.hash.substring(1);
458
+ const [, after] = withoutHash.split('?');
459
+ return after;
460
+ }
461
+
388
462
  getLocation() {
389
463
  const withoutHash = window.location.hash.substring(1);
390
464
  const [before, after] = withoutHash.split('?');
@@ -1 +1 @@
1
- {"version":3,"names":["PreviewPreview","constructor","pubsub","previewSlot","renderingContextSlot","isReady","Promise","resolve","_setupPromise","PREVIEW_MODULES","onSet","add","rootExt","previewName","componentId","getLocation","name","getDefault","isDev","preview","getPreview","PreviewNotFound","includesAll","all","include","map","inclPreviewName","includedPreview","undefined","inclPreviewModule","getPreviewModule","selectPreviewModel","fullName","includes","filter","module","componentAspects","getComponentAspects","toString","render","getRenderingContext","memoize","fetchComponentAspects","max","maxAge","registerClickPubSub","window","addEventListener","e","timestamp","Date","now","clickEvent","Object","assign","pub","PreviewAspect","id","ClickInsideAnIframeEvent","has","includedReady","every","included","compShortId","relevantModel","get","Error","componentMap","componentPreviews","fetchComponentPreview","loadComponentPreviews","component","mainModule","previewFile","allFiles","fetchComponentPreviewFiles","file","endsWith","addComponentFileElement","loadPreviewScript","previewBundleFileName","addComponentFileScriptElement","addComponentFileLinkElement","catch","err","previewAssetsRoute","stringId","url","res","crossFetch","status","parsed","json","isBundledWithEnv","files","length","previewRoute","src","loadScript","href","loadLink","globalId","toStringWithoutVersion","componentPreview","registerPreview","register","aspectsFilter","RenderingContext","registerRenderContext","renderContext","previews","values","defaultOne","find","previewCandidate","default","getParam","query","param","params","URLSearchParams","withoutHash","location","hash","substring","before","after","split","ComponentID","tryFromString","provider","config","PreviewRuntime","PubsubAspect","Slot","withType","addRuntime"],"sources":["preview.preview.runtime.tsx"],"sourcesContent":["import PubsubAspect, { PubsubPreview } from '@teambit/pubsub';\nimport { Slot, SlotRegistry } from '@teambit/harmony';\nimport { ComponentID } from '@teambit/component-id';\nimport crossFetch from 'cross-fetch';\nimport memoize from 'memoizee';\n\nimport { PreviewNotFound } from './exceptions';\nimport { PreviewType } from './preview-type';\nimport { PreviewAspect, PreviewRuntime } from './preview.aspect';\nimport { ClickInsideAnIframeEvent } from './events';\nimport { ModuleFile, PreviewModule } from './types/preview-module';\nimport { RenderingContext } from './rendering-context';\nimport { fetchComponentAspects } from './gql/fetch-component-aspects';\nimport { PREVIEW_MODULES } from './preview-modules';\nimport { loadScript, loadLink } from './html-utils';\n\n// forward linkModules() for generate-link.ts\nexport { linkModules } from './preview-modules';\n\nexport type PreviewSlot = SlotRegistry<PreviewType>;\n\nexport type RenderingContextOptions = { aspectsFilter?: string[] };\nexport type RenderingContextProvider = (options: RenderingContextOptions) => { [key: string]: any };\nexport type RenderingContextSlot = SlotRegistry<RenderingContextProvider>;\n\nexport class PreviewPreview {\n constructor(\n /**\n * register to pubsub\n */\n private pubsub: PubsubPreview,\n\n /**\n * preview slot.\n */\n private previewSlot: PreviewSlot,\n\n private renderingContextSlot: RenderingContextSlot\n ) {\n this.registerClickPubSub();\n }\n\n private registerClickPubSub() {\n window.addEventListener('click', (e) => {\n const timestamp = Date.now();\n const clickEvent = Object.assign({}, e);\n this.pubsub.pub(PreviewAspect.id, new ClickInsideAnIframeEvent(timestamp, clickEvent));\n });\n }\n\n private isDev = false;\n\n private isReady() {\n const { previewName } = this.getLocation();\n const name = previewName || this.getDefault();\n\n if (!PREVIEW_MODULES.has(name)) return false;\n const preview = this.getPreview(name);\n if (!preview) return false;\n const includedReady = preview.include?.every((included) => PREVIEW_MODULES.has(included)) ?? true;\n if (!includedReady) return false;\n\n return true;\n }\n\n private _setupPromise?: Promise<void>;\n setup = () => {\n if (this.isReady()) return Promise.resolve();\n\n this._setupPromise ??= new Promise((resolve) => {\n PREVIEW_MODULES.onSet.add(() => {\n if (this.isReady()) resolve();\n });\n });\n\n return this._setupPromise;\n };\n\n /**\n * render the preview.\n */\n render = async (rootExt?: string) => {\n const { previewName, componentId } = this.getLocation();\n const name = previewName || this.getDefault();\n if (rootExt) this.isDev = rootExt === 'teambit.workspace/workspace';\n\n const preview = this.getPreview(name);\n if (!preview || !componentId) {\n throw new PreviewNotFound(previewName);\n }\n\n const includesAll = await Promise.all(\n (preview.include || []).map(async (inclPreviewName) => {\n const includedPreview = this.getPreview(inclPreviewName);\n if (!includedPreview) return undefined;\n\n const inclPreviewModule = await this.getPreviewModule(inclPreviewName, componentId);\n return includedPreview.selectPreviewModel?.(componentId.fullName, inclPreviewModule);\n })\n );\n\n const includes = includesAll.filter((module) => !!module);\n // during build / tag, the component is isolated, so all aspects are relevant, and do not require filtering\n const componentAspects = this.isDev ? await this.getComponentAspects(componentId.toString()) : undefined;\n\n return preview.render(\n componentId,\n await this.getPreviewModule(name, componentId),\n includes,\n this.getRenderingContext(componentAspects)\n );\n };\n\n async getPreviewModule(previewName: string, id: ComponentID): Promise<PreviewModule> {\n const compShortId = id.fullName;\n\n const relevantModel = PREVIEW_MODULES.get(previewName);\n if (!relevantModel) throw new Error(`[preview.preview] missing preview \"${previewName}\"`);\n if (relevantModel.componentMap[compShortId]) return relevantModel;\n\n const componentPreviews = await this.fetchComponentPreview(id, previewName);\n PREVIEW_MODULES.loadComponentPreviews(compShortId, componentPreviews);\n\n const component = componentPreviews[previewName];\n\n return {\n mainModule: relevantModel.mainModule,\n componentMap: {\n [id.fullName]: component,\n },\n };\n }\n\n async fetchComponentPreview(id: ComponentID, name: string): Promise<Record<string, ModuleFile[]>> {\n let previewFile: string | undefined;\n const allFiles = await this.fetchComponentPreviewFiles(id, name);\n // It's a component bundled with the env\n if (allFiles === null) return {};\n\n await Promise.all(\n allFiles.map((file) => {\n // We want to run the preview file always last\n if (file.endsWith('-preview.js')) {\n previewFile = file;\n return undefined;\n }\n\n return this.addComponentFileElement(id, file);\n })\n );\n\n if (!previewFile) return {};\n return this.loadPreviewScript(id, name, previewFile);\n }\n\n private addComponentFileElement(id: ComponentID, previewBundleFileName: string) {\n if (previewBundleFileName.endsWith('.js')) {\n return this.addComponentFileScriptElement(id, previewBundleFileName);\n }\n\n // TODO - should we load assets other than .css / .js?\n // if (previewBundleFileName.endsWith('.css')) {\n this.addComponentFileLinkElement(id, previewBundleFileName).catch((err) => {\n throw new Error(\n `[preview.preview] failed loading asset \"${previewBundleFileName}\". Error - \"${err?.toString()}\"`\n );\n });\n\n // do NOT await non js assets, as they might never load (like images), and not critical for rendering.\n return undefined;\n }\n\n private async fetchComponentPreviewFiles(id: ComponentID, previewName: string): Promise<string[] | null> {\n const previewAssetsRoute = `~aspect/preview-assets`;\n const stringId = id.toString();\n const url = `/api/${stringId}/${previewAssetsRoute}`;\n\n const res = await crossFetch(url);\n if (res.status >= 400) {\n throw new PreviewNotFound(previewName);\n }\n const parsed = await res.json();\n // This is component bundled with the env, no reason to bring the files, as they will be the files of the env\n if (parsed.isBundledWithEnv) {\n return null;\n }\n if (!parsed.files || !parsed.files.length) {\n throw new PreviewNotFound(previewName);\n }\n return parsed.files;\n }\n\n private addComponentFileScriptElement(id: ComponentID, previewBundleFileName: string) {\n const previewRoute = `~aspect/component-preview`;\n const stringId = id.toString();\n const src = `/api/${stringId}/${previewRoute}/${previewBundleFileName}`;\n return loadScript({ src });\n }\n\n private addComponentFileLinkElement(id: ComponentID, previewBundleFileName: string) {\n const stringId = id.toString();\n const previewRoute = `~aspect/component-preview`;\n const href = `/api/${stringId}/${previewRoute}/${previewBundleFileName}`;\n return loadLink({ href });\n }\n\n private async loadPreviewScript(id: ComponentID, previewName: string, previewBundleFileName: string) {\n const previewRoute = `~aspect/component-preview`;\n const src = `/api/${id.toString()}/${previewRoute}/${previewBundleFileName}`;\n await loadScript({ src });\n\n // TODO - replace with jsonp\n const globalId = `${id.toStringWithoutVersion()}-preview`;\n const componentPreview = window[globalId];\n if (!componentPreview) throw new PreviewNotFound(previewName);\n\n return componentPreview as Record<string, ModuleFile[]>;\n }\n\n private getComponentAspects = memoize(fetchComponentAspects, {\n max: 100,\n maxAge: 12 * 60 * 60 * 1000,\n });\n\n /**\n * register a new preview.\n */\n registerPreview(preview: PreviewType) {\n this.previewSlot.register(preview);\n return this;\n }\n\n /**\n * get the preview rendering context.\n */\n getRenderingContext(aspectsFilter?: string[]) {\n return new RenderingContext(this.renderingContextSlot, { aspectsFilter });\n }\n\n /**\n * allows aspects to add rendering contexts.\n * render context is available through all preview definitions.\n */\n registerRenderContext(renderContext: RenderingContextProvider) {\n this.renderingContextSlot.register(renderContext);\n return this;\n }\n\n getDefault() {\n const previews = this.previewSlot.values();\n const defaultOne = previews.find((previewCandidate) => previewCandidate.default);\n\n return defaultOne?.name || previews[0].name;\n }\n\n private getPreview(previewName: string): undefined | PreviewType {\n const previews = this.previewSlot.values();\n const preview = previews.find((previewCandidate) => previewCandidate.name === previewName);\n\n return preview;\n }\n\n private getParam(query: string, param: string) {\n const params = new URLSearchParams(query);\n return params.get(param);\n }\n\n private getLocation() {\n const withoutHash = window.location.hash.substring(1);\n const [before, after] = withoutHash.split('?');\n\n return {\n previewName: this.getParam(after, 'preview'),\n componentId: ComponentID.tryFromString(before),\n };\n }\n\n static runtime = PreviewRuntime;\n\n static dependencies = [PubsubAspect];\n\n static slots = [Slot.withType<PreviewType>(), Slot.withType<RenderingContextProvider>()];\n\n static async provider(\n [pubsub]: [PubsubPreview],\n config,\n [previewSlot, renderingContextSlot]: [PreviewSlot, RenderingContextSlot]\n ) {\n const preview = new PreviewPreview(pubsub, previewSlot, renderingContextSlot);\n\n window.addEventListener('hashchange', () => {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n preview.render();\n });\n\n return preview;\n }\n}\n\nPreviewAspect.addRuntime(PreviewPreview);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;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d,CAAyBxI,cAAzB"}
1
+ {"version":3,"names":["PreviewPreview","constructor","pubsub","previewSlot","renderingContextSlot","isReady","Promise","resolve","_setupPromise","PREVIEW_MODULES","onSet","add","rootExt","window","document","body","style","width","previewName","componentId","getLocation","name","getDefault","isDev","preview","getPreview","PreviewNotFound","includesAll","all","include","map","inclPreviewName","includedPreview","undefined","inclPreviewModule","getPreviewModule","selectPreviewModel","fullName","includes","filter","module","componentAspects","getComponentAspects","toString","previewModule","render","getRenderingContext","reportSize","setViewport","memoize","fetchComponentAspects","max","maxAge","registerClickPubSub","addEventListener","e","timestamp","Date","now","clickEvent","Object","assign","pub","PreviewAspect","id","ClickInsideAnIframeEvent","has","includedReady","every","included","query","getQuery","viewPort","getParam","maxWidth","parent","sendPubsubEvent","SizeEvent","offsetWidth","height","offsetHeight","debounce","counter","interval","setInterval","clearInterval","compShortId","relevantModel","get","Error","componentMap","componentPreviews","fetchComponentPreview","loadComponentPreviews","component","mainModule","previewFile","allFiles","fetchComponentPreviewFiles","file","endsWith","addComponentFileElement","loadPreviewScript","previewBundleFileName","addComponentFileScriptElement","addComponentFileLinkElement","catch","err","previewAssetsRoute","stringId","url","res","crossFetch","status","parsed","json","isBundledWithEnv","files","length","previewRoute","src","loadScript","href","loadLink","globalId","toStringWithoutVersion","componentPreview","registerPreview","register","aspectsFilter","RenderingContext","registerRenderContext","renderContext","previews","values","defaultOne","find","previewCandidate","default","param","params","URLSearchParams","withoutHash","location","hash","substring","after","split","before","ComponentID","tryFromString","provider","config","PreviewRuntime","PubsubAspect","Slot","withType","addRuntime"],"sources":["preview.preview.runtime.tsx"],"sourcesContent":["import PubsubAspect, { PubsubPreview } from '@teambit/pubsub';\nimport { Slot, SlotRegistry } from '@teambit/harmony';\nimport { ComponentID } from '@teambit/component-id';\nimport crossFetch from 'cross-fetch';\nimport memoize from 'memoizee';\nimport { debounce } from 'lodash';\n\nimport { PreviewNotFound } from './exceptions';\nimport { PreviewType } from './preview-type';\nimport { PreviewAspect, PreviewRuntime } from './preview.aspect';\nimport { ClickInsideAnIframeEvent } from './events';\nimport { ModuleFile, PreviewModule } from './types/preview-module';\nimport { RenderingContext } from './rendering-context';\nimport { fetchComponentAspects } from './gql/fetch-component-aspects';\nimport { PREVIEW_MODULES } from './preview-modules';\nimport { loadScript, loadLink } from './html-utils';\nimport { SizeEvent } from './size-event';\n\n// forward linkModules() for generate-link.ts\nexport { linkModules } from './preview-modules';\n\nexport type PreviewSlot = SlotRegistry<PreviewType>;\n\nexport type RenderingContextOptions = { aspectsFilter?: string[] };\nexport type RenderingContextProvider = (options: RenderingContextOptions) => { [key: string]: any };\nexport type RenderingContextSlot = SlotRegistry<RenderingContextProvider>;\n\nexport class PreviewPreview {\n constructor(\n /**\n * register to pubsub\n */\n private pubsub: PubsubPreview,\n\n /**\n * preview slot.\n */\n private previewSlot: PreviewSlot,\n\n private renderingContextSlot: RenderingContextSlot\n ) {\n this.registerClickPubSub();\n }\n\n private registerClickPubSub() {\n window.addEventListener('click', (e) => {\n const timestamp = Date.now();\n const clickEvent = Object.assign({}, e);\n this.pubsub.pub(PreviewAspect.id, new ClickInsideAnIframeEvent(timestamp, clickEvent));\n });\n }\n\n private isDev = false;\n\n private isReady() {\n const { previewName } = this.getLocation();\n const name = previewName || this.getDefault();\n\n if (!PREVIEW_MODULES.has(name)) return false;\n const preview = this.getPreview(name);\n if (!preview) return false;\n const includedReady = preview.include?.every((included) => PREVIEW_MODULES.has(included)) ?? true;\n if (!includedReady) return false;\n\n return true;\n }\n\n private _setupPromise?: Promise<void>;\n setup = () => {\n if (this.isReady()) return Promise.resolve();\n\n this._setupPromise ??= new Promise((resolve) => {\n PREVIEW_MODULES.onSet.add(() => {\n if (this.isReady()) resolve();\n });\n });\n\n return this._setupPromise;\n };\n\n /**\n * render the preview.\n */\n render = async (rootExt?: string) => {\n // fit content always.\n window.document.body.style.width = 'fit-content';\n\n const { previewName, componentId } = this.getLocation();\n const name = previewName || this.getDefault();\n if (rootExt) this.isDev = rootExt === 'teambit.workspace/workspace';\n\n const preview = this.getPreview(name);\n if (!preview || !componentId) {\n throw new PreviewNotFound(previewName);\n }\n\n const includesAll = await Promise.all(\n (preview.include || []).map(async (inclPreviewName) => {\n const includedPreview = this.getPreview(inclPreviewName);\n if (!includedPreview) return undefined;\n\n const inclPreviewModule = await this.getPreviewModule(inclPreviewName, componentId);\n return includedPreview.selectPreviewModel?.(componentId.fullName, inclPreviewModule);\n })\n );\n\n const includes = includesAll.filter((module) => !!module);\n // during build / tag, the component is isolated, so all aspects are relevant, and do not require filtering\n const componentAspects = this.isDev ? await this.getComponentAspects(componentId.toString()) : undefined;\n const previewModule = await this.getPreviewModule(name, componentId);\n const render = preview.render(\n componentId,\n previewModule,\n includes,\n this.getRenderingContext(componentAspects)\n );\n\n this.reportSize();\n this.setViewport();\n return render;\n };\n\n setViewport() {\n const query = this.getQuery();\n const viewPort = this.getParam(query, 'viewport');\n if (!viewPort) {\n window.document.body.style.width = '100%';\n return;\n }\n\n window.document.body.style.maxWidth = `${viewPort}px`;\n }\n\n reportSize() {\n if (!window?.parent || !window?.document) return;\n // TODO: discuss with gilad for a better way to resolve page loaded here.\n\n const sendPubsubEvent = () => {\n this.pubsub.pub(PreviewAspect.id, new SizeEvent({\n width: window.document.body.offsetWidth,\n height: window.document.body.offsetHeight\n })); \n }\n\n window.addEventListener('resize', debounce(sendPubsubEvent, 150));\n \n let counter = 0;\n const interval = setInterval(() => {\n // TODO: think\n counter += 1;\n if (counter > 10) {\n clearInterval(interval);\n return;\n }\n this.pubsub.pub(PreviewAspect.id, new SizeEvent({\n width: window.document.body.offsetWidth,\n height: window.document.body.offsetHeight\n })); \n }, 200);\n }\n\n async getPreviewModule(previewName: string, id: ComponentID): Promise<PreviewModule> {\n const compShortId = id.fullName;\n\n const relevantModel = PREVIEW_MODULES.get(previewName);\n if (!relevantModel) throw new Error(`[preview.preview] missing preview \"${previewName}\"`);\n if (relevantModel.componentMap[compShortId]) return relevantModel;\n\n const componentPreviews = await this.fetchComponentPreview(id, previewName);\n PREVIEW_MODULES.loadComponentPreviews(compShortId, componentPreviews);\n\n const component = componentPreviews[previewName];\n\n return {\n mainModule: relevantModel.mainModule,\n componentMap: {\n [id.fullName]: component,\n },\n };\n }\n\n async fetchComponentPreview(id: ComponentID, name: string): Promise<Record<string, ModuleFile[]>> {\n let previewFile: string | undefined;\n const allFiles = await this.fetchComponentPreviewFiles(id, name);\n // It's a component bundled with the env\n if (allFiles === null) return {};\n\n await Promise.all(\n allFiles.map((file) => {\n // We want to run the preview file always last\n if (file.endsWith('-preview.js')) {\n previewFile = file;\n return undefined;\n }\n\n return this.addComponentFileElement(id, file);\n })\n );\n\n if (!previewFile) return {};\n return this.loadPreviewScript(id, name, previewFile);\n }\n\n private addComponentFileElement(id: ComponentID, previewBundleFileName: string) {\n if (previewBundleFileName.endsWith('.js')) {\n return this.addComponentFileScriptElement(id, previewBundleFileName);\n }\n\n // TODO - should we load assets other than .css / .js?\n // if (previewBundleFileName.endsWith('.css')) {\n this.addComponentFileLinkElement(id, previewBundleFileName).catch((err) => {\n throw new Error(\n `[preview.preview] failed loading asset \"${previewBundleFileName}\". Error - \"${err?.toString()}\"`\n );\n });\n\n // do NOT await non js assets, as they might never load (like images), and not critical for rendering.\n return undefined;\n }\n\n private async fetchComponentPreviewFiles(id: ComponentID, previewName: string): Promise<string[] | null> {\n const previewAssetsRoute = `~aspect/preview-assets`;\n const stringId = id.toString();\n const url = `/api/${stringId}/${previewAssetsRoute}`;\n\n const res = await crossFetch(url);\n if (res.status >= 400) {\n throw new PreviewNotFound(previewName);\n }\n const parsed = await res.json();\n // This is component bundled with the env, no reason to bring the files, as they will be the files of the env\n if (parsed.isBundledWithEnv) {\n return null;\n }\n if (!parsed.files || !parsed.files.length) {\n throw new PreviewNotFound(previewName);\n }\n return parsed.files;\n }\n\n private addComponentFileScriptElement(id: ComponentID, previewBundleFileName: string) {\n const previewRoute = `~aspect/component-preview`;\n const stringId = id.toString();\n const src = `/api/${stringId}/${previewRoute}/${previewBundleFileName}`;\n return loadScript({ src });\n }\n\n private addComponentFileLinkElement(id: ComponentID, previewBundleFileName: string) {\n const stringId = id.toString();\n const previewRoute = `~aspect/component-preview`;\n const href = `/api/${stringId}/${previewRoute}/${previewBundleFileName}`;\n return loadLink({ href });\n }\n\n private async loadPreviewScript(id: ComponentID, previewName: string, previewBundleFileName: string) {\n const previewRoute = `~aspect/component-preview`;\n const src = `/api/${id.toString()}/${previewRoute}/${previewBundleFileName}`;\n await loadScript({ src });\n\n // TODO - replace with jsonp\n const globalId = `${id.toStringWithoutVersion()}-preview`;\n const componentPreview = window[globalId];\n if (!componentPreview) throw new PreviewNotFound(previewName);\n\n return componentPreview as Record<string, ModuleFile[]>;\n }\n\n private getComponentAspects = memoize(fetchComponentAspects, {\n max: 100,\n maxAge: 12 * 60 * 60 * 1000,\n });\n\n /**\n * register a new preview.\n */\n registerPreview(preview: PreviewType) {\n this.previewSlot.register(preview);\n return this;\n }\n\n /**\n * get the preview rendering context.\n */\n getRenderingContext(aspectsFilter?: string[]) {\n return new RenderingContext(this.renderingContextSlot, { aspectsFilter });\n }\n\n /**\n * allows aspects to add rendering contexts.\n * render context is available through all preview definitions.\n */\n registerRenderContext(renderContext: RenderingContextProvider) {\n this.renderingContextSlot.register(renderContext);\n return this;\n }\n\n getDefault() {\n const previews = this.previewSlot.values();\n const defaultOne = previews.find((previewCandidate) => previewCandidate.default);\n\n return defaultOne?.name || previews[0].name;\n }\n\n private getPreview(previewName: string): undefined | PreviewType {\n const previews = this.previewSlot.values();\n const preview = previews.find((previewCandidate) => previewCandidate.name === previewName);\n\n return preview;\n }\n\n getParam(query: string, param: string) {\n const params = new URLSearchParams(query);\n return params.get(param);\n }\n\n getQuery() {\n const withoutHash = window.location.hash.substring(1);\n const [, after] = withoutHash.split('?');\n return after;\n }\n\n private getLocation() {\n const withoutHash = window.location.hash.substring(1);\n const [before, after] = withoutHash.split('?');\n\n return {\n previewName: this.getParam(after, 'preview'),\n componentId: ComponentID.tryFromString(before),\n };\n }\n\n static runtime = PreviewRuntime;\n\n static dependencies = [PubsubAspect];\n\n static slots = [Slot.withType<PreviewType>(), Slot.withType<RenderingContextProvider>()];\n\n static async provider(\n [pubsub]: [PubsubPreview],\n config,\n [previewSlot, renderingContextSlot]: [PreviewSlot, RenderingContextSlot]\n ) {\n const preview = new PreviewPreview(pubsub, previewSlot, renderingContextSlot);\n\n window.addEventListener('hashchange', () => {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n preview.render();\n });\n\n return preview;\n }\n}\n\nPreviewAspect.addRuntime(PreviewPreview);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;AASO,MAAMA,cAAN,CAAqB;EAC1BC,WAAW;EACT;AACJ;AACA;EACYC,MAJC;EAMT;AACJ;AACA;EACYC,WATC,EAWDC,oBAXC,EAYT;IAAA,KARQF,MAQR,GARQA,MAQR;IAAA,KAHQC,WAGR,GAHQA,WAGR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AAIxB,cAAJ,CAAmBE,MAAnB,EAA2BC,WAA3B,EAAwCC,oBAAxC,CAAhB;IAEAS,MAAM,CAACyC,gBAAP,CAAwB,YAAxB,EAAsC,MAAM;MAC1C;MACA9B,OAAO,CAACqB,MAAR;IACD,CAHD;IAKA,OAAOrB,OAAP;EACD;;AAnUyB;;;gCAAfxB,c,aAgTMyJ,yB;gCAhTNzJ,c,kBAkTW,CAAC0J,iBAAD,C;gCAlTX1J,c,WAoTI,CAAC2J,eAAA,CAAKC,QAAL,EAAD,EAA+BD,eAAA,CAAKC,QAAL,EAA/B,C;;AAkBjB7F,wBAAA,CAAc8F,UAAd,CAAyB7J,cAAzB"}
@@ -0,0 +1,9 @@
1
+ import { BitBaseEvent } from "@teambit/pubsub";
2
+ export declare type SizeEventType = {
3
+ height: number;
4
+ width: number;
5
+ };
6
+ export declare class SizeEvent extends BitBaseEvent<SizeEventType> {
7
+ static readonly TYPE = "preview-size";
8
+ constructor(sizeEvent: SizeEventType);
9
+ }
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+
5
+ Object.defineProperty(exports, "__esModule", {
6
+ value: true
7
+ });
8
+ exports.SizeEvent = void 0;
9
+
10
+ function _defineProperty2() {
11
+ const data = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
12
+
13
+ _defineProperty2 = function () {
14
+ return data;
15
+ };
16
+
17
+ return data;
18
+ }
19
+
20
+ function _pubsub() {
21
+ const data = require("@teambit/pubsub");
22
+
23
+ _pubsub = function () {
24
+ return data;
25
+ };
26
+
27
+ return data;
28
+ }
29
+
30
+ class SizeEvent extends _pubsub().BitBaseEvent {
31
+ constructor(sizeEvent) {
32
+ super(SizeEvent.TYPE, '0.0.1', new Date().getTime(), sizeEvent);
33
+ }
34
+
35
+ }
36
+
37
+ exports.SizeEvent = SizeEvent;
38
+ (0, _defineProperty2().default)(SizeEvent, "TYPE", 'preview-size');
39
+
40
+ //# sourceMappingURL=size-event.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["SizeEvent","BitBaseEvent","constructor","sizeEvent","TYPE","Date","getTime"],"sources":["size-event.ts"],"sourcesContent":["import { BitBaseEvent } from \"@teambit/pubsub\";\n\nexport type SizeEventType = {\n height: number,\n width: number\n};\n\nexport class SizeEvent extends BitBaseEvent<SizeEventType> {\n static readonly TYPE = 'preview-size';\n\n constructor(sizeEvent: SizeEventType) {\n super(\n SizeEvent.TYPE,\n '0.0.1',\n new Date().getTime(),\n sizeEvent\n );\n }\n}"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAOO,MAAMA,SAAN,SAAwBC,sBAAxB,CAAoD;EAGzDC,WAAW,CAACC,SAAD,EAA2B;IACpC,MACEH,SAAS,CAACI,IADZ,EAEE,OAFF,EAGE,IAAIC,IAAJ,GAAWC,OAAX,EAHF,EAIEH,SAJF;EAMD;;AAVwD;;;gCAA9CH,S,UACY,c"}
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@teambit/preview",
3
- "version": "0.0.844",
3
+ "version": "0.0.847",
4
4
  "homepage": "https://bit.dev/teambit/preview/preview",
5
5
  "main": "dist/index.js",
6
6
  "componentId": {
7
7
  "scope": "teambit.preview",
8
8
  "name": "preview",
9
- "version": "0.0.844"
9
+ "version": "0.0.847"
10
10
  },
11
11
  "dependencies": {
12
12
  "mime": "2.5.2",
@@ -22,29 +22,30 @@
22
22
  "graphql-request": "3.4.0",
23
23
  "@babel/runtime": "7.12.18",
24
24
  "core-js": "^3.0.0",
25
- "@teambit/harmony": "0.3.3",
26
- "@teambit/express": "0.0.661",
27
- "@teambit/logger": "0.0.656",
28
- "@teambit/ui-foundation.ui.pages.static-error": "0.0.81",
29
- "@teambit/builder": "0.0.844",
30
- "@teambit/bundler": "0.0.844",
31
- "@teambit/component": "0.0.844",
32
- "@teambit/aspect-loader": "0.0.844",
33
- "@teambit/cli": "0.0.563",
34
- "@teambit/dependency-resolver": "0.0.844",
35
- "@teambit/envs": "0.0.844",
25
+ "@teambit/express": "0.0.663",
26
+ "@teambit/logger": "0.0.658",
27
+ "@teambit/ui-foundation.ui.pages.static-error": "0.0.82",
28
+ "@teambit/builder": "0.0.847",
29
+ "@teambit/bundler": "0.0.847",
30
+ "@teambit/component": "0.0.847",
31
+ "@teambit/preview.ui.component-preview": "0.0.501",
32
+ "@teambit/aspect-loader": "0.0.847",
33
+ "@teambit/cli": "0.0.565",
34
+ "@teambit/dependency-resolver": "0.0.847",
35
+ "@teambit/envs": "0.0.847",
36
36
  "@teambit/toolbox.path.to-windows-compatible-path": "0.0.489",
37
37
  "@teambit/component-id": "0.0.417",
38
+ "@teambit/harmony": "0.3.3",
38
39
  "@teambit/bit-error": "0.0.400",
39
- "@teambit/graphql": "0.0.844",
40
- "@teambit/pkg": "0.0.844",
41
- "@teambit/pubsub": "0.0.844",
42
- "@teambit/ui": "0.0.844",
43
- "@teambit/workspace": "0.0.844",
44
- "@teambit/compiler": "0.0.844",
40
+ "@teambit/graphql": "0.0.847",
41
+ "@teambit/pkg": "0.0.847",
42
+ "@teambit/pubsub": "0.0.847",
43
+ "@teambit/ui": "0.0.847",
44
+ "@teambit/workspace": "0.0.847",
45
+ "@teambit/compiler": "0.0.847",
45
46
  "@teambit/preview.cli.preview-server-status": "0.0.498",
46
47
  "@teambit/preview.cli.webpack-events-listener": "0.0.167",
47
- "@teambit/isolator": "0.0.844"
48
+ "@teambit/isolator": "0.0.847"
48
49
  },
49
50
  "devDependencies": {
50
51
  "@types/mime": "2.0.3",
@@ -62,7 +63,7 @@
62
63
  "@teambit/preview.aspect-docs.preview": "0.0.145"
63
64
  },
64
65
  "peerDependencies": {
65
- "@teambit/legacy": "1.0.344",
66
+ "@teambit/legacy": "1.0.346",
66
67
  "react-dom": "^16.8.0 || ^17.0.0",
67
68
  "react": "^16.8.0 || ^17.0.0"
68
69
  },
@@ -1,5 +1,5 @@
1
- import * as compositions_0 from '/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.preview_preview@0.0.844/dist/preview.composition.js';
2
- import * as overview_0 from '/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.preview_preview@0.0.844/dist/preview.docs.mdx';
1
+ import * as compositions_0 from '/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.preview_preview@0.0.847/dist/preview.composition.js';
2
+ import * as overview_0 from '/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.preview_preview@0.0.847/dist/preview.docs.mdx';
3
3
 
4
4
  export const compositions = [compositions_0];
5
5
  export const overview = [overview_0];
@@ -192,6 +192,14 @@ export class PreviewMain {
192
192
  return false;
193
193
  }
194
194
 
195
+ /**
196
+ * can the current component preview scale in size for different preview sizes.
197
+ */
198
+ async isScaling(component: Component): Promise<boolean> {
199
+ const previewData = component.state.aspects.get(PreviewAspect.id)?.data;
200
+ return previewData?.scaling;
201
+ }
202
+
195
203
  /**
196
204
  * Check if the component preview bundle contain the header inside of it (legacy)
197
205
  * today we are not including the header inside anymore
@@ -613,6 +621,12 @@ export class PreviewMain {
613
621
  workspace.registerOnComponentAdd((c) =>
614
622
  preview.handleComponentChange(c, (currentComponents) => currentComponents.add(c))
615
623
  );
624
+ workspace.onComponentLoad(async () => {
625
+ return {
626
+ // used for backward compatibility. can be removed in the future.
627
+ scaling: true
628
+ };
629
+ });
616
630
  workspace.registerOnComponentChange((c) =>
617
631
  preview.handleComponentChange(c, (currentComponents) => currentComponents.update(c))
618
632
  );
@@ -3,6 +3,7 @@ import { Slot, SlotRegistry } from '@teambit/harmony';
3
3
  import { ComponentID } from '@teambit/component-id';
4
4
  import crossFetch from 'cross-fetch';
5
5
  import memoize from 'memoizee';
6
+ import { debounce } from 'lodash';
6
7
 
7
8
  import { PreviewNotFound } from './exceptions';
8
9
  import { PreviewType } from './preview-type';
@@ -13,6 +14,7 @@ import { RenderingContext } from './rendering-context';
13
14
  import { fetchComponentAspects } from './gql/fetch-component-aspects';
14
15
  import { PREVIEW_MODULES } from './preview-modules';
15
16
  import { loadScript, loadLink } from './html-utils';
17
+ import { SizeEvent } from './size-event';
16
18
 
17
19
  // forward linkModules() for generate-link.ts
18
20
  export { linkModules } from './preview-modules';
@@ -80,6 +82,9 @@ export class PreviewPreview {
80
82
  * render the preview.
81
83
  */
82
84
  render = async (rootExt?: string) => {
85
+ // fit content always.
86
+ window.document.body.style.width = 'fit-content';
87
+
83
88
  const { previewName, componentId } = this.getLocation();
84
89
  const name = previewName || this.getDefault();
85
90
  if (rootExt) this.isDev = rootExt === 'teambit.workspace/workspace';
@@ -102,15 +107,58 @@ export class PreviewPreview {
102
107
  const includes = includesAll.filter((module) => !!module);
103
108
  // during build / tag, the component is isolated, so all aspects are relevant, and do not require filtering
104
109
  const componentAspects = this.isDev ? await this.getComponentAspects(componentId.toString()) : undefined;
105
-
106
- return preview.render(
110
+ const previewModule = await this.getPreviewModule(name, componentId);
111
+ const render = preview.render(
107
112
  componentId,
108
- await this.getPreviewModule(name, componentId),
113
+ previewModule,
109
114
  includes,
110
115
  this.getRenderingContext(componentAspects)
111
116
  );
117
+
118
+ this.reportSize();
119
+ this.setViewport();
120
+ return render;
112
121
  };
113
122
 
123
+ setViewport() {
124
+ const query = this.getQuery();
125
+ const viewPort = this.getParam(query, 'viewport');
126
+ if (!viewPort) {
127
+ window.document.body.style.width = '100%';
128
+ return;
129
+ }
130
+
131
+ window.document.body.style.maxWidth = `${viewPort}px`;
132
+ }
133
+
134
+ reportSize() {
135
+ if (!window?.parent || !window?.document) return;
136
+ // TODO: discuss with gilad for a better way to resolve page loaded here.
137
+
138
+ const sendPubsubEvent = () => {
139
+ this.pubsub.pub(PreviewAspect.id, new SizeEvent({
140
+ width: window.document.body.offsetWidth,
141
+ height: window.document.body.offsetHeight
142
+ }));
143
+ }
144
+
145
+ window.addEventListener('resize', debounce(sendPubsubEvent, 150));
146
+
147
+ let counter = 0;
148
+ const interval = setInterval(() => {
149
+ // TODO: think
150
+ counter += 1;
151
+ if (counter > 10) {
152
+ clearInterval(interval);
153
+ return;
154
+ }
155
+ this.pubsub.pub(PreviewAspect.id, new SizeEvent({
156
+ width: window.document.body.offsetWidth,
157
+ height: window.document.body.offsetHeight
158
+ }));
159
+ }, 200);
160
+ }
161
+
114
162
  async getPreviewModule(previewName: string, id: ComponentID): Promise<PreviewModule> {
115
163
  const compShortId = id.fullName;
116
164
 
@@ -260,11 +308,17 @@ export class PreviewPreview {
260
308
  return preview;
261
309
  }
262
310
 
263
- private getParam(query: string, param: string) {
311
+ getParam(query: string, param: string) {
264
312
  const params = new URLSearchParams(query);
265
313
  return params.get(param);
266
314
  }
267
315
 
316
+ getQuery() {
317
+ const withoutHash = window.location.hash.substring(1);
318
+ const [, after] = withoutHash.split('?');
319
+ return after;
320
+ }
321
+
268
322
  private getLocation() {
269
323
  const withoutHash = window.location.hash.substring(1);
270
324
  const [before, after] = withoutHash.split('?');