Skip to content

Commit

Permalink
chore: update nav preview
Browse files Browse the repository at this point in the history
  • Loading branch information
xwchris committed Dec 25, 2024
1 parent d6f7c44 commit b7e7059
Show file tree
Hide file tree
Showing 9 changed files with 126 additions and 17 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"@babel/traverse": "^7.16.5",
"@babel/types": "^7.16.0",
"@bytedance/mona-manager": "0.3.39-alpha.10",
"@bytedance/mona-shared": "0.3.39-alpha.10",
"@bytedance/mona-manager-plugins-shared": "0.3.39-alpha.10",
"@bytedance/mona-speedy": "0.0.37",
"@bytedance/mona-speedy-components": "0.0.37",
Expand Down Expand Up @@ -68,4 +69,4 @@
"registry": "https://registry.npmjs.org"
},
"gitHead": "cc5aa5283af595fd7d8a7b4921f54e2797504edd"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import path from 'path';
import child_process from 'child_process';
import { IPlugin } from '@bytedance/mona-manager';
import { Platform } from '@bytedance/mona-manager-plugins-shared';
import { requestBeforeCheck, generateRequestFromOpen } from '@bytedance/mona-shared';
import { writeLynxConfig } from './writeLynxConfig';
import { ttmlToReactLynx } from './ttmlToReactLynx';
import { writeEntry } from './writeEntry';
Expand All @@ -12,6 +13,11 @@ const speedy = require('@bytedance/mona-speedy');

let isFirst = true;

export interface NavComponent {
position: 'left' | 'top',
level: number
}

const { MAX, MAX_TEMPLATE } = Platform;
const max: IPlugin = async ctx => {
const configHelper = ctx.configHelper;
Expand All @@ -23,13 +29,13 @@ const max: IPlugin = async ctx => {

const transform = ({
isInjectProps = false,
navComponent = false,
navComponent,
debugPage = '',
notBuildWeb = false,
}: {
isInjectProps?: boolean;
debugPage?: string;
navComponent?: boolean;
navComponent?: NavComponent;
notBuildWeb?: boolean;
}) => {
const entry = ttmlToReactLynx(tempLynxDir, configHelper);
Expand Down Expand Up @@ -64,11 +70,32 @@ const max: IPlugin = async ctx => {
};

// 复写start命令
tctx.overrideStartCommand(args => {
tctx.overrideStartCommand(async args => {
// 进入哪个装修页面
const debugPage = args['debug-page'];
// 是否是分类页的导航组件(需特殊处理)
const navComponent = !!args['nav-component']

// 如果是分类页,需要读取appId来拉取详情
let navComponent: NavComponent | undefined;
if (debugPage === 'category') {
const { user, appId } = await requestBeforeCheck(ctx, args);
const request = generateRequestFromOpen(args, user.cookie);

const appDetail: any = await request<any>('/captain/appManage/getAppDetail', {
method: 'GET',
params: { appId },
});

const isTopBar = appDetail.appExtend.componentGroupType === 6;
const isSideBar = appDetail.appExtend.componentGroupType === 7;

if (isTopBar || isSideBar) {
const position: 'left' | 'top' = isTopBar ? 'top' : 'left';
navComponent = {
position,
level: appDetail.appExtend.componentLevel || 0
}
}
}

try {
const sourceDir = path.join(configHelper.cwd, 'src');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@ import WebpackDevServer from 'webpack-dev-server';
import webpack from 'webpack';
import ora from 'ora';
import chalk from 'chalk';
import { NavComponent } from '..';

const pluginName = 'WebBootstrapPlugin';

let alreadyStart = false;
const WebBootstrapPlugin = ({ entry, appid, navComponent, debugPage }: { entry: string, appid: string, navComponent?: boolean, debugPage: string }) => ({
const WebBootstrapPlugin = ({ entry, appid, navComponent, debugPage }: { entry: string, appid: string, navComponent?: NavComponent, debugPage: string }) => ({
name: pluginName,
apply(compiler: any) {
const isDev = process.env.NODE_ENV !== 'production';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,12 @@ const DEV_SERVER_PORT = 10089;
const WS_PORT = 10079;
const TARGET_URL = `https://fxg.jinritemai.com/ffa/shop/decorate/brand/list?debug=1&WSPORT=${WS_PORT}`;

function generateTargetUrl({ debugPage = '', navComponent = false }) {
return `https://fxg.jinritemai.com/ffa/shop/decorate/${debugPage || 'brand'}/list?debug=1&WSPORT=${WS_PORT}${navComponent ? '&nav=1' : ''}`
function generateTargetUrl({ debugPage = '', navComponent }) {
const extra = ''
if (navComponent) {
extra = `&nav_position=${navComponent.position}&nav_level=${navComponent.level}`
}
return `https://fxg.jinritemai.com/ffa/shop-editor/designable?id=7450057439795233078&debug=1&WSPORT=${WS_PORT}&page_type=${debugPage}${navComponent ? extra : ''}`
}

const SEND_DATA = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const generateBaseConfig = require('./webpack.base.js');
const umdConfig = require('./build-umd-config.js');
const esmConfig = require('./build-esm-config.js');
const openBrowser = require('react-dev-utils/openBrowser')
const { DEV_SERVER_PORT, AfterBuildPlugin, TARGET_URL, generateTargetUrl } = require('../utils/maxDevServer');
const { DEV_SERVER_PORT, AfterBuildPlugin, generateTargetUrl } = require('../utils/maxDevServer');
const getDevProps = require('../utils/getDevProps');

const { name = '@shop-isv/isv-com' } = JSON.parse(
Expand Down Expand Up @@ -118,7 +118,7 @@ function generateDevConfig({ navComponent, debugPage }) {
return devConfig;
}

module.exports = function ({ buildType = 'umd', entry, pxToRem = false, useWebExt = false, appid = '', navComponent = false, debugPage = '' }) {
module.exports = function ({ buildType = 'umd', entry, pxToRem = false, useWebExt = false, appid = '', navComponent, debugPage = '' }) {
const baseConfig = generateBaseConfig({ entry, pxToRem, useWebExt, appid, navComponent, debugPage });
const moduleConfig = buildType === 'umd' ? umdConfig : esmConfig;
const devConfig = generateDevConfig({ navComponent, debugPage });
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import path from 'path';
import fs from 'fs';
import { NavComponent } from '.';

export const getLynxEntry = (tempReactLynxDir: string, isWeb = false) => {
// 兼容window路径
Expand All @@ -12,14 +13,14 @@ export const getLynxEntry = (tempReactLynxDir: string, isWeb = false) => {
export const writeLynxConfig = ({
tempReactLynxDir,
appid,
navComponent = false,
navComponent,
debugPage = '',
notBuildWeb = false,
}: {
tempReactLynxDir: string;
appid: string;
debugPage: string;
navComponent?: boolean;
navComponent?: NavComponent;
notBuildWeb?: boolean;
}) => {
const lynxConfigFile = path.join(tempReactLynxDir, 'lynx.config.js');
Expand Down Expand Up @@ -53,7 +54,7 @@ export const writeLynxConfig = ({
${
notBuildWeb
? ''
: `plugins: [WebBootstrapPlugin({ entry: "${webEntry}", appid: "${appid}", navComponent: "${navComponent}", debugPage: "${debugPage}" })],`
: `plugins: [WebBootstrapPlugin({ entry: "${webEntry}", appid: "${appid}", navComponent: ${navComponent ? JSON.stringify(navComponent) : 'undefined'}, debugPage: "${debugPage}" })],`
}
define: {
__MONA_APPID: JSON.stringify("${appid}")
Expand Down Expand Up @@ -82,7 +83,7 @@ export const writeLynxConfig = ({
${
notBuildWeb
? ''
: `plugins: [WebBootstrapPlugin({ entry: "${webEntry}", appid: "${appid}", navComponent: "${navComponent}", debugPage: "${debugPage}" })],`
: `plugins: [WebBootstrapPlugin({ entry: "${webEntry}", appid: "${appid}",navComponent: ${navComponent ? JSON.stringify(navComponent) : 'undefined'}, debugPage: "${debugPage}" })],`
}
define: {
__MONA_APPID: JSON.stringify("${appid}")
Expand Down
6 changes: 4 additions & 2 deletions packages/mona-shared/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@
"@babel/core": "7.19.0",
"@babel/preset-env": "^7.16.5",
"@babel/preset-typescript": "^7.16.5",
"@babel/register": "^7.16.5"
"@babel/register": "^7.16.5",
"chalk": "^4.1.2",
"assert": "^2.0.0"
},
"devDependencies": {
"@types/node": "^16.4.5",
Expand All @@ -33,4 +35,4 @@
"registry": "https://registry.npmjs.org"
},
"gitHead": "cc5aa5283af595fd7d8a7b4921f54e2797504edd"
}
}
1 change: 1 addition & 0 deletions packages/mona-shared/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,4 @@ export * from './promisify';
export * from './_transformWebStyle';
export * from './_transformWebClass';
export * from './user';
export * from './request';
72 changes: 72 additions & 0 deletions packages/mona-shared/src/request.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import axios, { AxiosRequestConfig } from 'axios';
import { OPEN_DOMAIN, OPEN_DEV_HEADERS } from './domain';
import { deleteUser, readUser } from './user';
import chalk from 'chalk';
import assert from 'assert';

function parseHeaders(headers: string) {
const result: Record<string, string> = {};
const lines = headers.split(';');
lines.forEach(line => {
const [key, value] = line.split('=');
result[key.trim()] = value.trim();
});
return result;
}

export function generateRequestFromOpen(args: any, cookie: string) {
return function <T = any>(path: string, options?: AxiosRequestConfig<any>): Promise<T> {
const domain = args.domain || OPEN_DOMAIN;
const header = args.headers ? parseHeaders(args.headers) : OPEN_DEV_HEADERS;
const url = `https://${domain}${path}`;

const config = {
url,
...options,
headers: {
cookie,
'Content-Type': 'application/json',
...options?.headers,
...header,
},
};
return axios.request(config).then(res => {
const data = res.data as any;
if (data.code === 0) {
return data.data;
} else {
throw new Error(
(data.message || '未知错误') +
(args.debug ? ` [path: ${path}, logid:${res?.headers?.['x-tt-logid'] || 'unknow'}] ` : ''),
);
}
});
};
}

export async function requestBeforeCheck(ctx: any, args: Record<string, string>) {
const appId = ctx.configHelper?.projectConfig.appId;

console.log(chalk.yellow(`请确保在项目根目录使用该命令`));
assert(appId, `未在mona.config中指定appId,请在抖店开放平台应用详情页查看应用APP_Key`);
assert(typeof appId === 'string', 'appId应该为字符串');
assert(/^\d{19}$/.test(appId), 'appId应该为字符串');


// ensure login
const user = readUser();
assert(user, `未登录,请使用 mona login 进行登录`);

const request = generateRequestFromOpen(args, user.cookie);
// ensure user status is not expired
try {
console.log(chalk.cyan(`检查当前登录态...`));
await request('/captain/user/login/info');
console.log(chalk.cyan(`当前用户:${user.nickName}`));
} catch (err) {
deleteUser();
throw new Error('登录态已过期,请使用mona login重新登录');
}

return { user, appId };
}

0 comments on commit b7e7059

Please sign in to comment.