### Configure and Use Axios for Widget Server API Source: https://context7.com/widget-js/widgets/llms.txt Demonstrates how to use a pre-configured Axios instance (`widgetServerApi`) for interacting with the widget server. It includes examples for making GET requests with parameters and POST requests with form data, utilizing interceptors for automatic handling of base URL, timeouts, and response formatting. Error handling is included for both request types. ```typescript import { widgetServerApi } from '@/api/axios' // API is pre-configured with base URL and interceptors // Base URL: https://widgetjs.cn/api/v1 // Timeout: 60000ms // GET request with automatic parameter encoding async function getWidgetData(widgetId: string) { try { const response = await widgetServerApi.get('/widget/detail', { params: { id: widgetId } }) return response // Automatically unwrapped from { code: 200, data: ... } } catch (error) { console.error('API request failed:', error) throw error } } // POST request with form data async function updateWidgetSettings(settings: any) { try { const response = await widgetServerApi.post('/widget/settings', settings, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }) return response } catch (error) { console.error('Settings update failed:', error) throw error } } ``` -------------------------------- ### Widget Server API (Axios Configuration) Source: https://context7.com/widget-js/widgets/llms.txt Provides a centralized HTTP client for the widget server API, pre-configured with base URL and interceptors for requests and responses. Supports GET and POST requests. ```APIDOC ## Widget Server API ### Description Centralized HTTP client with request/response interceptors for the widget server API. ### Base URL `https://widgetjs.cn/api/v1` ### Timeout `60000ms` ### Methods #### GET Request - **Method**: GET - **Endpoint**: `/widget/detail` - **Description**: Retrieves detailed information for a specific widget. - **Query Parameters**: - **id** (string) - Required - The ID of the widget to retrieve details for. - **Response**: - **Success Response (200)**: - The widget data object. - **Response Example**: ```json { "id": "widget-123", "name": "Sample Widget", "version": "1.0.0" } ``` #### POST Request (Update Settings) - **Method**: POST - **Endpoint**: `/widget/settings` - **Description**: Updates the settings for a specific widget. - **Request Body**: - **settings** (object) - Required - An object containing the widget settings to update. - **Headers**: - **Content-Type**: `application/x-www-form-urlencoded` - **Response**: - **Success Response (200)**: - A confirmation message indicating the settings were updated successfully. - **Response Example**: ```json { "message": "Widget settings updated successfully." } ``` ``` -------------------------------- ### Define a Countdown Widget with Widget.js Core Source: https://context7.com/widget-js/widgets/llms.txt Shows how to define a new widget using the `Widget` class from `@widget-js/core`. This example defines a countdown widget, specifying its name, localized titles and descriptions, routes, dimensions, keywords, categories, and preview image. It also includes optional properties like `disabled` and `socialLinks`. ```typescript import { Widget, WidgetKeyword } from '@widget-js/core' const CountdownWidget = new Widget({ // Unique identifier for the widget name: 'cn.widgetjs.widgets.countdown', // Localized titles and descriptions title: { 'zh-CN': '倒计时' }, description: { 'zh-CN': '简单的倒计时组件,支持农历' }, // Widget routes path: '/widget/countdown', configPagePath: '/widget/config/countdown?frame=true&transparent=false&width=600&height=500', // Visual properties width: 2, height: 2, minWidth: 2, maxWidth: 4, minHeight: 2, maxHeight: 4, // Metadata keywords: [WidgetKeyword.RECOMMEND], categories: ['countdown'], lang: 'zh-CN', previewImage: '/images/preview_countdown.png', // Optional features disabled: false, socialLinks: [ { name: 'github', link: 'https://github.com/widget-js/widgets' } ] }) export default CountdownWidget ``` -------------------------------- ### Manage Widget Package Updates with Composition API (TypeScript) Source: https://context7.com/widget-js/widgets/llms.txt Provides functionality to check for and perform updates on installed widget packages using the `useWidgetPackage` composition function. It compares remote and local versions and handles the upgrade process. Dependencies include '@widget-js/core'. ```typescript import { useWidgetPackage } from '@/composition/useWidgetPackage' import type { RemotePackageUrlInfo } from '@widget-js/core' // Initialize package manager for a specific widget package const packageName = 'cn.widgetjs.weather' const remoteVersion = '2.1.0' const remoteUrlInfo: RemotePackageUrlInfo = { url: 'https://widgetjs.cn/packages/weather.zip', hash: 'sha256-abc123...' } const { upgrading, upgradable, checkUpgrade, upgradePackage } = useWidgetPackage(packageName, remoteVersion, remoteUrlInfo) // Check if upgrade is available async function checkForUpdates() { const hasUpdate = await checkUpgrade() if (hasUpdate) { console.log('Update available!') console.log('Upgradable:', upgradable.value) // true console.log('Currently upgrading:', upgrading.value) // false } else { console.log('Package is up to date') } } // Perform package upgrade async function performUpgrade() { if (upgradable.value && !upgrading.value) { console.log('Starting upgrade...') await upgradePackage() console.log('Upgrade completed') // upgradable.value is now false } } // Example usage checkForUpdates().then(() => { if (upgradable.value) { performUpgrade() } }) ``` -------------------------------- ### Aggregate Widget Routes for Vue Router (TypeScript) Source: https://context7.com/widget-js/widgets/llms.txt Combines all individual widget routes into a single router configuration for Vue Router. This simplifies the main router setup by importing and spreading all widget routes. Dependencies include 'vue-router'. ```typescript import type { RouteRecordRaw } from 'vue-router' import TodoListWidgetRoutes from './todo-list/TodoListWidgetRoutes' import CountdownWidgetRoutes from './countdown/CountdownWidgetRoutes' import DynamicIslandWidgetRoutes from './dynamic-island/DynamicIslandWidgetRoutes' const WidgetRouter: RouteRecordRaw[] = [ ...TodoListWidgetRoutes, ...CountdownWidgetRoutes, ...DynamicIslandWidgetRoutes ] export default WidgetRouter // In main router configuration import { createRouter, createWebHashHistory } from 'vue-router' import WidgetRouter from '@/widgets/widget-router' const routes: RouteRecordRaw[] = [ ...WidgetRouter, { path: '/', name: 'home', component: () => import('@/views/add/AddWidgetView.vue') }, { path: '/setting', name: 'setting', component: () => import('@/views/settings/SettingView.vue') } ] const router = createRouter({ history: createWebHashHistory(), routes }) ``` -------------------------------- ### Define Widget Package Metadata (TypeScript) Source: https://context7.com/widget-js/widgets/llms.txt Defines the metadata for a widget package, including its name, author, homepage, localized descriptions and titles, version, entry point, and development options. This configuration is essential for package distribution and installation within the Widget JS ecosystem. It utilizes the `WidgetPackage` class from '@widget-js/core'. ```typescript import { WidgetPackage } from '@widget-js/core' export default new WidgetPackage({ // Package identifier name: 'cn.widgetjs.widgets', author: 'Widget JS', homepage: 'https://widgetjs.cn', // Localized metadata description: { 'zh-CN': '内置基础组件' }, title: { 'zh-CN': '内置基础组件' }, // Package configuration version: '0.0.1', entry: 'index.html', hash: true, // Development options devOptions: { folder: './src/widgets/', route: true, devUrl: 'http://localhost:5174' }, // Widget list (populated automatically) widgets: [], // Required permissions permissions: [] }) ``` -------------------------------- ### Fetch and Like Featured Widgets with FeatureWallApi Source: https://context7.com/widget-js/widgets/llms.txt Fetches a list of featured community widgets and allows users to 'like' them using the FeatureWallApi. The `loadFeaturedWidgets` function retrieves all features, logging their details. The `likeWidget` function takes a feature ID to register a like. Includes error handling for both operations. ```typescript import { FeatureWallApi } from '@/api/FeatureWallApi' import type { FeatureWall } from '@/model/FeatureWall' // Get all featured widgets async function loadFeaturedWidgets() { try { const features: FeatureWall[] = await FeatureWallApi.findAll() features.forEach(feature => { console.log(`${feature.title}: ${feature.description}`) console.log(`Likes: ${feature.likes}`) console.log(`Preview: ${feature.previewImage}`) }) return features } catch (error) { console.error('Failed to load feature wall:', error) return [] } } // Like a featured widget async function likeWidget(featureId: number) { try { await FeatureWallApi.like(featureId) console.log(`Successfully liked feature #${featureId}`) } catch (error) { console.error('Failed to like widget:', error) } } // Example usage loadFeaturedWidgets().then(features => { if (features.length > 0) { likeWidget(features[0].id) } }) ``` -------------------------------- ### Initialize Vue 3 Application (TypeScript) Source: https://context7.com/widget-js/widgets/llms.txt Bootsraps the Vue 3 application by creating an app instance and registering various plugins, including Element Plus, Widget.js, VueUse Motion, i18n, Vue Router, and Pinia. It also configures dayjs for internationalization and imports necessary global styles. The main `App.vue` component and router are also set up. ```typescript import { createApp } from 'vue' import { createPinia } from 'pinia' import { WidgetJsPlugin } from '@widget-js/vue3' import { MotionPlugin } from '@vueuse/motion' import ElementPlus from 'element-plus' import dayjs from 'dayjs' import 'dayjs/locale/zh-cn.js' import '@widget-js/vue3/dist/style.css' import 'element-plus/dist/index.css' import 'animate.css' import 'virtual:uno.css' import App from './App.vue' import router from './router' import { i18n } from '@/i18n/i18n' // Configure dayjs locale dayjs.locale('cn') // Create Vue app instance const app = createApp(App) const pinia = createPinia() // Register plugins app.use(ElementPlus) // UI component library app.use(WidgetJsPlugin) // Widget.js core integration app.use(MotionPlugin) // Animation library app.use(i18n) // Internationalization app.use(router) // Vue Router app.use(pinia) // State management // Mount application app.mount('#app') ``` -------------------------------- ### Configure Vite with Widget.js Plugin and Auto-Imports (TypeScript) Source: https://context7.com/widget-js/widgets/llms.txt This TypeScript configuration sets up the Vite build tool. It integrates the Widget.js plugin for widget development, enables auto-importing of Vue components and utilities with Element Plus resolvers, and includes TypeScript checking. The configuration optimizes build output and sets up path aliases. ```typescript import path from 'node:path' import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import AutoImport from 'unplugin-auto-import/vite' import Components from 'unplugin-vue-components/vite' import { ElementPlusResolver } from 'unplugin-vue-components/resolvers' import widget from '@widget-js/vite-plugin-widget' import checker from 'vite-plugin-checker' import UnoCSS from 'unocss/vite' export default defineConfig({ base: './', server: { port: 8085 }, // Build configuration build: { rollupOptions: { output: { entryFileNames: 'assets/[name].js', chunkFileNames: 'assets/[name].js', assetFileNames: 'assets/[name].[ext]' } } }, // Plugins plugins: [ vue(), UnoCSS(), widget(), // Widget.js integration checker({ typescript: true }), // TypeScript checking AutoImport({ resolvers: [ElementPlusResolver()] }), Components({ resolvers: [ElementPlusResolver()] }) ], // Path aliases resolve: { alias: [{ find: '@', replacement: path.resolve(__dirname, 'src') }] } }) ``` -------------------------------- ### Feature Wall API Source: https://context7.com/widget-js/widgets/llms.txt Fetch and interact with featured community widgets. Supports retrieving all featured widgets and liking individual widgets for user engagement. ```APIDOC ## Feature Wall API ### Description Fetch and interact with featured community widgets, including like functionality for user engagement. ### Methods #### Get All Featured Widgets - **Method**: GET - **Endpoint**: /api/feature-wall - **Description**: Retrieves a list of all featured community widgets. - **Response**: - **Success Response (200)**: - **features** (array) - An array of feature wall objects. - **id** (integer) - The unique identifier of the feature. - **title** (string) - The title of the featured widget. - **description** (string) - The description of the featured widget. - **likes** (integer) - The number of likes for the widget. - **previewImage** (string) - URL to the preview image of the widget. - **Response Example**: ```json [ { "id": 1, "title": "Awesome Widget", "description": "A widget that does amazing things.", "likes": 120, "previewImage": "/images/preview_awesome.png" } ] ``` #### Like a Featured Widget - **Method**: POST - **Endpoint**: /api/feature-wall/{featureId}/like - **Description**: Allows a user to like a specific featured widget. - **Parameters**: #### Path Parameters - **featureId** (integer) - Required - The ID of the feature to like. - **Response**: - **Success Response (200)**: - A confirmation message indicating the like was successful. - **Response Example**: ```json { "message": "Successfully liked feature #1" } ``` ``` -------------------------------- ### Configure Background Deployment Mode Widget (TypeScript) Source: https://context7.com/widget-js/widgets/llms.txt Defines a widget that supports background deployment mode for notifications and reminders. It includes fixed dimensions and specifies the background deploy mode. Dependencies include '@widget-js/core'. ```typescript import { Widget, WidgetKeyword, DeployMode } from '@widget-js/core' const DynamicIslandWidget = new Widget({ name: 'cn.widgetjs.widgets.dynamic_island', title: { 'zh-CN': '灵动通知' }, description: { 'zh-CN': '设置间隔,定时提醒,适合长期久坐的人群' }, path: '/widget/dynamic_island', configPagePath: '/widget/config/dynamic_island?frame=true&transparent=false', // Fixed dimensions for notification widget width: 6, height: 4, minWidth: 6, maxWidth: 6, minHeight: 4, maxHeight: 4, // Enable background mode supportDeployMode: DeployMode.BACKGROUND, keywords: [WidgetKeyword.RECOMMEND], categories: ['utilities'], lang: 'zh-CN', previewImage: '/images/preview_sit_reminder.png', socialLinks: [ { name: 'github', link: 'https://github.com/widget-js/widgets' } ] }) export default DynamicIslandWidget ``` -------------------------------- ### Widget Search API Source: https://context7.com/widget-js/widgets/llms.txt Allows searching for available widgets from the remote widget server. Supports filtering by keyword and category, along with pagination. ```APIDOC ## Widget Search API ### Description Search for available widgets from the remote widget server with filtering and pagination support. ### Method GET ### Endpoint /api/widgets/search ### Parameters #### Query Parameters - **keyword** (string) - Optional - The keyword to search for widgets. - **category** (string) - Optional - The category to filter widgets by. - **page** (integer) - Optional - The page number for pagination. Defaults to 1. - **pageSize** (integer) - Optional - The number of widgets per page. Defaults to 20. ### Request Example ```json { "keyword": "countdown", "category": "productivity", "page": 1, "pageSize": 20 } ``` ### Response #### Success Response (200) - **total** (integer) - The total number of widgets found. - **items** (array) - An array of widget objects. - **name** (string) - The name of the widget. - **description** (string) - The description of the widget. #### Response Example ```json { "total": 50, "items": [ { "name": "Countdown Timer", "description": "A simple countdown timer widget." }, { "name": "Event Countdown", "description": "Countdown to specific events." } ] } ``` ``` -------------------------------- ### Configure Application Settings (TypeScript) Source: https://context7.com/widget-js/widgets/llms.txt Manages application-level settings such as debug mode, grid size, and language preferences using Vue 3 composition API. It provides functions to toggle debug mode, update grid size, and change language, with automatic synchronization to AppApi. Dependencies include '@/composition/useAppConfig'. ```typescript import { useDebugConfig, useCellSizeConfig, useLanguageConfig } from '@/composition/useAppConfig' // Debug mode configuration const debugMode = useDebugConfig((debug) => { console.log(`Debug mode loaded: ${debug}`) }) // Toggle debug mode function toggleDebug() { debugMode.value = !debugMode.value // Automatically synced with AppApi.setDevMode() } // Grid cell size configuration (for widget layout) const gridSize = useCellSizeConfig() function updateGridSize(size: number) { if (size >= 60 && size <= 120) { gridSize.value = size // Automatically synced with AppApi.setGridCellSize() console.log(`Grid size updated to ${size}px`) } } // Language configuration const languageCode = useLanguageConfig() function changeLanguage(lang: string) { languageCode.value = lang // Automatically synced with AppApi.setLanguageCode() console.log(`Language changed to ${lang}`) } // Example: Settings component setup export default { setup() { const debug = useDebugConfig() const cellSize = useCellSizeConfig() const language = useLanguageConfig() return { debug, cellSize, language, toggleDebug, updateGridSize, changeLanguage } } } ``` -------------------------------- ### Search Widgets with WebWidgetApi Source: https://context7.com/widget-js/widgets/llms.txt Searches for available widgets from a remote server using the WebWidgetApi. Supports filtering by keyword and category, with pagination. It takes WidgetSearchOptions and returns a Pagination object containing WebWidget items. Handles potential errors during the search. ```typescript import { WebWidgetApi } from '@/api/WebWidgetApi' import type { WidgetSearchOptions, Pagination, WebWidget } from '@widget-js/web-api' // Search for widgets by keyword and category const searchOptions: WidgetSearchOptions = { keyword: 'countdown', category: 'productivity', page: 1, pageSize: 20 } try { const result: Pagination = await WebWidgetApi.search(searchOptions) console.log(`Found ${result.total} widgets`) result.items.forEach(widget => { console.log(`${widget.name}: ${widget.description}`) }) } catch (error) { console.error('Widget search failed:', error) } ``` -------------------------------- ### Configure Widget Routes for Vue Router (TypeScript) Source: https://context7.com/widget-js/widgets/llms.txt Registers widget and configuration page routes for Vue Router integration. It imports widget definitions and dynamically imports corresponding Vue components. Dependencies include 'vue-router'. ```typescript import type { RouteRecordRaw } from 'vue-router' import CountdownWidgetDefine from './Countdown.widget' const url = CountdownWidgetDefine.path const name = CountdownWidgetDefine.name const configUrl = CountdownWidgetDefine.configPagePath!.split('?')[0] const CountdownWidgetRoutes: RouteRecordRaw[] = [ { path: url, name: `${name}`, component: () => import('./CountdownWidgetView.vue') }, { path: configUrl, name: `${name}.config`, component: () => import('./CountdownConfigView.vue') } ] export default CountdownWidgetRoutes ``` -------------------------------- ### Generate Widget Social Link Icons (TypeScript) Source: https://context7.com/widget-js/widgets/llms.txt Provides utility functions for rendering widget metadata, specifically social media icons. The `renderSocialLinks` function takes a social type and returns an HTML image tag or an empty string. It depends on `WidgetUtil` from '@/utils/WidgetUtil' and `SocialType` from '@widget-js/core'. ```typescript import WidgetUtil from '@/utils/WidgetUtil' import type { SocialType } from '@widget-js/core' // Get icon URL for social links function renderSocialLinks(socialType: SocialType) { const iconUrl = WidgetUtil.getSocialLinkIcon(socialType) if (iconUrl) { return `${socialType}` } return '' } // Example with multiple social links const socialLinks = [ { name: 'github', link: 'https://github.com/widget-js/widgets' }, { name: 'bilibili', link: 'https://space.bilibili.com/123456' }, { name: 'discord', link: 'https://discord.gg/xyz' } ] socialLinks.forEach(social => { const icon = WidgetUtil.getSocialLinkIcon(social.name as SocialType) console.log(`${social.name}: ${icon}`) }) // Supported social types: // github, bilibili, discord, tiktok, douyin, email, qq, gitee, youtube, wechat ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.