Files
cc-switch/src/components/JsonEditor.tsx

217 lines
6.1 KiB
TypeScript
Raw Normal View History

import React, { useRef, useEffect, useMemo } from "react";
import { EditorView, basicSetup } from "codemirror";
import { json } from "@codemirror/lang-json";
feat: add provider usage query with JavaScript scripting support (#101) * feat: add provider usage query functionality - Updated `Cargo.toml` to include `regex` and `rquickjs` dependencies for usage script execution. - Implemented `query_provider_usage` command in `commands.rs` to handle usage queries. - Created `UsageScript` and `UsageData` structs in `provider.rs` for managing usage script configurations and results. - Added `execute_usage_script` function in `usage_script.rs` to run user-defined scripts for querying usage. - Enhanced `ProviderList` component to include a button for configuring usage scripts and a modal for editing scripts. - Introduced `UsageFooter` component to display usage information and status. - Added `UsageScriptModal` for editing and testing usage scripts with preset templates. - Updated Tauri API to support querying provider usage. - Modified types in `types.ts` to include structures for usage scripts and results. * feat(usage): support multi-plan usage display for providers - 【Feature】 - Update `UsageResult` to support an array of `UsageData` for displaying multiple usage plans per provider. - Refactor `query_provider_usage` command to parse both single `UsageData` objects (for backward compatibility) and arrays of `UsageData`. - Enhance `usage_script` validation to accept either a single usage object or an array of usage objects. - 【Frontend】 - Redesign `UsageFooter` to iterate and display details for all available usage plans, introducing `UsagePlanItem` for individual plan rendering. - Improve usage display with color-coded remaining balance and clear plan information. - Update `UsageScriptModal` test notification to summarize all returned plans. - Remove redundant `isCurrent` prop from `UsageFooter` in `ProviderList`. - 【Build】 - Change frontend development server port from `3000` to `3005` in `tauri.conf.json` and `vite.config.mts`. * feat(usage): enhance query flexibility and display - 【`src/types.ts`, `src-tauri/src/provider.rs`】Make `UsageData` fields optional and introduce `extra` and `invalidMessage` for more flexible reporting. - `expiresAt` replaced by generic `extra` field. - `isValid`, `remaining`, `unit` are now optional. - Added `invalidMessage` to provide specific reasons for invalid status. - 【`src-tauri/src/usage_script.rs`】Relax usage script result validation to accommodate optional fields in `UsageData`. - 【`src/components/UsageFooter.tsx`】Update UI to display `extra` field and `invalidMessage`, and conditionally render `remaining` and `unit` based on availability. - 【`src/components/UsageScriptModal.tsx`】 - Add a new `NewAPI` preset template demonstrating advanced extractor logic for complex API responses. - Update script instructions to reflect optional fields and new variable syntax (`{{apiKey}}`). - Remove old "DeepSeek" and "OpenAI" templates. - Remove basic syntax check for `return` statement. - 【`.vscode/settings.json`】Add `dish-ai-commit.base.language` setting. - 【`src-tauri/src/commands.rs`】Adjust usage logging to handle optional `remaining` and `unit` fields. * chore(config): remove VS Code settings from version control - delete .vscode/settings.json to remove editor-specific configurations - add /.vscode to .gitignore to prevent tracking of local VS Code settings - ensure personalized editor preferences are not committed to the repository * fix(provider): preserve usage script during provider update - When updating a provider, the `usage_script` configuration within `ProviderMeta` was not explicitly merged. - This could lead to the accidental loss of `usage_script` settings if the incoming `provider` object in the update request did not contain this field. - Ensure `usage_script` is cloned from the existing provider's meta when merging `ProviderMeta` during an update. * refactor(provider): enforce base_url for usage scripts and update dev ports - 【Backend】 - `src-tauri/src/commands.rs`: Made `ANTHROPIC_BASE_URL` a required field for Claude providers and `base_url` a required field in `config.toml` for Codex providers when extracting credentials for usage script execution. This improves error handling by explicitly failing if these critical URLs are missing or malformed. - 【Frontend】 - `src/App.tsx`, `src/components/ProviderList.tsx`: Passed `appType` prop to `ProviderList` component to ensure `updateProvider` calls within `handleSaveUsageScript` correctly identify the application type. - 【Config】 - `src-tauri/tauri.conf.json`, `vite.config.mts`: Updated development server ports from `3005` to `3000` to standardize local development environment. * refactor(usage): improve usage data fetching logic - Prevent redundant API calls by tracking last fetched parameters in `useEffect`. - Avoid concurrent API requests by adding a guard in `fetchUsage`. - Clear usage data and last fetch parameters when usage query is disabled. - Add `queryProviderUsage` API declaration to `window.api` interface. * fix(usage-script): ensure usage script updates and improve reactivity - correctly update `usage_script` from new provider meta during updates - replace full page reload with targeted provider data refresh after saving usage script settings - trigger usage data fetch or clear when `usageEnabled` status changes in `UsageFooter` - reduce logging verbosity for usage script execution in backend commands and script execution * style(usage-footer): adjust usage plan item layout - Decrease width of extra field column from 35% to 30% - Increase width of usage information column from 40% to 45% - Improve visual balance and readability of usage plan items
2025-10-15 09:15:25 +08:00
import { javascript } from "@codemirror/lang-javascript";
import { oneDark } from "@codemirror/theme-one-dark";
import { EditorState } from "@codemirror/state";
import { placeholder } from "@codemirror/view";
import { linter, Diagnostic } from "@codemirror/lint";
import { useTranslation } from "react-i18next";
import { Wand2 } from "lucide-react";
import { toast } from "sonner";
import { formatJSON } from "@/utils/formatters";
interface JsonEditorProps {
value: string;
onChange: (value: string) => void;
placeholder?: string;
darkMode?: boolean;
rows?: number;
showValidation?: boolean;
feat: add provider usage query with JavaScript scripting support (#101) * feat: add provider usage query functionality - Updated `Cargo.toml` to include `regex` and `rquickjs` dependencies for usage script execution. - Implemented `query_provider_usage` command in `commands.rs` to handle usage queries. - Created `UsageScript` and `UsageData` structs in `provider.rs` for managing usage script configurations and results. - Added `execute_usage_script` function in `usage_script.rs` to run user-defined scripts for querying usage. - Enhanced `ProviderList` component to include a button for configuring usage scripts and a modal for editing scripts. - Introduced `UsageFooter` component to display usage information and status. - Added `UsageScriptModal` for editing and testing usage scripts with preset templates. - Updated Tauri API to support querying provider usage. - Modified types in `types.ts` to include structures for usage scripts and results. * feat(usage): support multi-plan usage display for providers - 【Feature】 - Update `UsageResult` to support an array of `UsageData` for displaying multiple usage plans per provider. - Refactor `query_provider_usage` command to parse both single `UsageData` objects (for backward compatibility) and arrays of `UsageData`. - Enhance `usage_script` validation to accept either a single usage object or an array of usage objects. - 【Frontend】 - Redesign `UsageFooter` to iterate and display details for all available usage plans, introducing `UsagePlanItem` for individual plan rendering. - Improve usage display with color-coded remaining balance and clear plan information. - Update `UsageScriptModal` test notification to summarize all returned plans. - Remove redundant `isCurrent` prop from `UsageFooter` in `ProviderList`. - 【Build】 - Change frontend development server port from `3000` to `3005` in `tauri.conf.json` and `vite.config.mts`. * feat(usage): enhance query flexibility and display - 【`src/types.ts`, `src-tauri/src/provider.rs`】Make `UsageData` fields optional and introduce `extra` and `invalidMessage` for more flexible reporting. - `expiresAt` replaced by generic `extra` field. - `isValid`, `remaining`, `unit` are now optional. - Added `invalidMessage` to provide specific reasons for invalid status. - 【`src-tauri/src/usage_script.rs`】Relax usage script result validation to accommodate optional fields in `UsageData`. - 【`src/components/UsageFooter.tsx`】Update UI to display `extra` field and `invalidMessage`, and conditionally render `remaining` and `unit` based on availability. - 【`src/components/UsageScriptModal.tsx`】 - Add a new `NewAPI` preset template demonstrating advanced extractor logic for complex API responses. - Update script instructions to reflect optional fields and new variable syntax (`{{apiKey}}`). - Remove old "DeepSeek" and "OpenAI" templates. - Remove basic syntax check for `return` statement. - 【`.vscode/settings.json`】Add `dish-ai-commit.base.language` setting. - 【`src-tauri/src/commands.rs`】Adjust usage logging to handle optional `remaining` and `unit` fields. * chore(config): remove VS Code settings from version control - delete .vscode/settings.json to remove editor-specific configurations - add /.vscode to .gitignore to prevent tracking of local VS Code settings - ensure personalized editor preferences are not committed to the repository * fix(provider): preserve usage script during provider update - When updating a provider, the `usage_script` configuration within `ProviderMeta` was not explicitly merged. - This could lead to the accidental loss of `usage_script` settings if the incoming `provider` object in the update request did not contain this field. - Ensure `usage_script` is cloned from the existing provider's meta when merging `ProviderMeta` during an update. * refactor(provider): enforce base_url for usage scripts and update dev ports - 【Backend】 - `src-tauri/src/commands.rs`: Made `ANTHROPIC_BASE_URL` a required field for Claude providers and `base_url` a required field in `config.toml` for Codex providers when extracting credentials for usage script execution. This improves error handling by explicitly failing if these critical URLs are missing or malformed. - 【Frontend】 - `src/App.tsx`, `src/components/ProviderList.tsx`: Passed `appType` prop to `ProviderList` component to ensure `updateProvider` calls within `handleSaveUsageScript` correctly identify the application type. - 【Config】 - `src-tauri/tauri.conf.json`, `vite.config.mts`: Updated development server ports from `3005` to `3000` to standardize local development environment. * refactor(usage): improve usage data fetching logic - Prevent redundant API calls by tracking last fetched parameters in `useEffect`. - Avoid concurrent API requests by adding a guard in `fetchUsage`. - Clear usage data and last fetch parameters when usage query is disabled. - Add `queryProviderUsage` API declaration to `window.api` interface. * fix(usage-script): ensure usage script updates and improve reactivity - correctly update `usage_script` from new provider meta during updates - replace full page reload with targeted provider data refresh after saving usage script settings - trigger usage data fetch or clear when `usageEnabled` status changes in `UsageFooter` - reduce logging verbosity for usage script execution in backend commands and script execution * style(usage-footer): adjust usage plan item layout - Decrease width of extra field column from 35% to 30% - Increase width of usage information column from 40% to 45% - Improve visual balance and readability of usage plan items
2025-10-15 09:15:25 +08:00
language?: "json" | "javascript";
height?: string;
}
const JsonEditor: React.FC<JsonEditorProps> = ({
value,
onChange,
placeholder: placeholderText = "",
darkMode = false,
rows = 12,
showValidation = true,
feat: add provider usage query with JavaScript scripting support (#101) * feat: add provider usage query functionality - Updated `Cargo.toml` to include `regex` and `rquickjs` dependencies for usage script execution. - Implemented `query_provider_usage` command in `commands.rs` to handle usage queries. - Created `UsageScript` and `UsageData` structs in `provider.rs` for managing usage script configurations and results. - Added `execute_usage_script` function in `usage_script.rs` to run user-defined scripts for querying usage. - Enhanced `ProviderList` component to include a button for configuring usage scripts and a modal for editing scripts. - Introduced `UsageFooter` component to display usage information and status. - Added `UsageScriptModal` for editing and testing usage scripts with preset templates. - Updated Tauri API to support querying provider usage. - Modified types in `types.ts` to include structures for usage scripts and results. * feat(usage): support multi-plan usage display for providers - 【Feature】 - Update `UsageResult` to support an array of `UsageData` for displaying multiple usage plans per provider. - Refactor `query_provider_usage` command to parse both single `UsageData` objects (for backward compatibility) and arrays of `UsageData`. - Enhance `usage_script` validation to accept either a single usage object or an array of usage objects. - 【Frontend】 - Redesign `UsageFooter` to iterate and display details for all available usage plans, introducing `UsagePlanItem` for individual plan rendering. - Improve usage display with color-coded remaining balance and clear plan information. - Update `UsageScriptModal` test notification to summarize all returned plans. - Remove redundant `isCurrent` prop from `UsageFooter` in `ProviderList`. - 【Build】 - Change frontend development server port from `3000` to `3005` in `tauri.conf.json` and `vite.config.mts`. * feat(usage): enhance query flexibility and display - 【`src/types.ts`, `src-tauri/src/provider.rs`】Make `UsageData` fields optional and introduce `extra` and `invalidMessage` for more flexible reporting. - `expiresAt` replaced by generic `extra` field. - `isValid`, `remaining`, `unit` are now optional. - Added `invalidMessage` to provide specific reasons for invalid status. - 【`src-tauri/src/usage_script.rs`】Relax usage script result validation to accommodate optional fields in `UsageData`. - 【`src/components/UsageFooter.tsx`】Update UI to display `extra` field and `invalidMessage`, and conditionally render `remaining` and `unit` based on availability. - 【`src/components/UsageScriptModal.tsx`】 - Add a new `NewAPI` preset template demonstrating advanced extractor logic for complex API responses. - Update script instructions to reflect optional fields and new variable syntax (`{{apiKey}}`). - Remove old "DeepSeek" and "OpenAI" templates. - Remove basic syntax check for `return` statement. - 【`.vscode/settings.json`】Add `dish-ai-commit.base.language` setting. - 【`src-tauri/src/commands.rs`】Adjust usage logging to handle optional `remaining` and `unit` fields. * chore(config): remove VS Code settings from version control - delete .vscode/settings.json to remove editor-specific configurations - add /.vscode to .gitignore to prevent tracking of local VS Code settings - ensure personalized editor preferences are not committed to the repository * fix(provider): preserve usage script during provider update - When updating a provider, the `usage_script` configuration within `ProviderMeta` was not explicitly merged. - This could lead to the accidental loss of `usage_script` settings if the incoming `provider` object in the update request did not contain this field. - Ensure `usage_script` is cloned from the existing provider's meta when merging `ProviderMeta` during an update. * refactor(provider): enforce base_url for usage scripts and update dev ports - 【Backend】 - `src-tauri/src/commands.rs`: Made `ANTHROPIC_BASE_URL` a required field for Claude providers and `base_url` a required field in `config.toml` for Codex providers when extracting credentials for usage script execution. This improves error handling by explicitly failing if these critical URLs are missing or malformed. - 【Frontend】 - `src/App.tsx`, `src/components/ProviderList.tsx`: Passed `appType` prop to `ProviderList` component to ensure `updateProvider` calls within `handleSaveUsageScript` correctly identify the application type. - 【Config】 - `src-tauri/tauri.conf.json`, `vite.config.mts`: Updated development server ports from `3005` to `3000` to standardize local development environment. * refactor(usage): improve usage data fetching logic - Prevent redundant API calls by tracking last fetched parameters in `useEffect`. - Avoid concurrent API requests by adding a guard in `fetchUsage`. - Clear usage data and last fetch parameters when usage query is disabled. - Add `queryProviderUsage` API declaration to `window.api` interface. * fix(usage-script): ensure usage script updates and improve reactivity - correctly update `usage_script` from new provider meta during updates - replace full page reload with targeted provider data refresh after saving usage script settings - trigger usage data fetch or clear when `usageEnabled` status changes in `UsageFooter` - reduce logging verbosity for usage script execution in backend commands and script execution * style(usage-footer): adjust usage plan item layout - Decrease width of extra field column from 35% to 30% - Increase width of usage information column from 40% to 45% - Improve visual balance and readability of usage plan items
2025-10-15 09:15:25 +08:00
language = "json",
height,
}) => {
const { t } = useTranslation();
const editorRef = useRef<HTMLDivElement>(null);
const viewRef = useRef<EditorView | null>(null);
// JSON linter 函数
const jsonLinter = useMemo(
() =>
linter((view) => {
const diagnostics: Diagnostic[] = [];
feat: add provider usage query with JavaScript scripting support (#101) * feat: add provider usage query functionality - Updated `Cargo.toml` to include `regex` and `rquickjs` dependencies for usage script execution. - Implemented `query_provider_usage` command in `commands.rs` to handle usage queries. - Created `UsageScript` and `UsageData` structs in `provider.rs` for managing usage script configurations and results. - Added `execute_usage_script` function in `usage_script.rs` to run user-defined scripts for querying usage. - Enhanced `ProviderList` component to include a button for configuring usage scripts and a modal for editing scripts. - Introduced `UsageFooter` component to display usage information and status. - Added `UsageScriptModal` for editing and testing usage scripts with preset templates. - Updated Tauri API to support querying provider usage. - Modified types in `types.ts` to include structures for usage scripts and results. * feat(usage): support multi-plan usage display for providers - 【Feature】 - Update `UsageResult` to support an array of `UsageData` for displaying multiple usage plans per provider. - Refactor `query_provider_usage` command to parse both single `UsageData` objects (for backward compatibility) and arrays of `UsageData`. - Enhance `usage_script` validation to accept either a single usage object or an array of usage objects. - 【Frontend】 - Redesign `UsageFooter` to iterate and display details for all available usage plans, introducing `UsagePlanItem` for individual plan rendering. - Improve usage display with color-coded remaining balance and clear plan information. - Update `UsageScriptModal` test notification to summarize all returned plans. - Remove redundant `isCurrent` prop from `UsageFooter` in `ProviderList`. - 【Build】 - Change frontend development server port from `3000` to `3005` in `tauri.conf.json` and `vite.config.mts`. * feat(usage): enhance query flexibility and display - 【`src/types.ts`, `src-tauri/src/provider.rs`】Make `UsageData` fields optional and introduce `extra` and `invalidMessage` for more flexible reporting. - `expiresAt` replaced by generic `extra` field. - `isValid`, `remaining`, `unit` are now optional. - Added `invalidMessage` to provide specific reasons for invalid status. - 【`src-tauri/src/usage_script.rs`】Relax usage script result validation to accommodate optional fields in `UsageData`. - 【`src/components/UsageFooter.tsx`】Update UI to display `extra` field and `invalidMessage`, and conditionally render `remaining` and `unit` based on availability. - 【`src/components/UsageScriptModal.tsx`】 - Add a new `NewAPI` preset template demonstrating advanced extractor logic for complex API responses. - Update script instructions to reflect optional fields and new variable syntax (`{{apiKey}}`). - Remove old "DeepSeek" and "OpenAI" templates. - Remove basic syntax check for `return` statement. - 【`.vscode/settings.json`】Add `dish-ai-commit.base.language` setting. - 【`src-tauri/src/commands.rs`】Adjust usage logging to handle optional `remaining` and `unit` fields. * chore(config): remove VS Code settings from version control - delete .vscode/settings.json to remove editor-specific configurations - add /.vscode to .gitignore to prevent tracking of local VS Code settings - ensure personalized editor preferences are not committed to the repository * fix(provider): preserve usage script during provider update - When updating a provider, the `usage_script` configuration within `ProviderMeta` was not explicitly merged. - This could lead to the accidental loss of `usage_script` settings if the incoming `provider` object in the update request did not contain this field. - Ensure `usage_script` is cloned from the existing provider's meta when merging `ProviderMeta` during an update. * refactor(provider): enforce base_url for usage scripts and update dev ports - 【Backend】 - `src-tauri/src/commands.rs`: Made `ANTHROPIC_BASE_URL` a required field for Claude providers and `base_url` a required field in `config.toml` for Codex providers when extracting credentials for usage script execution. This improves error handling by explicitly failing if these critical URLs are missing or malformed. - 【Frontend】 - `src/App.tsx`, `src/components/ProviderList.tsx`: Passed `appType` prop to `ProviderList` component to ensure `updateProvider` calls within `handleSaveUsageScript` correctly identify the application type. - 【Config】 - `src-tauri/tauri.conf.json`, `vite.config.mts`: Updated development server ports from `3005` to `3000` to standardize local development environment. * refactor(usage): improve usage data fetching logic - Prevent redundant API calls by tracking last fetched parameters in `useEffect`. - Avoid concurrent API requests by adding a guard in `fetchUsage`. - Clear usage data and last fetch parameters when usage query is disabled. - Add `queryProviderUsage` API declaration to `window.api` interface. * fix(usage-script): ensure usage script updates and improve reactivity - correctly update `usage_script` from new provider meta during updates - replace full page reload with targeted provider data refresh after saving usage script settings - trigger usage data fetch or clear when `usageEnabled` status changes in `UsageFooter` - reduce logging verbosity for usage script execution in backend commands and script execution * style(usage-footer): adjust usage plan item layout - Decrease width of extra field column from 35% to 30% - Increase width of usage information column from 40% to 45% - Improve visual balance and readability of usage plan items
2025-10-15 09:15:25 +08:00
if (!showValidation || language !== "json") return diagnostics;
const doc = view.state.doc.toString();
if (!doc.trim()) return diagnostics;
try {
const parsed = JSON.parse(doc);
// 检查是否是JSON对象
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
// 格式正确
} else {
diagnostics.push({
from: 0,
to: doc.length,
severity: "error",
message: t("jsonEditor.mustBeObject"),
});
}
} catch (e) {
// 简单处理JSON解析错误
const message =
e instanceof SyntaxError ? e.message : t("jsonEditor.invalidJson");
diagnostics.push({
from: 0,
to: doc.length,
severity: "error",
message,
});
}
return diagnostics;
}),
feat: add provider usage query with JavaScript scripting support (#101) * feat: add provider usage query functionality - Updated `Cargo.toml` to include `regex` and `rquickjs` dependencies for usage script execution. - Implemented `query_provider_usage` command in `commands.rs` to handle usage queries. - Created `UsageScript` and `UsageData` structs in `provider.rs` for managing usage script configurations and results. - Added `execute_usage_script` function in `usage_script.rs` to run user-defined scripts for querying usage. - Enhanced `ProviderList` component to include a button for configuring usage scripts and a modal for editing scripts. - Introduced `UsageFooter` component to display usage information and status. - Added `UsageScriptModal` for editing and testing usage scripts with preset templates. - Updated Tauri API to support querying provider usage. - Modified types in `types.ts` to include structures for usage scripts and results. * feat(usage): support multi-plan usage display for providers - 【Feature】 - Update `UsageResult` to support an array of `UsageData` for displaying multiple usage plans per provider. - Refactor `query_provider_usage` command to parse both single `UsageData` objects (for backward compatibility) and arrays of `UsageData`. - Enhance `usage_script` validation to accept either a single usage object or an array of usage objects. - 【Frontend】 - Redesign `UsageFooter` to iterate and display details for all available usage plans, introducing `UsagePlanItem` for individual plan rendering. - Improve usage display with color-coded remaining balance and clear plan information. - Update `UsageScriptModal` test notification to summarize all returned plans. - Remove redundant `isCurrent` prop from `UsageFooter` in `ProviderList`. - 【Build】 - Change frontend development server port from `3000` to `3005` in `tauri.conf.json` and `vite.config.mts`. * feat(usage): enhance query flexibility and display - 【`src/types.ts`, `src-tauri/src/provider.rs`】Make `UsageData` fields optional and introduce `extra` and `invalidMessage` for more flexible reporting. - `expiresAt` replaced by generic `extra` field. - `isValid`, `remaining`, `unit` are now optional. - Added `invalidMessage` to provide specific reasons for invalid status. - 【`src-tauri/src/usage_script.rs`】Relax usage script result validation to accommodate optional fields in `UsageData`. - 【`src/components/UsageFooter.tsx`】Update UI to display `extra` field and `invalidMessage`, and conditionally render `remaining` and `unit` based on availability. - 【`src/components/UsageScriptModal.tsx`】 - Add a new `NewAPI` preset template demonstrating advanced extractor logic for complex API responses. - Update script instructions to reflect optional fields and new variable syntax (`{{apiKey}}`). - Remove old "DeepSeek" and "OpenAI" templates. - Remove basic syntax check for `return` statement. - 【`.vscode/settings.json`】Add `dish-ai-commit.base.language` setting. - 【`src-tauri/src/commands.rs`】Adjust usage logging to handle optional `remaining` and `unit` fields. * chore(config): remove VS Code settings from version control - delete .vscode/settings.json to remove editor-specific configurations - add /.vscode to .gitignore to prevent tracking of local VS Code settings - ensure personalized editor preferences are not committed to the repository * fix(provider): preserve usage script during provider update - When updating a provider, the `usage_script` configuration within `ProviderMeta` was not explicitly merged. - This could lead to the accidental loss of `usage_script` settings if the incoming `provider` object in the update request did not contain this field. - Ensure `usage_script` is cloned from the existing provider's meta when merging `ProviderMeta` during an update. * refactor(provider): enforce base_url for usage scripts and update dev ports - 【Backend】 - `src-tauri/src/commands.rs`: Made `ANTHROPIC_BASE_URL` a required field for Claude providers and `base_url` a required field in `config.toml` for Codex providers when extracting credentials for usage script execution. This improves error handling by explicitly failing if these critical URLs are missing or malformed. - 【Frontend】 - `src/App.tsx`, `src/components/ProviderList.tsx`: Passed `appType` prop to `ProviderList` component to ensure `updateProvider` calls within `handleSaveUsageScript` correctly identify the application type. - 【Config】 - `src-tauri/tauri.conf.json`, `vite.config.mts`: Updated development server ports from `3005` to `3000` to standardize local development environment. * refactor(usage): improve usage data fetching logic - Prevent redundant API calls by tracking last fetched parameters in `useEffect`. - Avoid concurrent API requests by adding a guard in `fetchUsage`. - Clear usage data and last fetch parameters when usage query is disabled. - Add `queryProviderUsage` API declaration to `window.api` interface. * fix(usage-script): ensure usage script updates and improve reactivity - correctly update `usage_script` from new provider meta during updates - replace full page reload with targeted provider data refresh after saving usage script settings - trigger usage data fetch or clear when `usageEnabled` status changes in `UsageFooter` - reduce logging verbosity for usage script execution in backend commands and script execution * style(usage-footer): adjust usage plan item layout - Decrease width of extra field column from 35% to 30% - Increase width of usage information column from 40% to 45% - Improve visual balance and readability of usage plan items
2025-10-15 09:15:25 +08:00
[showValidation, language, t],
);
useEffect(() => {
if (!editorRef.current) return;
// 创建编辑器扩展
feat: add provider usage query with JavaScript scripting support (#101) * feat: add provider usage query functionality - Updated `Cargo.toml` to include `regex` and `rquickjs` dependencies for usage script execution. - Implemented `query_provider_usage` command in `commands.rs` to handle usage queries. - Created `UsageScript` and `UsageData` structs in `provider.rs` for managing usage script configurations and results. - Added `execute_usage_script` function in `usage_script.rs` to run user-defined scripts for querying usage. - Enhanced `ProviderList` component to include a button for configuring usage scripts and a modal for editing scripts. - Introduced `UsageFooter` component to display usage information and status. - Added `UsageScriptModal` for editing and testing usage scripts with preset templates. - Updated Tauri API to support querying provider usage. - Modified types in `types.ts` to include structures for usage scripts and results. * feat(usage): support multi-plan usage display for providers - 【Feature】 - Update `UsageResult` to support an array of `UsageData` for displaying multiple usage plans per provider. - Refactor `query_provider_usage` command to parse both single `UsageData` objects (for backward compatibility) and arrays of `UsageData`. - Enhance `usage_script` validation to accept either a single usage object or an array of usage objects. - 【Frontend】 - Redesign `UsageFooter` to iterate and display details for all available usage plans, introducing `UsagePlanItem` for individual plan rendering. - Improve usage display with color-coded remaining balance and clear plan information. - Update `UsageScriptModal` test notification to summarize all returned plans. - Remove redundant `isCurrent` prop from `UsageFooter` in `ProviderList`. - 【Build】 - Change frontend development server port from `3000` to `3005` in `tauri.conf.json` and `vite.config.mts`. * feat(usage): enhance query flexibility and display - 【`src/types.ts`, `src-tauri/src/provider.rs`】Make `UsageData` fields optional and introduce `extra` and `invalidMessage` for more flexible reporting. - `expiresAt` replaced by generic `extra` field. - `isValid`, `remaining`, `unit` are now optional. - Added `invalidMessage` to provide specific reasons for invalid status. - 【`src-tauri/src/usage_script.rs`】Relax usage script result validation to accommodate optional fields in `UsageData`. - 【`src/components/UsageFooter.tsx`】Update UI to display `extra` field and `invalidMessage`, and conditionally render `remaining` and `unit` based on availability. - 【`src/components/UsageScriptModal.tsx`】 - Add a new `NewAPI` preset template demonstrating advanced extractor logic for complex API responses. - Update script instructions to reflect optional fields and new variable syntax (`{{apiKey}}`). - Remove old "DeepSeek" and "OpenAI" templates. - Remove basic syntax check for `return` statement. - 【`.vscode/settings.json`】Add `dish-ai-commit.base.language` setting. - 【`src-tauri/src/commands.rs`】Adjust usage logging to handle optional `remaining` and `unit` fields. * chore(config): remove VS Code settings from version control - delete .vscode/settings.json to remove editor-specific configurations - add /.vscode to .gitignore to prevent tracking of local VS Code settings - ensure personalized editor preferences are not committed to the repository * fix(provider): preserve usage script during provider update - When updating a provider, the `usage_script` configuration within `ProviderMeta` was not explicitly merged. - This could lead to the accidental loss of `usage_script` settings if the incoming `provider` object in the update request did not contain this field. - Ensure `usage_script` is cloned from the existing provider's meta when merging `ProviderMeta` during an update. * refactor(provider): enforce base_url for usage scripts and update dev ports - 【Backend】 - `src-tauri/src/commands.rs`: Made `ANTHROPIC_BASE_URL` a required field for Claude providers and `base_url` a required field in `config.toml` for Codex providers when extracting credentials for usage script execution. This improves error handling by explicitly failing if these critical URLs are missing or malformed. - 【Frontend】 - `src/App.tsx`, `src/components/ProviderList.tsx`: Passed `appType` prop to `ProviderList` component to ensure `updateProvider` calls within `handleSaveUsageScript` correctly identify the application type. - 【Config】 - `src-tauri/tauri.conf.json`, `vite.config.mts`: Updated development server ports from `3005` to `3000` to standardize local development environment. * refactor(usage): improve usage data fetching logic - Prevent redundant API calls by tracking last fetched parameters in `useEffect`. - Avoid concurrent API requests by adding a guard in `fetchUsage`. - Clear usage data and last fetch parameters when usage query is disabled. - Add `queryProviderUsage` API declaration to `window.api` interface. * fix(usage-script): ensure usage script updates and improve reactivity - correctly update `usage_script` from new provider meta during updates - replace full page reload with targeted provider data refresh after saving usage script settings - trigger usage data fetch or clear when `usageEnabled` status changes in `UsageFooter` - reduce logging verbosity for usage script execution in backend commands and script execution * style(usage-footer): adjust usage plan item layout - Decrease width of extra field column from 35% to 30% - Increase width of usage information column from 40% to 45% - Improve visual balance and readability of usage plan items
2025-10-15 09:15:25 +08:00
const minHeightPx = height ? undefined : Math.max(1, rows) * 18;
// 使用 baseTheme 定义基础样式,优先级低于 oneDark但可以正确响应主题
const baseTheme = EditorView.baseTheme({
"&light .cm-editor, &dark .cm-editor": {
border: "1px solid hsl(var(--border))",
borderRadius: "0.5rem",
},
"&light .cm-editor.cm-focused, &dark .cm-editor.cm-focused": {
outline: "none",
borderColor: "hsl(var(--primary))",
},
});
// 使用 theme 定义尺寸和字体样式
const sizingTheme = EditorView.theme({
feat: add provider usage query with JavaScript scripting support (#101) * feat: add provider usage query functionality - Updated `Cargo.toml` to include `regex` and `rquickjs` dependencies for usage script execution. - Implemented `query_provider_usage` command in `commands.rs` to handle usage queries. - Created `UsageScript` and `UsageData` structs in `provider.rs` for managing usage script configurations and results. - Added `execute_usage_script` function in `usage_script.rs` to run user-defined scripts for querying usage. - Enhanced `ProviderList` component to include a button for configuring usage scripts and a modal for editing scripts. - Introduced `UsageFooter` component to display usage information and status. - Added `UsageScriptModal` for editing and testing usage scripts with preset templates. - Updated Tauri API to support querying provider usage. - Modified types in `types.ts` to include structures for usage scripts and results. * feat(usage): support multi-plan usage display for providers - 【Feature】 - Update `UsageResult` to support an array of `UsageData` for displaying multiple usage plans per provider. - Refactor `query_provider_usage` command to parse both single `UsageData` objects (for backward compatibility) and arrays of `UsageData`. - Enhance `usage_script` validation to accept either a single usage object or an array of usage objects. - 【Frontend】 - Redesign `UsageFooter` to iterate and display details for all available usage plans, introducing `UsagePlanItem` for individual plan rendering. - Improve usage display with color-coded remaining balance and clear plan information. - Update `UsageScriptModal` test notification to summarize all returned plans. - Remove redundant `isCurrent` prop from `UsageFooter` in `ProviderList`. - 【Build】 - Change frontend development server port from `3000` to `3005` in `tauri.conf.json` and `vite.config.mts`. * feat(usage): enhance query flexibility and display - 【`src/types.ts`, `src-tauri/src/provider.rs`】Make `UsageData` fields optional and introduce `extra` and `invalidMessage` for more flexible reporting. - `expiresAt` replaced by generic `extra` field. - `isValid`, `remaining`, `unit` are now optional. - Added `invalidMessage` to provide specific reasons for invalid status. - 【`src-tauri/src/usage_script.rs`】Relax usage script result validation to accommodate optional fields in `UsageData`. - 【`src/components/UsageFooter.tsx`】Update UI to display `extra` field and `invalidMessage`, and conditionally render `remaining` and `unit` based on availability. - 【`src/components/UsageScriptModal.tsx`】 - Add a new `NewAPI` preset template demonstrating advanced extractor logic for complex API responses. - Update script instructions to reflect optional fields and new variable syntax (`{{apiKey}}`). - Remove old "DeepSeek" and "OpenAI" templates. - Remove basic syntax check for `return` statement. - 【`.vscode/settings.json`】Add `dish-ai-commit.base.language` setting. - 【`src-tauri/src/commands.rs`】Adjust usage logging to handle optional `remaining` and `unit` fields. * chore(config): remove VS Code settings from version control - delete .vscode/settings.json to remove editor-specific configurations - add /.vscode to .gitignore to prevent tracking of local VS Code settings - ensure personalized editor preferences are not committed to the repository * fix(provider): preserve usage script during provider update - When updating a provider, the `usage_script` configuration within `ProviderMeta` was not explicitly merged. - This could lead to the accidental loss of `usage_script` settings if the incoming `provider` object in the update request did not contain this field. - Ensure `usage_script` is cloned from the existing provider's meta when merging `ProviderMeta` during an update. * refactor(provider): enforce base_url for usage scripts and update dev ports - 【Backend】 - `src-tauri/src/commands.rs`: Made `ANTHROPIC_BASE_URL` a required field for Claude providers and `base_url` a required field in `config.toml` for Codex providers when extracting credentials for usage script execution. This improves error handling by explicitly failing if these critical URLs are missing or malformed. - 【Frontend】 - `src/App.tsx`, `src/components/ProviderList.tsx`: Passed `appType` prop to `ProviderList` component to ensure `updateProvider` calls within `handleSaveUsageScript` correctly identify the application type. - 【Config】 - `src-tauri/tauri.conf.json`, `vite.config.mts`: Updated development server ports from `3005` to `3000` to standardize local development environment. * refactor(usage): improve usage data fetching logic - Prevent redundant API calls by tracking last fetched parameters in `useEffect`. - Avoid concurrent API requests by adding a guard in `fetchUsage`. - Clear usage data and last fetch parameters when usage query is disabled. - Add `queryProviderUsage` API declaration to `window.api` interface. * fix(usage-script): ensure usage script updates and improve reactivity - correctly update `usage_script` from new provider meta during updates - replace full page reload with targeted provider data refresh after saving usage script settings - trigger usage data fetch or clear when `usageEnabled` status changes in `UsageFooter` - reduce logging verbosity for usage script execution in backend commands and script execution * style(usage-footer): adjust usage plan item layout - Decrease width of extra field column from 35% to 30% - Increase width of usage information column from 40% to 45% - Improve visual balance and readability of usage plan items
2025-10-15 09:15:25 +08:00
"&": height ? { height } : { minHeight: `${minHeightPx}px` },
".cm-scroller": { overflow: "auto" },
".cm-content": {
fontFamily:
"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace",
fontSize: "14px",
},
});
const extensions = [
basicSetup,
feat: add provider usage query with JavaScript scripting support (#101) * feat: add provider usage query functionality - Updated `Cargo.toml` to include `regex` and `rquickjs` dependencies for usage script execution. - Implemented `query_provider_usage` command in `commands.rs` to handle usage queries. - Created `UsageScript` and `UsageData` structs in `provider.rs` for managing usage script configurations and results. - Added `execute_usage_script` function in `usage_script.rs` to run user-defined scripts for querying usage. - Enhanced `ProviderList` component to include a button for configuring usage scripts and a modal for editing scripts. - Introduced `UsageFooter` component to display usage information and status. - Added `UsageScriptModal` for editing and testing usage scripts with preset templates. - Updated Tauri API to support querying provider usage. - Modified types in `types.ts` to include structures for usage scripts and results. * feat(usage): support multi-plan usage display for providers - 【Feature】 - Update `UsageResult` to support an array of `UsageData` for displaying multiple usage plans per provider. - Refactor `query_provider_usage` command to parse both single `UsageData` objects (for backward compatibility) and arrays of `UsageData`. - Enhance `usage_script` validation to accept either a single usage object or an array of usage objects. - 【Frontend】 - Redesign `UsageFooter` to iterate and display details for all available usage plans, introducing `UsagePlanItem` for individual plan rendering. - Improve usage display with color-coded remaining balance and clear plan information. - Update `UsageScriptModal` test notification to summarize all returned plans. - Remove redundant `isCurrent` prop from `UsageFooter` in `ProviderList`. - 【Build】 - Change frontend development server port from `3000` to `3005` in `tauri.conf.json` and `vite.config.mts`. * feat(usage): enhance query flexibility and display - 【`src/types.ts`, `src-tauri/src/provider.rs`】Make `UsageData` fields optional and introduce `extra` and `invalidMessage` for more flexible reporting. - `expiresAt` replaced by generic `extra` field. - `isValid`, `remaining`, `unit` are now optional. - Added `invalidMessage` to provide specific reasons for invalid status. - 【`src-tauri/src/usage_script.rs`】Relax usage script result validation to accommodate optional fields in `UsageData`. - 【`src/components/UsageFooter.tsx`】Update UI to display `extra` field and `invalidMessage`, and conditionally render `remaining` and `unit` based on availability. - 【`src/components/UsageScriptModal.tsx`】 - Add a new `NewAPI` preset template demonstrating advanced extractor logic for complex API responses. - Update script instructions to reflect optional fields and new variable syntax (`{{apiKey}}`). - Remove old "DeepSeek" and "OpenAI" templates. - Remove basic syntax check for `return` statement. - 【`.vscode/settings.json`】Add `dish-ai-commit.base.language` setting. - 【`src-tauri/src/commands.rs`】Adjust usage logging to handle optional `remaining` and `unit` fields. * chore(config): remove VS Code settings from version control - delete .vscode/settings.json to remove editor-specific configurations - add /.vscode to .gitignore to prevent tracking of local VS Code settings - ensure personalized editor preferences are not committed to the repository * fix(provider): preserve usage script during provider update - When updating a provider, the `usage_script` configuration within `ProviderMeta` was not explicitly merged. - This could lead to the accidental loss of `usage_script` settings if the incoming `provider` object in the update request did not contain this field. - Ensure `usage_script` is cloned from the existing provider's meta when merging `ProviderMeta` during an update. * refactor(provider): enforce base_url for usage scripts and update dev ports - 【Backend】 - `src-tauri/src/commands.rs`: Made `ANTHROPIC_BASE_URL` a required field for Claude providers and `base_url` a required field in `config.toml` for Codex providers when extracting credentials for usage script execution. This improves error handling by explicitly failing if these critical URLs are missing or malformed. - 【Frontend】 - `src/App.tsx`, `src/components/ProviderList.tsx`: Passed `appType` prop to `ProviderList` component to ensure `updateProvider` calls within `handleSaveUsageScript` correctly identify the application type. - 【Config】 - `src-tauri/tauri.conf.json`, `vite.config.mts`: Updated development server ports from `3005` to `3000` to standardize local development environment. * refactor(usage): improve usage data fetching logic - Prevent redundant API calls by tracking last fetched parameters in `useEffect`. - Avoid concurrent API requests by adding a guard in `fetchUsage`. - Clear usage data and last fetch parameters when usage query is disabled. - Add `queryProviderUsage` API declaration to `window.api` interface. * fix(usage-script): ensure usage script updates and improve reactivity - correctly update `usage_script` from new provider meta during updates - replace full page reload with targeted provider data refresh after saving usage script settings - trigger usage data fetch or clear when `usageEnabled` status changes in `UsageFooter` - reduce logging verbosity for usage script execution in backend commands and script execution * style(usage-footer): adjust usage plan item layout - Decrease width of extra field column from 35% to 30% - Increase width of usage information column from 40% to 45% - Improve visual balance and readability of usage plan items
2025-10-15 09:15:25 +08:00
language === "javascript" ? javascript() : json(),
placeholder(placeholderText || ""),
baseTheme,
sizingTheme,
jsonLinter,
EditorView.updateListener.of((update) => {
if (update.docChanged) {
const newValue = update.state.doc.toString();
onChange(newValue);
}
}),
];
// 如果启用深色模式,添加深色主题
if (darkMode) {
extensions.push(oneDark);
// 在 oneDark 之后强制覆盖边框样式
extensions.push(
EditorView.theme({
".cm-editor": {
border: "1px solid hsl(var(--border))",
borderRadius: "0.5rem",
},
".cm-editor.cm-focused": {
outline: "none",
borderColor: "hsl(var(--primary))",
},
}),
);
}
// 创建初始状态
const state = EditorState.create({
doc: value,
extensions,
});
// 创建编辑器视图
const view = new EditorView({
state,
parent: editorRef.current,
});
viewRef.current = view;
// 清理函数
return () => {
view.destroy();
viewRef.current = null;
};
feat: add provider usage query with JavaScript scripting support (#101) * feat: add provider usage query functionality - Updated `Cargo.toml` to include `regex` and `rquickjs` dependencies for usage script execution. - Implemented `query_provider_usage` command in `commands.rs` to handle usage queries. - Created `UsageScript` and `UsageData` structs in `provider.rs` for managing usage script configurations and results. - Added `execute_usage_script` function in `usage_script.rs` to run user-defined scripts for querying usage. - Enhanced `ProviderList` component to include a button for configuring usage scripts and a modal for editing scripts. - Introduced `UsageFooter` component to display usage information and status. - Added `UsageScriptModal` for editing and testing usage scripts with preset templates. - Updated Tauri API to support querying provider usage. - Modified types in `types.ts` to include structures for usage scripts and results. * feat(usage): support multi-plan usage display for providers - 【Feature】 - Update `UsageResult` to support an array of `UsageData` for displaying multiple usage plans per provider. - Refactor `query_provider_usage` command to parse both single `UsageData` objects (for backward compatibility) and arrays of `UsageData`. - Enhance `usage_script` validation to accept either a single usage object or an array of usage objects. - 【Frontend】 - Redesign `UsageFooter` to iterate and display details for all available usage plans, introducing `UsagePlanItem` for individual plan rendering. - Improve usage display with color-coded remaining balance and clear plan information. - Update `UsageScriptModal` test notification to summarize all returned plans. - Remove redundant `isCurrent` prop from `UsageFooter` in `ProviderList`. - 【Build】 - Change frontend development server port from `3000` to `3005` in `tauri.conf.json` and `vite.config.mts`. * feat(usage): enhance query flexibility and display - 【`src/types.ts`, `src-tauri/src/provider.rs`】Make `UsageData` fields optional and introduce `extra` and `invalidMessage` for more flexible reporting. - `expiresAt` replaced by generic `extra` field. - `isValid`, `remaining`, `unit` are now optional. - Added `invalidMessage` to provide specific reasons for invalid status. - 【`src-tauri/src/usage_script.rs`】Relax usage script result validation to accommodate optional fields in `UsageData`. - 【`src/components/UsageFooter.tsx`】Update UI to display `extra` field and `invalidMessage`, and conditionally render `remaining` and `unit` based on availability. - 【`src/components/UsageScriptModal.tsx`】 - Add a new `NewAPI` preset template demonstrating advanced extractor logic for complex API responses. - Update script instructions to reflect optional fields and new variable syntax (`{{apiKey}}`). - Remove old "DeepSeek" and "OpenAI" templates. - Remove basic syntax check for `return` statement. - 【`.vscode/settings.json`】Add `dish-ai-commit.base.language` setting. - 【`src-tauri/src/commands.rs`】Adjust usage logging to handle optional `remaining` and `unit` fields. * chore(config): remove VS Code settings from version control - delete .vscode/settings.json to remove editor-specific configurations - add /.vscode to .gitignore to prevent tracking of local VS Code settings - ensure personalized editor preferences are not committed to the repository * fix(provider): preserve usage script during provider update - When updating a provider, the `usage_script` configuration within `ProviderMeta` was not explicitly merged. - This could lead to the accidental loss of `usage_script` settings if the incoming `provider` object in the update request did not contain this field. - Ensure `usage_script` is cloned from the existing provider's meta when merging `ProviderMeta` during an update. * refactor(provider): enforce base_url for usage scripts and update dev ports - 【Backend】 - `src-tauri/src/commands.rs`: Made `ANTHROPIC_BASE_URL` a required field for Claude providers and `base_url` a required field in `config.toml` for Codex providers when extracting credentials for usage script execution. This improves error handling by explicitly failing if these critical URLs are missing or malformed. - 【Frontend】 - `src/App.tsx`, `src/components/ProviderList.tsx`: Passed `appType` prop to `ProviderList` component to ensure `updateProvider` calls within `handleSaveUsageScript` correctly identify the application type. - 【Config】 - `src-tauri/tauri.conf.json`, `vite.config.mts`: Updated development server ports from `3005` to `3000` to standardize local development environment. * refactor(usage): improve usage data fetching logic - Prevent redundant API calls by tracking last fetched parameters in `useEffect`. - Avoid concurrent API requests by adding a guard in `fetchUsage`. - Clear usage data and last fetch parameters when usage query is disabled. - Add `queryProviderUsage` API declaration to `window.api` interface. * fix(usage-script): ensure usage script updates and improve reactivity - correctly update `usage_script` from new provider meta during updates - replace full page reload with targeted provider data refresh after saving usage script settings - trigger usage data fetch or clear when `usageEnabled` status changes in `UsageFooter` - reduce logging verbosity for usage script execution in backend commands and script execution * style(usage-footer): adjust usage plan item layout - Decrease width of extra field column from 35% to 30% - Increase width of usage information column from 40% to 45% - Improve visual balance and readability of usage plan items
2025-10-15 09:15:25 +08:00
}, [darkMode, rows, height, language, jsonLinter]); // 依赖项中不包含 onChange 和 placeholder避免不必要的重建
// 当 value 从外部改变时更新编辑器内容
useEffect(() => {
if (viewRef.current && viewRef.current.state.doc.toString() !== value) {
const transaction = viewRef.current.state.update({
changes: {
from: 0,
to: viewRef.current.state.doc.length,
insert: value,
},
});
viewRef.current.dispatch(transaction);
}
}, [value]);
// 格式化处理函数
const handleFormat = () => {
if (!viewRef.current) return;
const currentValue = viewRef.current.state.doc.toString();
if (!currentValue.trim()) return;
try {
const formatted = formatJSON(currentValue);
onChange(formatted);
toast.success(t("common.formatSuccess", { defaultValue: "格式化成功" }));
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : String(error);
toast.error(
t("common.formatError", {
defaultValue: "格式化失败:{{error}}",
error: errorMessage,
}),
);
}
};
return (
<div style={{ width: "100%" }}>
<div ref={editorRef} style={{ width: "100%" }} />
{language === "json" && (
<button
type="button"
onClick={handleFormat}
className="mt-2 inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-gray-700 dark:text-gray-300 hover:text-blue-600 dark:hover:text-blue-400 transition-colors"
>
<Wand2 className="w-3.5 h-3.5" />
{t("common.format", { defaultValue: "格式化" })}
</button>
)}
</div>
);
};
export default JsonEditor;