### Install Project Dependencies Source: https://github.com/didi/dimina/blob/main/_autodocs/README.md Navigate to the project directory and install dependencies using pnpm. ```bash cd dimina/fe pnpm install ``` -------------------------------- ### Start Local Development Server Source: https://github.com/didi/dimina/blob/main/_autodocs/05-container-api.md Use these commands to manage the local development server for the container package. Includes starting the server, building for production, previewing the build, and serving via HTTP. ```bash cd fe/packages/container pnpm dev # Start Vite dev server pnpm build # Build for production pnpm preview # Preview production build pnpm serve # Serve via HTTP server (for QR code) ``` -------------------------------- ### Run Web Version of Application Source: https://github.com/didi/dimina/blob/main/_autodocs/README.md Navigate to the container package and start the development server for the web version. ```bash cd fe/packages/container pnpm dev ``` -------------------------------- ### Verify Node.js, pnpm, and Git Installation Source: https://github.com/didi/dimina/blob/main/_autodocs/09-getting-started-guide.md Check if Node.js, pnpm, and Git are installed and meet the minimum version requirements. ```bash node --version # v22.22.3+ pnpm --version # v7.0.0+ git --version ``` -------------------------------- ### Handle Image Selection and Preview Source: https://github.com/didi/dimina/blob/main/_autodocs/09-getting-started-guide.md Shows how to allow users to pick images from their album and then preview them. Also includes an example for compressing images. ```javascript // Pick image from album wx.chooseImage({ count: 3, sourceType: ['album'], success(res) { console.log('Selected:', res.tempFilePaths) // Preview image wx.previewImage({ urls: res.tempFilePaths, current: 0 }) } }) // Compress image wx.compressImage({ src: 'path/to/image.jpg', quality: 60, success(res) { console.log('Compressed:', res.tempFilePath) } }) ``` -------------------------------- ### Get File System Manager Instance Source: https://github.com/didi/dimina/blob/main/_autodocs/02-service-api.md Obtain a `FileSystemManager` instance to perform file operations like reading, writing, and deleting files. The example shows how to read a file with UTF-8 encoding. ```javascript import { getFileSystemManager } from '@dimina/service' const fs = getFileSystemManager() fs.readFile({ filePath: 'difile://usr/data.json', encoding: 'utf8', success: (res) => console.log(res.data) }) ``` -------------------------------- ### Using the Custom Component Source: https://github.com/didi/dimina/blob/main/fe/packages/compiler/docs/host-selector-example.md Examples of how to use the custom component in a parent WXML file, demonstrating basic usage, themed variants, and disabled states. ```xml 内容 内容 内容 ``` -------------------------------- ### Ancestor-Descendant Relationship Example Source: https://github.com/didi/dimina/blob/main/fe/packages/service/docs/relations.md Demonstrates the setup and usage of ancestor-descendant relationships, showing how ancestor components can broadcast messages to their descendants. ```APIDOC ## Ancestor-Descendant Relationship Example ### Ancestor Component ```javascript Component({ relations: { './descendant-component': { type: 'descendant', linked: function(target) { this.descendants = this.descendants || [] this.descendants.push(target) } } }, methods: { broadcastMessage: function(message) { const descendants = this.getRelationNodes('./descendant-component') descendants.forEach(descendant => { descendant.receiveMessage(message) }) } } }) ``` ### Descendant Component ```javascript Component({ relations: { './ancestor-component': { type: 'ancestor', linked: function(target) { this.ancestor = target } } }, methods: { receiveMessage: function(message) { console.log('Received ancestor message:', message) } } }) ``` ``` -------------------------------- ### Instantiate AppList Source: https://github.com/didi/dimina/blob/main/_autodocs/05-container-api.md Create an instance of the AppList component. This component is used to display a list of installed mini-programs for user selection. ```javascript new AppList() ``` -------------------------------- ### Get System Information Source: https://github.com/didi/dimina/blob/main/_autodocs/09-getting-started-guide.md Retrieves information about the user's device and screen. Demonstrates both callback-based and promise-based usage of `wx.getSystemInfo`. ```javascript // Get system info wx.getSystemInfo({ success(res) { console.log('Platform:', res.platform) console.log('Screen:', res.screenWidth, 'x', res.screenHeight) } }) // Get or use promise style const info = await wx.getSystemInfo() ``` -------------------------------- ### Platform Detection Example Source: https://github.com/didi/dimina/blob/main/_autodocs/01-common-sdk.md Demonstrates how to use platform detection booleans to conditionally execute code based on the runtime environment. Import necessary detectors from '@dimina/common'. ```javascript import { isAndroid, isIOS, isDesktop } from '@dimina/common' if (isAndroid) { console.log('Running on Android') } else if (isDesktop) { console.log('Running on desktop') } ``` -------------------------------- ### Component Stylesheet with :host Source: https://github.com/didi/dimina/blob/main/fe/packages/compiler/docs/host-selector-example.md Example of a component's WXSS file demonstrating various :host selector usages for different themes, states, and internal elements. ```css /* 组件根节点基础样式 */ :host { display: flex; flex-direction: column; border-radius: 8px; overflow: hidden; background-color: #fff; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); } /* 不同主题的根节点样式 */ :host(.theme-dark) { background-color: #2d2d2d; color: #fff; } :host(.theme-primary) { background-color: #007aff; color: #fff; } /* 根节点状态样式 */ :host(.disabled) { opacity: 0.5; pointer-events: none; } /* 根节点内的子元素样式 */ :host .header { padding: 16px; border-bottom: 1px solid #eee; } :host(.theme-dark) .header { border-bottom-color: #444; } :host .content { padding: 16px; flex: 1; } :host .footer { padding: 12px 16px; background-color: #f8f8f8; } :host(.theme-dark) .footer { background-color: #1a1a1a; } ``` -------------------------------- ### WXSS to CSS Transformation Example Source: https://github.com/didi/dimina/blob/main/_autodocs/08-architecture-overview.md Demonstrates the conversion of WXSS units (rpx) to CSS units (rem) during the transformation process. ```text Input: .box { width: 100rpx; padding: 20rpx; } Output: .box { width: 100rem; padding: 20rem; } ``` -------------------------------- ### Navigate Between Pages Source: https://github.com/didi/dimina/blob/main/_autodocs/09-getting-started-guide.md Provides examples for navigating to a new page and returning to the previous one. Includes a check for API availability before attempting to use `wx.getLocation`. ```javascript // Navigate to page wx.navigateTo({ url: 'pages/detail?id=123' }) // Return to previous page wx.navigateBack({ delta: 1 }) // Check if API available if (wx.canIUse('wx.getLocation')) { // Get user location wx.getLocation({ type: 'wgs84', success(res) { console.log('Location:', res.latitude, res.longitude) }, fail(err) { console.error('Failed:', err.errMsg) } }) } ``` -------------------------------- ### Compile and Run Dimina Development Server Source: https://github.com/didi/dimina/blob/main/_autodocs/09-getting-started-guide.md Follow these steps to compile the Dimina application and start the development server for manual testing. Ensure you navigate to the correct package directory before running commands. ```bash # 1. Compile app pnpm compile # 2. Start dev server cd fe/packages/container && pnpm dev # 3. Open browser and test manually # - Interact with pages # - Check console for errors # - Verify navigation works # - Test on different devices (mobile, tablet, desktop) ``` -------------------------------- ### Event Handlers Source: https://github.com/didi/dimina/blob/main/_autodocs/09-getting-started-guide.md Provides example implementations for common event handlers, accessing event details like target, detail, and touches. ```javascript Page({ onTap(event) { console.log('Tapped:', event.target) }, onInputChange(event) { console.log('Input value:', event.detail.value) }, onTouchStart(event) { console.log('Touch start:', event.touches[0]) }, onCustomEvent(event) { console.log('Custom event detail:', event.detail) } }) ``` -------------------------------- ### Navigation Types Source: https://github.com/didi/dimina/blob/main/_autodocs/09-getting-started-guide.md Provides examples for different navigation methods like navigateTo, redirectTo, navigateBack, switchTab, and reLaunch. ```javascript // Push new page on stack wx.navigateTo({ url: 'pages/detail' }) // Replace current page wx.redirectTo({ url: 'pages/list' }) // Pop pages from stack wx.navigateBack({ delta: 1 }) // Switch to tabBar page wx.switchTab({ url: 'pages/category' }) // Close all and open new page wx.reLaunch({ url: 'pages/home' }) ``` -------------------------------- ### Basic Parent-Child Relationship Example Source: https://github.com/didi/dimina/blob/main/fe/packages/service/docs/relations.md Illustrates how to set up and manage basic parent-child relationships between components, including linked and unlinked lifecycle hooks and accessing child components. ```APIDOC ## Basic Parent-Child Relationship Example ### Parent Component ```javascript Component({ relations: { './child-component': { type: 'child', linked: function(target) { console.log('Child component linked:', target) // Can directly call child component methods target.updateFromParent(this.data.someValue) }, unlinked: function(target) { console.log('Child component unlinked:', target) } } }, methods: { updateAllChildren: function() { const children = this.getRelationNodes('./child-component') children.forEach(child => { child.updateFromParent(this.data.someValue) }) } } }) ``` ### Child Component ```javascript Component({ relations: { './parent-component': { type: 'parent', linked: function(target) { this.parent = target } } }, methods: { updateFromParent: function(value) { this.setData({ parentValue: value }) }, notifyParent: function(data) { if (this.parent) { this.parent.handleChildEvent(data) } } } }) ``` ``` -------------------------------- ### Dimina Project Setup and Development Flow Source: https://github.com/didi/dimina/blob/main/README.md This diagram outlines the general workflow for creating, developing, compiling, and deploying a Dimina mini program across different target platforms. ```mermaid graph TD A[创建小程序项目] --> B[开发小程序页面] B --> C[使用小程序语法编写逻辑] C --> D[使用 DMCC 编译打包] D --> E[生成星河小程序包] E --> F{目标平台} F -->|Android| G[集成Android SDK] F -->|iOS| H[集成iOS SDK] F -->|Harmony| I[集成Harmony SDK] F -->|Web| M[运行Web容器预览] G --> J[运行到Android设备] H --> K[运行到iOS设备] I --> L[运行到Harmony设备] ``` -------------------------------- ### Launch Mini Program in Swift Source: https://github.com/didi/dimina/blob/main/iOS/README.md Launches a mini-program within the iOS application. Ensure the app has necessary UI setup and Dimina SDK is configured. ```swift import Dimina import SwiftUI struct ContentView: View { var body: some View { Button("启动小程序") { launchMiniProgram() } } func launchMiniProgram() { if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene, let window = windowScene.windows.first { let navController = UINavigationController() // 创建一个新的 ContentView 作为根视图,可以自行替换 let contentView = ContentView() let hostingController = UIHostingController(rootView: contentView) hostingController.navigationItem.title = "星河小程序" // 设置为根视图 navController.viewControllers = [hostingController] window.rootViewController = navController // 创建小程序配置和实例 let manager: DMPAppManager = DMPAppManager.sharedInstance() var appConfig: DMPAppConfig = DMPAppConfig(appName: "小程序名称", appId: "wx92269e3b2f304afc") appConfig.isDebugMode = true appConfig.updateManifestUrl = "https://example.com/jsapp/wx92269e3b2f304afc.json" // 可选:远程更新 manifest let app: DMPApp = manager.appWithConfig(appConfig: appConfig) // 设置导航 app.getNavigator()!.setup(navigationController: navController) // 启动小程序 Task { @MainActor in let launchConfig: DMPLaunchConfig = DMPLaunchConfig() await app.launch(launchConfig: launchConfig) } } } } ``` -------------------------------- ### Run Local Development with Compiled App Source: https://github.com/didi/dimina/blob/main/_autodocs/09-getting-started-guide.md To run a compiled mini program locally, first compile the mini program, then start the dev server, and finally copy the compiled app to the public directory. ```bash # Terminal 1: Compile mini program node fe/packages/compiler/src/bin/compile.js \ --target ./shared/jsapp \ --work ./my-miniprogram # Terminal 2: Start dev server cd fe/packages/container pnpm dev # Terminal 3: Copy app to public cp -r shared/jsapp public/apps/ ``` -------------------------------- ### Dimina Local Web Preview Source: https://github.com/didi/dimina/blob/main/README.md Command to start a local development server for previewing and debugging web versions of Dimina mini programs. This is typically run from the 'fe/' directory. ```bash pnpm dev ``` -------------------------------- ### Import and Access Render Instance Properties Source: https://github.com/didi/dimina/blob/main/_autodocs/03-render-api.md Import the Render instance and access its properties like env and message. Ensure the '@dimina/render' package is installed. ```javascript import render from '@dimina/render' // Access properties console.log(render.env) console.log(render.message) ``` -------------------------------- ### Re-launch the application Source: https://github.com/didi/dimina/blob/main/_autodocs/02-service-api.md Use `reLaunch` to close all existing pages and open a new specified page. This is typically used for starting fresh or navigating to a main entry point. ```javascript import { reLaunch } from '@dimina/service' reLaunch({ url: 'pages/home' }) ``` -------------------------------- ### Get Mini Program Environment Source: https://github.com/didi/dimina/blob/main/_autodocs/06-jdimina-h5-sdk.md Retrieves information about the current mini program environment, such as platform and version. Use this to adapt behavior based on the execution context. ```javascript window.wx.miniProgram.getEnv((env) => { console.log('Platform:', env.platform) console.log('Version:', env.version) }) ``` -------------------------------- ### Browser Console Testing for jDimina H5 SDK Source: https://github.com/didi/dimina/blob/main/_autodocs/06-jdimina-h5-sdk.md Use these examples to quickly test jDimina H5 SDK functionalities in your browser's developer console. They demonstrate navigation, system info, location, and bridge invocation. ```javascript // Test navigation window.wx.miniProgram.navigateTo({ url: 'pages/home' }) // Test system info window.wx.miniProgram.getSystemInfo((info) => { console.log(info) }) // Test location window.wx.getLocation({ success(res) { console.log('Location:', res) }, fail(err) { console.log('Error:', err) } }) // Test low-level bridge window.didiJsBridge.invoke({ command: 'WebView_Native', to: 'Native', data: { method: 'getSystemInfo' } }, (res) => console.log(res)) ``` -------------------------------- ### Initialize Dimina SDK in Application Class Source: https://github.com/didi/dimina/blob/main/android/README.md Initialize the Dimina SDK in your `Application` class's `onCreate()` method. This setup is crucial for the SDK to function correctly. Debug mode can be enabled here to affect logging and vConsole initialization. ```kotlin import com.didi.dimina.Dimina class MyApplication : Application() { override fun onCreate() { super.onCreate() Dimina.init(this, Dimina.DiminaConfig.Builder() // 是否启用调试模式:影响日志显示,并允许 pageFrame 初始化 vConsole // 调试模式不检测 App 是否已更新,都会进入 JSSDK 和 JSApp 的更新检测逻辑 .setDebugMode(true) .build() ) } } ``` -------------------------------- ### Get App Configuration Info with Compiler API Source: https://github.com/didi/dimina/blob/main/_autodocs/04-compiler-api.md Retrieves the complete app.json configuration object. This includes properties like entryPagePath, pages, subPackages, tabBar, and window. Ensure the compiler API is imported. ```javascript import { getAppConfigInfo } from '@dimina/compiler' const config = getAppConfigInfo() console.log(config.entryPagePath) ``` -------------------------------- ### Simple Binding Example Source: https://github.com/didi/dimina/blob/main/fe/packages/compiler/docs/expression-binding-implementation.md Example of a simple data binding for a checkbox component. ```xml ``` -------------------------------- ### Launch Mini Program Source: https://github.com/didi/dimina/blob/main/android/README.md Instantiate a `MiniProgram` object with its configuration details and then use `Dimina.getInstance().startMiniProgram()` to launch it. The `context` and the `MiniProgram` object are required parameters. ```kotlin // 从 config.json 文件创建 MiniProgram 对象 val miniProgram = MiniProgram( appId = "wx92269e3b2f304afc", // 小程序唯一标识 name = "小程序名称", // 小程序名称 versionCode = 1, // 版本号 versionName = "1.0.0", // 版本名称 path = "example/index", // 小程序入口路径 // updateManifestUrl = "https://example.com/jsapp/wx92269e3b2f304afc.json" // 可选:远程更新 manifest ) // 启动小程序 Dimina.getInstance().startMiniProgram(context, miniProgram) ``` -------------------------------- ### Handle Mini Program Update Events Source: https://github.com/didi/dimina/blob/main/docs/MiniProgram-Update.md This code handles the events related to Mini Program updates. It checks for updates, prompts the user to restart if an update is ready, and shows a message on update failure. Actual package fetching and installation are handled by the host application. ```javascript const updateManager = wx.getUpdateManager() updateManager.onCheckForUpdate((res) => { if (!res.hasUpdate) { return } }) updateManager.onUpdateReady(() => { wx.showModal({ title: '更新提示', content: '新版本已经准备好,是否重启应用?', success(res) { if (res.confirm) { updateManager.applyUpdate() } }, }) }) updateManager.onUpdateFailed(() => { wx.showToast({ title: '更新失败', icon: 'none', }) }) ``` -------------------------------- ### Configure Application Settings Source: https://github.com/didi/dimina/blob/main/_autodocs/README.md Define application ID, name, and entry point in app.json. ```json { "appId": "com.example.myapp", "name": "My App", "entryPagePath": "pages/home", "pages": ["pages/home"] } ``` -------------------------------- ### Logical Operation Binding Source: https://github.com/didi/dimina/blob/main/fe/packages/compiler/docs/expression-binding-implementation.md Example of using a logical OR operation in a data binding for a checkbox. ```xml ``` -------------------------------- ### Conditional Expression Binding Source: https://github.com/didi/dimina/blob/main/fe/packages/compiler/docs/expression-binding-implementation.md Example of using a conditional expression for an image source binding. ```xml ``` -------------------------------- ### Preview Production Build Locally Source: https://github.com/didi/dimina/blob/main/_autodocs/09-getting-started-guide.md Preview your production build locally using `pnpm preview` within the container package directory. For a local HTTP server with a QR code, use `pnpm serve`. ```bash cd fe/packages/container pnpm preview ``` ```bash cd fe/packages/container pnpm serve ``` -------------------------------- ### Open Application with Device Source: https://github.com/didi/dimina/blob/main/_autodocs/05-container-api.md Initializes device-specific features and mounts the application instance. This method sets up platform features, native bridge communication, and mounts the application's DOM. ```javascript import { Device } from '@/pages/device/device' import { Application } from '@/pages/application/application' const device = new Device() const application = new Application() device.open(application) ``` -------------------------------- ### wx.miniProgram.getSystemInfo Source: https://github.com/didi/dimina/blob/main/_autodocs/06-jdimina-h5-sdk.md Fetches detailed information about the device's system and screen. ```APIDOC ## wx.miniProgram.getSystemInfo(callback) ### Description Gets device system information. ### Method `wx.miniProgram.getSystemInfo` ### Parameters #### Callback Function - **callback** (function) - Required - Invoked with system info; receives `{ platform, screenWidth, screenHeight, ... }` ### Request Example ```javascript window.wx.miniProgram.getSystemInfo((info) => { console.log('Screen:', info.screenWidth, 'x', info.screenHeight) console.log('Platform:', info.platform) }) ``` ### Response #### Success Response - **info** (object) - An object containing system information like `screenWidth`, `screenHeight`, and `platform`. ``` -------------------------------- ### Get User Data Path Source: https://github.com/didi/dimina/blob/main/_autodocs/07-types-and-configuration.md Access the user data directory path using `env.USER_DATA_PATH` from the `@dimina/service` module. ```javascript import { env } from '@dimina/service' const userPath = env.USER_DATA_PATH // 'difile://usr' const dataFile = `${userPath}/data.json` ``` -------------------------------- ### wx.miniProgram.navigateTo Source: https://github.com/didi/dimina/blob/main/_autodocs/06-jdimina-h5-sdk.md Navigates to a specified mini program page from the current webview. The current webview remains open. ```APIDOC ## wx.miniProgram.navigateTo(opts) ### Description Navigates to a mini program page from webview. ### Method `navigateTo` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **opts** (object) - Required - Options object - **opts.url** (string) - Required - Target page path (e.g., 'pages/detail?id=123') ### Request Example ```javascript window.wx.miniProgram.navigateTo({ url: 'pages/detail?id=123&name=product' }) ``` ### Response This method does not return a value. ``` -------------------------------- ### 构建 npm 包 Source: https://github.com/didi/dimina/blob/main/fe/packages/compiler/docs/npm-support.md 使用微信开发者工具或命令行工具构建 npm 包。构建过程会生成 `miniprogram_npm` 目录,其中包含可供小程序使用的 npm 包文件。 ```bash # 使用微信开发者工具 # 工具 -> 构建 npm # 或者使用 miniprogram-ci npx miniprogram-ci build-npm --project-path ./ ``` -------------------------------- ### Page: Select Component by ID Source: https://github.com/didi/dimina/blob/main/fe/packages/service/docs/selectComponent-usage.md In a page, use `this.selectComponent('#my-component')` in `onReady` to get a component instance with the specified ID. ```javascript // 页面 Page({ data: {}, onReady: function () { // 页面渲染完成后可以获取组件实例 const myComponent = this.selectComponent('#my-component'); console.log(myComponent); // 获取页面中 id 为 my-component 的组件实例 } }) ``` ```xml ``` -------------------------------- ### Get Application Name with Compiler API Source: https://github.com/didi/dimina/blob/main/_autodocs/04-compiler-api.md Retrieves the application name from the app.json configuration. Ensure the compiler API is imported. ```javascript import { getAppName } from '@dimina/compiler' const appName = getAppName() ``` -------------------------------- ### Read and Write Files Source: https://github.com/didi/dimina/blob/main/_autodocs/09-getting-started-guide.md Demonstrates file system operations for reading data from and writing data to a file using `wx.getFileSystemManager`. Assumes UTF-8 encoding. ```javascript const fs = wx.getFileSystemManager() // Read file fs.readFile({ filePath: 'difile://usr/data.json', encoding: 'utf8', success(res) { const data = JSON.parse(res.data) console.log('Data:', data) } }) // Write file fs.writeFile({ filePath: 'difile://usr/data.json', data: JSON.stringify({ count: 123 }), encoding: 'utf8', success() { console.log('File saved') } }) ``` -------------------------------- ### Get Application ID with Compiler API Source: https://github.com/didi/dimina/blob/main/_autodocs/04-compiler-api.md Retrieves the application ID from the app.json configuration. Ensure the compiler API is imported. ```javascript import { getAppId } from '@dimina/compiler' const appId = getAppId() ``` -------------------------------- ### wx.miniProgram.goSuperAppTab Source: https://github.com/didi/dimina/blob/main/_autodocs/06-jdimina-h5-sdk.md Navigates the user to a specified tab within the host super application. ```APIDOC ## wx.miniProgram.goSuperAppTab(tabName, callback) ### Description Navigates to a tab in the super app (host application). ### Method `wx.miniProgram.goSuperAppTab` ### Parameters #### Path Parameters - **tabName** (string) - Required - Tab identifier in host app #### Callback Function - **callback** (function) - Optional - Invoked with navigation result ### Request Example ```javascript window.wx.miniProgram.goSuperAppTab('home', (result) => { if (result.success) { console.log('Navigated to home tab') } }) ``` ### Response #### Success Response - **result** (object) - An object indicating the success or failure of the navigation. ``` -------------------------------- ### Instantiate Application Class Source: https://github.com/didi/dimina/blob/main/_autodocs/05-container-api.md Creates a new instance of the Application class. This is typically the first step in setting up the main application view. ```javascript new Application() ``` -------------------------------- ### Object Utilities - get Source: https://github.com/didi/dimina/blob/main/_autodocs/01-common-sdk.md Retrieves a value from a nested object using dot notation or array indexing, with protection against prototype pollution. ```APIDOC ## get(data, path) Retrieves a value from a nested object using dot notation or array indexing. ### Signature: ```javascript function get(data: object, path: string | string[] | symbol | number): any ``` ### Parameters: #### Path Parameters - **data** (object) - Required - Source object - **path** (string | string[] | symbol | number) - Required - Property path; supports `'a.b.c'`, `'a[0].b'`, or `['a', 'b', 'c']` ### Return Type: Retrieved value or `undefined` if not found ### Example: ```javascript import { get } from '@dimina/common' const obj = { user: { name: 'Alice', tags: ['admin', 'user'] } } get(obj, 'user.name') // 'Alice' get(obj, 'user.tags[0]') // 'admin' get(obj, ['user', 'name']) // 'Alice' get(obj, 'user.missing') // undefined ``` ### Security: Returns `undefined` for `__proto__` key to prevent prototype pollution. ``` -------------------------------- ### List Rendering Source: https://github.com/didi/dimina/blob/main/_autodocs/09-getting-started-guide.md Illustrates how to render lists of data using `wx:for` and how to customize item and index variable names. ```html {{ item.name }} {{ idx }}: {{ product.name }} ``` -------------------------------- ### Page: Select Component by Class Source: https://github.com/didi/dimina/blob/main/fe/packages/service/docs/selectComponent-usage.md In a page, use `this.selectComponent('.my-class')` to get the first component instance with the specified class name. ```javascript // 页面 Page({ data: {}, onReady: function () { const myComponent = this.selectComponent('.my-class'); console.log(myComponent); // 获取页面中第一个 class 包含 my-class 的组件实例 } }) ``` -------------------------------- ### wx.getLocation Source: https://github.com/didi/dimina/blob/main/_autodocs/06-jdimina-h5-sdk.md Gets the user's current location. Supports different coordinate systems and provides callbacks for success, failure, and completion. ```APIDOC ## wx.getLocation(params) ### Description Gets user's current location. ### Method `wx.getLocation` ### Parameters #### Path Parameters - **params.type** (string) - Optional - Coordinate system: 'wgs84' (GPS) or 'gcj02' (China). Defaults to 'wgs84'. - **params.success** (function) - Optional - Success callback; receives `{ latitude, longitude, accuracy }`. - **params.fail** (function) - Optional - Failure callback. - **params.complete** (function) - Optional - Always invoked. ### Request Example ```javascript window.wx.getLocation({ type: 'wgs84', success(res) { console.log('Location:', res.latitude, res.longitude) }, fail(err) { console.error('Failed to get location:', err) } }) ``` ### Response #### Success Response - **latitude** (number) - The latitude of the current location. - **longitude** (number) - The longitude of the current location. - **accuracy** (number) - The accuracy of the location, in meters. ``` -------------------------------- ### Initialize AppList Page Source: https://github.com/didi/dimina/blob/main/_autodocs/05-container-api.md Import and initialize the AppList component, then set it as the root view of the application. This is typically done during the application's startup sequence. ```javascript import { AppList } from '@/pages/appList/appList' const appListPage = new AppList() application.initRootView(appListPage) ``` -------------------------------- ### Custom Component: Select Child by ID Source: https://github.com/didi/dimina/blob/main/fe/packages/service/docs/selectComponent-usage.md Within a custom component, use `this.selectComponent('#my-component')` to get a child component instance by its ID. ```javascript // 父组件 Component({ methods: { getChildComponent: function () { const child = this.selectComponent('#my-component'); console.log(child); // 获取 id 为 my-component 的子组件实例 } } }) ``` ```xml ``` -------------------------------- ### 配置文件示例 (index.json) Source: https://github.com/didi/dimina/blob/main/fe/packages/compiler/docs/npm-support.md 在 `pages/index/index.json` 文件中配置 `usingComponents` 来引用 npm 组件和本地组件。这允许在 WXML 文件中使用自定义标签。 ```json { "usingComponents": { "lib-button": "lib-weapp/button", "lib-cell": "lib-weapp/cell", "custom-component": "./components/custom" } } ``` -------------------------------- ### Page: Select Multiple Components by Class Source: https://github.com/didi/dimina/blob/main/fe/packages/service/docs/selectComponent-usage.md In a page, use `this.selectAllComponents('.my-class')` to get an array of all component instances with the specified class name. ```javascript // 页面 Page({ data: {}, onReady: function () { const components = this.selectAllComponents('.my-class'); console.log(components); // 获取页面中所有 class 包含 my-class 的组件实例数组 } }) ``` -------------------------------- ### Run Tests and Build Android Modules Source: https://github.com/didi/dimina/blob/main/CONTRIBUTING.md Execute tests for frontend packages or build Android sample and SDK modules. Ensure these commands are run before submitting changes. ```sh # Frontend packages cd fe pnpm test ``` ```sh # Android sample and SDK modules cd android ./gradlew build ``` -------------------------------- ### Get Target Path with Compiler API Source: https://github.com/didi/dimina/blob/main/_autodocs/04-compiler-api.md Retrieves the absolute file path of the output or distribution directory. Ensure the compiler API is imported. ```javascript import { getTargetPath } from '@dimina/compiler' const targetPath = getTargetPath() ``` -------------------------------- ### Get Network Type Source: https://github.com/didi/dimina/blob/main/_autodocs/02-service-api.md Retrieves the current network connection type. Supports both Promise and callback styles. Ensure the service is imported correctly. ```javascript import { getNetworkType } from '@dimina/service' // Promise style const result = await getNetworkType() console.log(result.networkType) // Callback style getNetworkType({ success: (res) => console.log(res.networkType) }) ``` -------------------------------- ### Get System Information Source: https://github.com/didi/dimina/blob/main/_autodocs/06-jdimina-h5-sdk.md Fetches device system information including screen dimensions and platform. Useful for responsive design or device-specific features. ```javascript window.wx.miniProgram.getSystemInfo((info) => { console.log('Screen:', info.screenWidth, 'x', info.screenHeight) console.log('Platform:', info.platform) }) ``` -------------------------------- ### wx.miniProgram.reLaunch Source: https://github.com/didi/dimina/blob/main/_autodocs/06-jdimina-h5-sdk.md Closes all currently open pages in the mini program and then opens the specified target page. This effectively restarts the mini program's navigation stack. ```APIDOC ## wx.miniProgram.reLaunch(opts) ### Description Closes all pages and opens target mini program page. ### Method `reLaunch` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **opts** (object) - Required - Options object - **opts.url** (string) - Required - Target page path ### Request Example ```javascript window.wx.miniProgram.reLaunch({ url: 'pages/home' }) ``` ### Response This method does not return a value. ``` -------------------------------- ### Receive Message in Mini Program Handler Source: https://github.com/didi/dimina/blob/main/_autodocs/06-jdimina-h5-sdk.md Example of how a mini program page can handle messages sent from a webview using the `onWebViewMessage` lifecycle function. ```javascript // In page.js Page({ onWebViewMessage(event) { // event.detail.data = [{ action: 'update', value: 42 }] console.log(event.detail.data) } }) ``` -------------------------------- ### wx.miniProgram.getEnv Source: https://github.com/didi/dimina/blob/main/_autodocs/06-jdimina-h5-sdk.md Retrieves information about the current mini program environment, such as the platform and version. ```APIDOC ## wx.miniProgram.getEnv(callback) ### Description Gets the mini program environment information. ### Method `wx.miniProgram.getEnv` ### Parameters #### Callback Function - **callback** (function) - Required - Invoked with environment object; receives `{ platform, version, ... }` ### Request Example ```javascript window.wx.miniProgram.getEnv((env) => { console.log('Platform:', env.platform) console.log('Version:', env.version) }) ``` ### Response #### Success Response - **env** (object) - An object containing environment details like `platform` and `version`. ``` -------------------------------- ### 在页面中使用 npm 组件 Source: https://github.com/didi/dimina/blob/main/fe/packages/compiler/docs/npm-support.md 在小程序的 `.json` 配置文件中引用 npm 组件。通过 `usingComponents` 字段可以映射组件的标签名到 npm 包的路径。 ```json { "usingComponents": { "my-component": "your-miniprogram-component", "other-component": "your-miniprogram-component/other" } } ``` -------------------------------- ### Dimina App Configuration with Sub-Packages Source: https://github.com/didi/dimina/blob/main/_autodocs/09-getting-started-guide.md Sets up a Dimina mini program using sub-packages to organize features, specifying the root directory and pages for each sub-package. ```json { "appId": "com.example.myapp", "name": "My App", "entryPagePath": "pages/home", "pages": [ "pages/home" ], "subPackages": [ { "root": "features/shop", "name": "shop", "pages": [ "pages/list", "pages/detail" ] } ] } ``` -------------------------------- ### Mini Program Configuration (config.json) Source: https://github.com/didi/dimina/blob/main/android/README.md Defines the configuration for a mini program, including its unique identifier, name, entry path, and version information. This JSON file is essential for launching the mini program. ```json { "appId": "wx92269e3b2f304afc", // 小程序唯一标识 "name": "小程序名称", "path": "example/index", // 小程序入口路径 "versionCode": 1, // 启动小程序时会根据版本号确认是否需要更新 "versionName": "1.0.0" } ``` -------------------------------- ### Custom Component: Select Child by Class Source: https://github.com/didi/dimina/blob/main/fe/packages/service/docs/selectComponent-usage.md Within a custom component, use `this.selectComponent('.my-class')` to get the first child component instance with the specified class. ```javascript // 父组件 Component({ methods: { getChildComponent: function () { const child = this.selectComponent('.my-class'); console.log(child); // 获取 class 包含 my-class 的第一个子组件实例 } } }) ``` ```xml ``` -------------------------------- ### Get Work Path with Compiler API Source: https://github.com/didi/dimina/blob/main/_autodocs/04-compiler-api.md Retrieves the absolute file path of the source project's root directory. Ensure the compiler API is imported. ```javascript import { getWorkPath } from '@dimina/compiler' const workPath = getWorkPath() ``` -------------------------------- ### Accessing Mini Program APIs Source: https://github.com/didi/dimina/blob/main/_autodocs/06-jdimina-h5-sdk.md Both `window.wx` and `window.dd` provide access to the same mini program API set. Use either to call functions like `getSystemInfo`. ```javascript window.wx.getSystemInfo(...) window.dd.getSystemInfo(...) ``` -------------------------------- ### Using Behavior with Relations Source: https://github.com/didi/dimina/blob/main/fe/packages/service/docs/relations.md Define a behavior that includes relation configurations. This allows multiple components to share the same relation setup, specifying a target behavior for the relation. ```javascript const parentBehavior = Behavior({ relations: { './child-component': { type: 'child', target: 'childBehavior', linked: function(target) { console.log('具有 childBehavior 的组件已连接') } } } }) Component({ behaviors: [parentBehavior], // 其他配置... }) ``` -------------------------------- ### QuickJS Source Files Source: https://github.com/didi/dimina/blob/main/harmony/dimina/src/main/cpp/CMakeLists.txt Explicitly lists the source files from the QuickJS library that are needed for the build. This provides more control than globbing. ```cmake # Add QuickJS source files directly set(QUICKJS_SOURCES ${quickjs_SOURCE_DIR}/quickjs.c ${quickjs_SOURCE_DIR}/libregexp.c ${quickjs_SOURCE_DIR}/libunicode.c ${quickjs_SOURCE_DIR}/cutils.c ${quickjs_SOURCE_DIR}/dtoa.c ) ``` -------------------------------- ### Build for Production Source: https://github.com/didi/dimina/blob/main/_autodocs/09-getting-started-guide.md Build your Dimina application for production by navigating to the container package directory and running `pnpm build`. This optimizes assets and prepares the application for deployment. ```bash cd fe/packages/container pnpm build ``` -------------------------------- ### Android config.json with Update URL Source: https://github.com/didi/dimina/blob/main/docs/MiniProgram-Update.md Alternatively, include `updateManifestUrl` in the `config.json` file when creating Mini Programs on Android if using the example project's configuration method. ```json { "appId": "wx92269e3b2f304afc", "name": "小程序名称", "path": "example/index", "versionCode": 1, "versionName": "1.0.0", "updateManifestUrl": "https://example.com/jsapp/wx92269e3b2f304afc.json" } ``` -------------------------------- ### Harmony Platform Architecture Source: https://github.com/didi/dimina/blob/main/_autodocs/08-architecture-overview.md Describes the Harmony architecture, featuring a Harmony WebView for rendering and QuickJS for service logic. ```text Harmony App ↓ Harmony WebView (Render) ←→ QuickJS (Service) ↓ ↓ HTML/CSS/JS Logic Execution ↓ ↓ WebKit Rendering Harmony APIs ``` -------------------------------- ### wx.miniProgram.redirectTo Source: https://github.com/didi/dimina/blob/main/_autodocs/06-jdimina-h5-sdk.md Closes the current webview and navigates to a specified mini program page. This is a one-way navigation. ```APIDOC ## wx.miniProgram.redirectTo(opts) ### Description Closes webview and navigates to mini program page. ### Method `redirectTo` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **opts** (object) - Required - Options object - **opts.url** (string) - Required - Target page path ### Request Example ```javascript window.wx.miniProgram.redirectTo({ url: 'pages/home' }) ``` ### Response This method does not return a value. ``` -------------------------------- ### Custom Component: Select Child by Tag Name Source: https://github.com/didi/dimina/blob/main/fe/packages/service/docs/selectComponent-usage.md Within a custom component, use `this.selectComponent('my-component')` to get the first child component instance by its tag name. ```javascript // 父组件 Component({ methods: { getChildComponent: function () { const child = this.selectComponent('my-component'); console.log(child); // 获取第一个 my-component 组件实例 } } }) ``` -------------------------------- ### Choose Image with Options Source: https://github.com/didi/dimina/blob/main/_autodocs/02-service-api.md Opens the image picker to select images from the camera or photo album. Specify count, size type, and source type for customization. Use the success callback to handle the returned temporary file paths and file objects. ```javascript import { chooseImage } from '@dimina/service' const result = await chooseImage({ count: 3, sizeType: ['compressed'], sourceType: ['album'] }) console.log(result.tempFilePaths) // ['difile://temp/image1.jpg', ...] ``` -------------------------------- ### Get Page Configuration with Compiler API Source: https://github.com/didi/dimina/blob/main/_autodocs/04-compiler-api.md Retrieves the page configuration structure organized by package. This includes main pages and sub-pages. Ensure the compiler API is imported. ```javascript import { getPages } from '@dimina/compiler' const pages = getPages() pages.mainPages.forEach(page => { console.log(`Page: ${page.path}`) }) ``` -------------------------------- ### Prevent Prototype Pollution Source: https://github.com/didi/dimina/blob/main/_autodocs/07-types-and-configuration.md Safely access and modify object properties to prevent prototype pollution. The `get` and `set` functions return `undefined` or are silently ignored when targeting `__proto__`. ```javascript get(obj, '__proto__') // Returns undefined set(obj, '__proto__', x) // Silently ignored ``` -------------------------------- ### Get Relation Nodes API Source: https://github.com/didi/dimina/blob/main/fe/packages/service/docs/relations.md Use getRelationNodes to retrieve all connected component instances based on a specified relation path. Ensure the relationPath matches the configuration in the relations object. ```javascript // 获取所有子组件 const children = this.getRelationNodes('./child-component') // 获取父组件 const parents = this.getRelationNodes('./parent-component') ``` -------------------------------- ### Dimina Compilation and Packaging Commands Source: https://github.com/didi/dimina/blob/main/README.md Commands to compile mini program code into Dimina runtime resources and generate application and SDK packages. Ensure dependencies are installed in the frontend workspace before execution. ```bash pnpm generate:app pnpm generate:sdk ``` -------------------------------- ### Download QuickJS Dependency Source: https://github.com/didi/dimina/blob/main/harmony/dimina/src/main/cpp/CMakeLists.txt Declares the QuickJS dependency using FetchContent, specifying its Git repository and tag. It's configured for shallow cloning to reduce download size. ```cmake FetchContent_Declare( quickjs GIT_REPOSITORY https://github.com/bellard/quickjs.git GIT_TAG master GIT_SHALLOW TRUE ) FetchContent_MakeAvailable(quickjs) ``` -------------------------------- ### Object Path Retrieval with `get` Source: https://github.com/didi/dimina/blob/main/_autodocs/01-common-sdk.md Safely retrieves a value from a nested object using a string path or an array of keys. Returns `undefined` if the path does not exist or for `__proto__` keys to prevent pollution. ```javascript import { get } from '@dimina/common' const obj = { user: { name: 'Alice', tags: ['admin', 'user'] } } get(obj, 'user.name') // 'Alice' get(obj, 'user.tags[0]') // 'admin' get(obj, ['user', 'name']) // 'Alice' get(obj, 'user.missing') // undefined ``` -------------------------------- ### WXML 示例 (index.wxml) Source: https://github.com/didi/dimina/blob/main/fe/packages/compiler/docs/npm-support.md 在 `pages/index/index.wxml` 文件中使用在 `.json` 配置文件中定义的组件标签。这些标签会渲染对应的 npm 或本地组件。 ```xml npm 组件按钮 本地组件 ``` -------------------------------- ### Custom Component: Select Child by Attribute Source: https://github.com/didi/dimina/blob/main/fe/packages/service/docs/selectComponent-usage.md Within a custom component, use `this.selectComponent('[data-type="button"]')` to get the first child component instance matching the attribute selector. ```javascript // 父组件 Component({ methods: { getChildComponent: function () { const child = this.selectComponent('[data-type="button"]'); console.log(child); // 获取 data-type 为 button 的第一个子组件实例 } } }) ``` ```xml ``` -------------------------------- ### Compile Project for Target Source: https://github.com/didi/dimina/blob/main/_autodocs/README.md Use the Dimina compiler to build the project for a specified target directory. ```bash node fe/packages/compiler/src/bin/compile.js \ --target ./dist \ --work ./my-app ``` -------------------------------- ### Register Persistent Native Module Subscription Source: https://github.com/didi/dimina/blob/main/_autodocs/05-container-api.md Register a handler for persistent subscriptions using AppManager.registerExtModule. The handler should return an unsubscribe function to clean up resources like intervals. This example sets up an accelerometer listener. ```javascript AppManager.registerExtModule('SensorModule', ({ event, data, success, fail }) => { if (event === 'onAccelerometer') { const interval = setInterval(() => { success?.({ x: Math.random() * 10, y: Math.random() * 10, z: Math.random() * 10 }) }, 100) // Return unsubscribe function return () => clearInterval(interval) } }) ``` -------------------------------- ### Path Resolution Algorithm Source: https://github.com/didi/dimina/blob/main/fe/packages/service/docs/relations.md Illustrates the logic for resolving relation paths, handling relative paths starting with './' and '../', as well as absolute paths. This ensures correct component matching regardless of location. ```javascript #resolveRelationPath(relationPath) { if (relationPath.startsWith('./')) { // 相对路径处理 const currentDir = this.is.substring(0, this.is.lastIndexOf('/')) return `${currentDir}/${relationPath.substring(2)}` } else if (relationPath.startsWith('../')) { // 上级路径处理 // 解析 .. 路径段 } else { // 绝对路径 return relationPath } } ``` -------------------------------- ### wx.miniProgram.navigateBack Source: https://github.com/didi/dimina/blob/main/_autodocs/06-jdimina-h5-sdk.md Closes the current webview and returns to a previous page in the mini program. You can specify how many pages to go back by providing the delta option. ```APIDOC ## wx.miniProgram.navigateBack(opts) ### Description Closes the webview and returns to previous page in mini program. ### Method `navigateBack` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **opts** (object) - Optional - Options object - **opts.delta** (number) - Optional - Number of pages to pop from stack. Defaults to 1. ### Request Example ```javascript window.wx.miniProgram.navigateBack({ delta: 1 }) ``` ### Response This method does not return a value. ``` -------------------------------- ### Instantiate Device Class Source: https://github.com/didi/dimina/blob/main/_autodocs/05-container-api.md Creates a new instance of the Device class. This class manages device-level UI and platform capabilities. ```javascript new Device() ```