diff --git a/RefactorPlan.md b/RefactorPlan.md index 7c991e74..e24db8e2 100644 --- a/RefactorPlan.md +++ b/RefactorPlan.md @@ -25,7 +25,7 @@ validated, and what remains uncertain. | Assessment and baseline design | Complete | Initial architecture, risks, sequencing, and validation matrix documented | | Retire legacy AI settings and fallbacks | Complete | Removed the retired migration, schema/default fields, GPT reset, and AI runtime fallbacks without filtering unknown persisted keys; manual testing found no issues | | Extract settings implementation service | Implemented; awaiting manual validation | `PluginSettingsManager` now owns persistence, default assembly, remaining migrations, and API-key obfuscation; plugin methods and startup readiness remain intact, while temporary autosave enablement is now explicit plugin-instance state rather than persisted settings state | -| Migrate the settings tab to declarative settings with legacy fallback | Checkpoint 4A complete | Extracted the canonical row specifications, legacy renderer, declarative converter, typed binding registry, and focus-safe coalesced persistence queue. The persistence diagnosis and recovery correction are complete and manually validated. Checkpoint 4A now stages compact Basic and Saving navigation pages with descriptions on folded declarative navigation entries and opened declarative pages; legacy mode displays each description only once, before its fold. One `SettingsPageModel` tree owns the Basic/Saving hierarchy, descriptions, leaf definition builders, and legacy leaf renderers: both modes therefore use Updates and startup, Files and folders, Stencil Library, Storage and autosave, and Filename with Automation scripts inside Files and folders. The shared compact Copy settings/NotebookLM/help/support toolbar renders in both modes, while Mastery remains root-only; legacy mode additionally keeps its custom search. On Obsidian 1.13+, a persisted top-level preference defaults to the searchable declarative interface and can select the legacy single-page interface for the next Obsidian session; older versions always use legacy and do not show the preference. Markdown export recursively traverses declarations and places the control type before the description. The remaining sections stay intentionally absent during this partial declarative test and will be added in 4B-4E. The dependency/minimum version remains `1.8.7` | +| Migrate the settings tab to declarative settings with legacy fallback | Checkpoint 4B complete | Checkpoint 4A established the shared shell, persistence bridge, Basic/Saving pages, layout preference, toolbar, and recursive Markdown export. Checkpoint 4B extends the same `SettingsPageModel` tree to Excalidraw appearance and behavior plus Links, transclusion and TODOs. Both modes now share logical Editing and previews, UI modes, Hotkeys, Theme, Zoom and pan, Pen, Grid, Laser, modifier-key, link behavior/opening/appearance, TODO, and transclusion groups. Manual validation covered the 4B settings UI and drove shared fixes for complex-component width, initial disabled state, and settings-triggered viewport preservation. The remaining sections stay intentionally absent from the declarative test interface until 4C-4E. The dependency/minimum version remains `1.8.7` | | Extract footer safe-area styling | Implemented; awaiting manual validation | `FooterSafeAreaManager` now owns device-specific stylesheet injection, open-document traversal, and unload cleanup; the plugin method remains as a settings-UI compatibility delegate | | Extract font management | Implemented; awaiting manual validation | `FontManager` now owns CJK discovery/loading, custom-font registration, document stylesheets, readiness, and cleanup; plugin methods and the externally read `fourthFontLoaded` field remain intact | | Extract startup instrumentation | Implemented; awaiting manual validation | `StartupTimer` now owns startup event history, delta tracking, and breakdown formatting; lifecycle calls, public methods, and the public `loadTimestamp` field remain intact | @@ -62,6 +62,10 @@ validated, and what remains uncertain. | Date | Action | Outcome | Validation | | --- | --- | --- | --- | +| 2026-08-23 | Completed final checkpoint-4B duplication/dead-code review | Confirmed the apparent legacy/declarative repetition around grid, laser, modifier, and transclusion controls is host-specific metadata/layout around shared control configurators, not duplicated behavior. No obsolete component, helper, import, locale key, or independent legacy implementation remains from the converted sections. Consolidated the duplicated viewport-filter calculation in `loadDrawing()` into one shared app-state value and added release-note coverage for viewport preservation and the maintainer-supplied completed-TODO default. No broader cleanup was mixed into the checkpoint | Node 22.22.2; targeted ESLint passed for settings, adapter, modifier component, release notes, and all maintained locales; `npm run code:unused`, `npm run build`, `npm run lib`, `node --check dist/main.js`, `git diff --check`, and the unchanged `1.8.7` dependency/minimum assertion passed. The build retains the established 33 circular-dependency warnings, and `ExcalidrawView.ts` retains exactly its existing 18 `no-unsafe-*` findings. User validation confirmed 4B overall and authorized commit after this review | +| 2026-08-23 | Preserved live viewports during rendering-related settings reloads | Toggling Parse TODO correctly requires open drawings to rebuild parsed scene content, but the settings queue used the general full reload path. When a view had no dirty drawing edits, its current navigation-only scroll/zoom was intentionally absent from disk, so the reload restored an older persisted viewport and visibly jumped. Added `ExcalidrawView.reloadAfterSettingsChange()` and routed only the settings action through it. It reuses the view's established multiple-leaf reload behavior by omitting `scrollX`, `scrollY`, and `zoom` from the incoming app state; Excalidraw therefore retains the live values while elements and setting-derived rendering refresh. General file-event, sync, save, and ordinary reload behavior remains unchanged | Targeted settings ESLint, `npm run code:unused`, `npm run build`, `npm run lib`, `node --check dist/main.js`, `git diff --check`, and the unchanged `1.8.7` dependency/minimum assertion passed; the production build retains the established 33 circular-dependency warnings. `ExcalidrawView.ts` retains exactly its existing 18 `no-unsafe-*` findings, with no new lint finding from this change. Focused manual retest pending: pan and zoom an otherwise-clean open drawing, toggle Parse TODO, and verify the TODO rendering changes without moving the viewport; repeat once with an actual TODO text element and once with Zoom to fit on open enabled | +| 2026-08-23 | Fixed checkpoint-4B complex-component layout and initial dependent-control state after manual testing | The declarative full-width rule was incorrectly conditional on an `.excalidraw-settings` ancestor that Obsidian's navigated 1.13 sub-pages do not retain, leaving custom renderers in the default horizontal `Setting` layout. The dedicated class is now self-sufficient, restoring full-width ownership for HotkeyEditor, modifier matrices, and every other renderer using the shared helper without affecting legacy rows. `LegacySettingsAdapter` previously called `Setting.setDisabled()` before creating its input; because the method only affects existing components, TODO/Done (and any similar predicate-driven custom control) reopened enabled. Disabled state is now evaluated once and applied after control creation for toggle, text, dropdown, number-dropdown, and slider rows in both the legacy path and declarative custom-render fallback. The maintainer's separate `done` default change remains untouched | Targeted ESLint, `npm run code:unused`, `npm run build`, `npm run lib`, `node --check dist/main.js`, `git diff --check`, and the unchanged `1.8.7` dependency/minimum assertion passed. The build retains the established 33 circular-dependency warnings. Focused manual retest pending: Hotkey overrides layout, one modifier matrix layout and persistence, and TODO/Done initial disabled state after leaving/re-entering in both modes | +| 2026-08-23 | Implemented declarative-settings checkpoint 4B: Display and Links/transclusions | Extended the shared page model to the complete appearance/behavior and links/transclusion/TODO sections without keeping the former standalone legacy renderers. Display now groups Editing and previews, device UI modes, Hotkey overrides, Theme and styling, Zoom and pan, Pen, Grid, Laser pointer, and Link click/drag-and-drop modifier keys. The modifier page contains Link-opening gestures plus third-level pages for browser drag, OS-file drag, internal Obsidian drag, and link-click pane targets; the existing toggle-matrix component can render one category without adding a second fold. Links now groups behavior, pane/tab handling, appearance, TODOs, and text transclusions. Shared custom-row helpers preserve nested grid/laser values and numeric blank/validation semantics; dynamic grid color refreshes declarative visibility without refreshing legacy mode, TODO parsing immediately updates both icon inputs, and hotkey listeners unload when navigating away. All former section text, four YouTube thumbnails, setting keys, grid/laser fields, modifier matrices, and the reading-mode legacy anchor remain represented. Markdown export rebuilds fresh declarations so DocumentFragments consumed by a previously opened page cannot disappear from the copied document | Automated validation passed: targeted ESLint on all changed source/locales, `npm run code:unused`, `npm run build`, `npm run lib`, `node --check dist/main.js`, `git diff --check`, and the unchanged `1.8.7` dependency/minimum assertion. The production build retains the established 33 circular-dependency warnings. Static parity checks found all 47 formerly canonical keys plus the six settings previously rendered by direct controls, all four grid fields, all three laser fields, the modifier configuration, HotkeyEditor, all four video IDs, and every prior locale reference. Manual validation is still required before committing. Prioritize: (1) toggle Dynamic grid color and verify the custom color row appears/disappears and an open drawing updates; (2) toggle Parse TODO and verify both icon inputs enable/disable, then edit an icon and reopen settings; (3) navigate to a third-level modifier page, change one non-default modifier, leave/re-enter, and verify persistence; (4) change a transclusion numeric field using a valid number, invalid text, and blank input; and (5) add/remove a hotkey override, navigate away, and verify it takes effect. Repeat checks 1-5 once in legacy mode after restart; one mobile smoke test should cover the mobile long-press and phone UI-mode controls, while popout coverage is only needed for hotkey capture if Settings is deliberately opened there | | 2026-08-23 | Completed declarative-settings checkpoint 4A: shell, help/promotion, Basic, and Saving | Activated a partial declarative tree on Obsidian 1.13+ while retaining the complete legacy single-page fallback. A persisted, default-enabled layout preference can select the legacy interface after restart. One `SettingsPageModel` hierarchy supplies both renderers with Basic/Saving descriptions and the Updates and startup, Files and folders, Stencil Library, Storage and autosave, and Filename sections; Automation scripts now belongs to Files and folders in both modes. Declarative navigation repeats descriptions inside opened pages as required, while legacy folds show each description once and put a separator before every nested section. Both modes share the compact Copy settings/NotebookLM/help/support toolbar; Mastery remains root-only and legacy alone retains local search. Declarative Markdown export recursively includes unopened pages and writes `- **Title:** (type) Description`. Final review removed the unused ContentSearcher clipboard/custom-element API, a stale settings-links CSS family, an unused NotebookLM label, unnecessary public type exports and wrapper methods, and avoided recreating Markdown normalization helpers per row. Added an idempotent declarative-display preparation guard so rendering a nested utility bar cannot reset pending embed/reload actions. The user-supplied Wiki URL correction is preserved | User validation drove four UI revisions and confirmed the resulting layout before the final low-risk separator/review cleanup. Targeted ESLint passed for every changed TypeScript and maintained-locale file; `npm run code:unused`, `npm run build`, `npm run lib`, `node --check dist/main.js`, `git diff --check`, and the unchanged `1.8.7` dependency/minimum assertion passed. The production build retains the established 33 circular-dependency warnings. Highest remaining risks for follow-up smoke testing are: toggle searchable/legacy layout in each direction and restart; navigate Basic/Saving nested pages and verify descriptions, toolbar, and root-only Mastery; inspect legacy separator/description/fold ordering; export Markdown before opening nested pages; and rapidly edit the filename prefix while checking its sample and persistence. Main-window desktop covers 4A behavior; use one mobile layout smoke test, while popout-specific coverage is only needed if Settings is deliberately opened there | | 2026-08-23 | Removed startup recovery dead ends and preserved deliberate factory reset | Split cold startup into explicit missing/corrupt and recovery/no-recovery cases. Missing `data.json` with no IndexedDB record is now treated as a normal new installation: defaults are persisted without a corruption warning. Missing `data.json` with a recovery record displays a localized modal offering **Restore backup** or **Reset to defaults**; restoring is the data-preserving close/Escape default, while resetting immediately replaces both `data.json` and the stale recovery. Existing-but-corrupt data with no recovery displays a localized modal offering **Reset to defaults** or **Wait for restored file**; waiting is the data-preserving close/Escape default and intentionally leaves the corrupt file untouched until a valid external replacement arrives. Corrupt data with recovery still restores automatically, and invalid runtime synchronization still repairs from active memory. While either startup modal is open, the normal three-second settings wait is extended so layout initialization cannot race ahead using an unresolved choice | Focused executable manager tests passed seven scenarios: silent new install, missing-with-recovery restore, missing-with-recovery factory reset replacing recovery, corrupt-without-recovery reset with subsequent saving enabled, corrupt-without-recovery wait with writes blocked, corrupt-with-recovery automatic restore, and runtime corruption repaired from memory. Targeted ESLint passed for the manager, new modal, recovery store, maintained locales, and release note. Production build passed with the unchanged 33 circular-dependency warnings and produced a 4,743,857-byte `dist/main.js`; `node --check`, `git diff --check`, and the unchanged `1.8.7` dependency/minimum assertion passed. Full `npm run code` remains at the established 138-error backlog with no finding in a new or behavior-changed module. Manual validation should prioritize: (1) rename/delete `data.json` after first establishing recovery, restart, and test both restore and reset choices on separate runs; (2) clear the recovery IndexedDB record, leave a zero-byte `data.json`, restart, and test both reset and wait/external-restore choices; (3) use a clean vault/new installation with neither file nor recovery and confirm there is no warning or question. The modal and IndexedDB path require one mobile smoke test; popouts do not need separate coverage because this is plugin-global startup state | | 2026-08-22 | Corrected invalid settings recovery semantics before checkpoint 4 | Added a durable `SettingsRecoveryStore` backed by a vault-namespaced IndexedDB database with one atomically replaced `lastKnownGood` record; it does not use `localStorage` or a synchronized vault file. The encrypted persisted form (including unknown keys and any legacy in-data stencil library) is refreshed after every valid load, even when no setting is edited, and before every ordinary `data.json` write. A corrupt external/runtime load now leaves active settings untouched, displays a localized repair notice, and immediately serializes the active settings back through recovery and `saveData()`. A corrupt cold-start load automatically applies the last-known-good recovery, repairs `data.json`, and displays a distinct recovery notice. Valid `data.json` remains authoritative and replaces the device-local recovery, preventing stale cross-device recovery prompts. Only the cold-start case where both `data.json` and recovery are unusable retains the protective write block. The database connection is closed on plugin unload; API-key obfuscation, unknown-key retention, checkpoint-4 hold, empty declarative fallback, and Obsidian `1.8.7` compatibility are unchanged | Targeted ESLint passed with zero findings in the new store, manager, maintained locale changes, and release note. A focused executable store test passed for an empty database, a 12 MiB snapshot, an aborted transaction preserving the preceding record, close/reopen persistence, and teardown while the initial database open was pending. Production `npm run build` passed with the unchanged 33 circular-dependency warnings and produced a 4,739,807-byte `dist/main.js`; `node --check`, `git diff --check`, and the `1.8.7` dependency/minimum assertion passed. Full `npm run code` remains at the established 138-error backlog with no finding in a new or behavior-changed module. Before checkpoint 4 resumes, prioritize three manual checks: (1) with a recognizable active setting, empty `data.json` while Obsidian is running and confirm the repair notice, immediate non-empty rewrite, unchanged UI value, and persistence after restart; (2) make a valid manual `data.json` change while Obsidian is closed, start and close without editing settings, then empty the file and restart, confirming the recovery notice and restoration of that manual value; (3) after a recovery exists, synchronize/load a different valid file and then corrupt it, confirming the newer valid value—not the older recovery—is restored. The IndexedDB path is plugin-global, so popout coverage is not separate; repeat check 1 once on mobile, and use a legacy multi-megabyte stencil-in-settings profile for the highest storage-pressure validation | @@ -1159,7 +1163,7 @@ removal as part of this refactor. | 2. Add Obsidian 1.13 compatibility types | Complete | Added the minimal documented 1.13.0 structural type shim and capability-checked runtime-method facade without changing dependencies, manifests, declarative activation, or runtime behavior | | 3. Establish canonical specifications and dual adapters | Complete | Extracted the local definition model and legacy interpreter, added declarative conversion plus typed get/set binding and persistence routing, and kept `getSettingDefinitions()` explicitly empty until full coverage is ready | | 4A. Convert shell, help/promotion, General, and Saving | Complete | Added the staged declarative shell, separately indexed General/Saving controls, custom library storage/migration rows, filename preview, full top help/promotion/link surface, and shared canonical specs. Four manual revisions corrected custom-row layout, mount ownership, filename initialization, duplicate keys, flat groups, recursive Markdown export, descriptions, toolbar placement, the remaining structural fork through one shared page model, duplicate legacy descriptions, and legacy separator placement. The hard-coded activation constant was replaced by `useDeclarativeSettings`, a default-enabled persisted top-level toggle shown only on Obsidian 1.13+. The setting tab snapshots that choice when it is constructed, so changing it persists immediately but intentionally takes effect only after restarting Obsidian. Older versions remain on legacy without showing the toggle. Both modes retain the same hierarchy and compact toolbar; legacy nested and sub-nested sections render a separator immediately before their description and fold. Declarative Markdown bullets use `- **Title:** (type) Description`. Final duplication/dead-code review and automated validation passed; checkpoint 4A is ready for its commit | -| 4B. Convert Display and Links/transclusions | Pending | Migrate display modes, theme/zoom, grid/laser, modifiers, link behavior, TODO dependencies, and validated transclusion inputs | +| 4B. Convert Display and Links/transclusions | Complete | Migrated display modes, theme/zoom, grid/laser, three-level modifier navigation, link behavior, TODO dependencies, and validated transclusion inputs through the shared declarative/legacy page model. Manual validation drove shared fixes for full-width components, initial dependent-control state, and live viewport preservation during settings reloads. Final duplication/dead-code review and automated validation passed; committed as one independently testable batch | | 4C. Convert Embed/export, Embedding, and nonstandard features | Pending | Migrate image cache actions, embed/autoexport dependency cluster, PDF/export custom UI, Markdown embeds, and custom pens | | 4D. Convert Fonts, Experimental, Excalidraw Automate, and Compatibility | Pending | Migrate font-picker cleanup, Taskbone dependency behavior, startup/autostart scripts, filename-preview cross-link, and dynamic script settings | | 4E. Convert AI | Pending | Extract and migrate the large runtime-generated provider/model/token-limit component independently because it has the highest complexity and credential risk | diff --git a/src/core/settings.ts b/src/core/settings.ts index e1ae3205..926a4cdd 100644 --- a/src/core/settings.ts +++ b/src/core/settings.ts @@ -10,6 +10,7 @@ import { TextComponent, } from "obsidian"; import { + DEVICE, LOGO_EXCALIDRAW_MASTERY, setRootElementSize, } from "src/constants/constants"; @@ -22,17 +23,27 @@ import { getDrawingFilename, getEmbedFilename, } from "src/utils/fileUtils"; -import { addYouTubeThumbnail, fragWithHTML } from "src/utils/utils"; import { - setElementHidden, - setSanitizedHtml, -} from "src/utils/htmlUtils"; + addYouTubeThumbnail, + fragWithHTML, + setLeftHandedMode, + setUIMode, +} from "src/utils/utils"; +import { setElementHidden, setSanitizedHtml } from "src/utils/htmlUtils"; import { getImageCache } from "src/shared/ImageCache"; import { MultiOptionConfirmationPrompt } from "src/shared/Dialogs/Prompt"; import { EmbeddalbeMDFileCustomDataSettingsComponent } from "src/shared/Dialogs/EmbeddableMDFileCustomDataSettingsComponent"; import { AutostartScriptsSettingsComponent } from "src/shared/Dialogs/AutostartScriptsSettingsComponent"; import { startupScript } from "src/constants/starutpscript"; -import { ModifierKeySettingsComponent } from "src/shared/Dialogs/ModifierKeySettings"; +import { + getModifierKeyCategoryName, + MODIFIER_KEY_CATEGORIES, + ModifierKeySettingsComponent, +} from "src/shared/Dialogs/ModifierKeySettings"; +import { + modifierKeyTooltipMessages, + type ModifierSetType, +} from "src/utils/modifierkeyHelper"; import { EDITOR_FADEOUT } from "src/core/editor/EditorHandler"; import { TAG_AUTOEXPORT, @@ -41,10 +52,9 @@ import { } from "src/constants/constSettingsTags"; import { HotkeyEditor } from "src/shared/Dialogs/HotkeyEditor"; import { getExcalidrawViews } from "src/utils/obsidianUtils"; -import { createSliderWithText } from "src/utils/sliderUtils"; +import { configureSliderWithText } from "src/utils/sliderUtils"; import { PDFExportSettingsComponent } from "src/shared/Dialogs/PDFExportSettingsComponent"; import { ContentSearcher } from "src/shared/components/ContentSearcher"; -import { UIModeSettingsComponent } from "src/shared/Dialogs/UIModeSettingComponent"; import { ScriptSettingValue } from "src/types/excalidrawAutomateTypes"; import { AIImageModelConfig, @@ -127,12 +137,16 @@ export class ExcalidrawSettingTab extends PluginSettingTab { private readonly useDeclarativeSettingsForSession: boolean; private declarativeDefinitionsActive = false; private declarativeDisplayPrepared = false; - private declarativeDefinitions: SettingDefinitionItem[] = []; + private declarativeDefinitions: SettingDefinitionItem[] = + []; private persistenceOwnerWindow: Window | null = null; private readonly flushOnSettingsWindowBlur = (): void => { void this.settingsPersistenceQueue.flush().catch((): void => undefined); }; - private hotkeyEditor: HotkeyEditor; + private hotkeyEditor: HotkeyEditor | null = null; + private todoPrefixSetting: TextComponent | null = null; + private donePrefixSetting: TextComponent | null = null; + private gridColorSettingEl: HTMLElement | null = null; private fontPickers: FontPickerComponent[] = []; /** * Filename-sample preview element from the Saving section, refreshed by @@ -247,6 +261,13 @@ export class ExcalidrawSettingTab extends PluginSettingTab { this.display(); } + private refreshDeclarativeDomState(): void { + if (!this.declarativeDefinitionsActive) { + return; + } + getDeclarativeSettingTabRuntime(this)?.refreshDomState(); + } + private prepareDeclarativeDisplay(): void { if (this.declarativeDisplayPrepared) { return; @@ -286,6 +307,55 @@ export class ExcalidrawSettingTab extends PluginSettingTab { setting.settingEl.addClass("excalidraw-declarative-full-width"); } + private createRenderedDefinition(options: { + name: string; + desc?: string | DocumentFragment; + aliases?: string[]; + searchable?: boolean | (() => boolean); + visible?: boolean | (() => boolean); + controlType?: string; + omitFromMarkdown?: boolean; + render: (container: HTMLElement) => void | (() => void); + }): SettingDefinition { + return annotateMarkdownDefinition( + { + name: options.name, + desc: options.desc, + aliases: options.aliases, + searchable: options.searchable, + visible: options.visible, + render: (setting) => { + this.prepareFullWidthDeclarativeSetting(setting); + return options.render(setting.settingEl); + }, + }, + { + controlType: options.controlType, + omit: options.omitFromMarkdown, + }, + ); + } + + private createCustomSettingDefinition(options: { + name: string; + desc?: string | DocumentFragment; + aliases?: string[]; + visible?: boolean | (() => boolean); + controlType: string; + configure: (setting: Setting) => void; + }): SettingDefinition { + return annotateMarkdownDefinition( + { + name: options.name, + desc: options.desc, + aliases: options.aliases, + visible: options.visible, + render: (setting) => options.configure(setting), + }, + { controlType: options.controlType }, + ); + } + private createSectionDescriptionDefinition( name: string, description: string, @@ -388,18 +458,17 @@ export class ExcalidrawSettingTab extends PluginSettingTab { ); } - private createTemplateVideoDefinition(): SettingDefinition { - return annotateMarkdownDefinition( - { - name: `${t("TEMPLATE_NAME")} · YouTube`, - searchable: false, - render: (setting) => { - this.prepareFullWidthDeclarativeSetting(setting); - addYouTubeThumbnail(setting.settingEl, "jgUpYznHP9A", 216); - }, - }, - { omit: true }, - ); + private createYouTubeDefinition( + scope: string, + videoId: string, + startAt?: number, + ): SettingDefinition { + return this.createRenderedDefinition({ + name: `${scope} · YouTube`, + searchable: false, + omitFromMarkdown: true, + render: (container) => addYouTubeThumbnail(container, videoId, startAt), + }); } private getCheckpoint4APages(): SettingsPageModel[] { @@ -424,7 +493,11 @@ export class ExcalidrawSettingTab extends PluginSettingTab { ), ...this.toDeclarativeDefinitions(this.getGeneralTrailingSpecs()), ...this.toDeclarativeDefinitions(this.getGeneralScriptSpecs()), - this.createTemplateVideoDefinition(), + this.createYouTubeDefinition( + t("TEMPLATE_NAME"), + "jgUpYznHP9A", + 216, + ), ], renderLegacy: (container) => { this.renderSettingSpecs( @@ -485,12 +558,193 @@ export class ExcalidrawSettingTab extends PluginSettingTab { return [basicPage, savingPage]; } + private getCheckpoint4BPages(): SettingsPageModel[] { + const modifierKeyPage: SettingsPageModel = { + name: t("DRAG_MODIFIER_NAME"), + description: t("DRAG_MODIFIER_GROUP_DESC"), + buildDefinitions: () => [this.createModifierKeyUsageDefinition()], + renderLegacy: (container) => this.renderModifierKeyUsage(container), + children: [ + { + name: t("LINK_OPENING_GESTURES_HEAD"), + description: t("LINK_OPENING_GESTURES_DESC"), + buildDefinitions: () => + this.toDeclarativeDefinitions(this.getLinkOpeningGestureSpecs()), + renderLegacy: (container) => + this.renderSettingSpecs( + container, + this.getLinkOpeningGestureSpecs(), + ), + }, + ...MODIFIER_KEY_CATEGORIES.map( + (modifierSetType): SettingsPageModel => ({ + name: getModifierKeyCategoryName(modifierSetType), + description: + this.getModifierKeyCategoryDescription(modifierSetType), + buildDefinitions: () => [ + this.createModifierKeyCategoryDefinition(modifierSetType), + ], + renderLegacy: (container) => + this.renderModifierKeyCategory(container, modifierSetType), + }), + ), + ], + }; + + const displayPage: SettingsPageModel = { + name: t("DISPLAY_HEAD"), + description: t("DISPLAY_DESC"), + children: [ + { + name: t("DISPLAY_EDITOR_PREVIEWS_HEAD"), + description: t("DISPLAY_EDITOR_PREVIEWS_DESC"), + buildDefinitions: () => + this.toDeclarativeDefinitions(this.getDisplayEditorPreviewSpecs()), + renderLegacy: (container) => + this.renderDisplayEditorPreviewSettings(container), + }, + { + name: t("MODES_HEAD"), + description: t("MODES_DESC"), + buildDefinitions: () => [ + ...this.toDeclarativeDefinitions(this.getUIModeSpecs()), + this.createYouTubeDefinition(t("MODES_HEAD"), "H8Njp7ZXYag", 999), + ], + renderLegacy: (container) => { + this.renderSettingSpecs(container, this.getUIModeSpecs()); + addYouTubeThumbnail(container, "H8Njp7ZXYag", 999); + }, + }, + { + name: t("HOTKEY_OVERRIDE_HEAD"), + description: t("HOTKEY_OVERRIDE_GROUP_DESC"), + buildDefinitions: () => [this.createHotkeyEditorDefinition()], + renderLegacy: (container) => this.renderHotkeyEditor(container), + }, + { + name: t("THEME_HEAD"), + description: t("THEME_DESC"), + buildDefinitions: () => { + const specs = this.getThemeSpecs(); + return [ + ...this.toDeclarativeDefinitions(specs.slice(0, 2)), + this.createYouTubeDefinition( + t("DYNAMICSTYLE_NAME"), + "fypDth_-8q0", + ), + ...this.toDeclarativeDefinitions(specs.slice(2, 3)), + this.createYouTubeDefinition( + t("IFRAME_MATCH_THEME_NAME"), + "ICpoyMv6KSs", + ), + ...this.toDeclarativeDefinitions(specs.slice(3)), + ]; + }, + renderLegacy: (container) => this.renderThemeSettings(container), + }, + { + name: t("ZOOM_AND_PAN_HEAD"), + description: t("ZOOM_AND_PAN_DESC"), + buildDefinitions: () => { + const specs = this.getZoomAndPanSpecs(); + return [ + ...this.toDeclarativeDefinitions(specs.slice(0, 2)), + this.createYouTubeDefinition( + t("DEFAULT_PINCHZOOM_NAME"), + "rBarRfcSxNo", + 107, + ), + ...this.toDeclarativeDefinitions(specs.slice(2)), + ]; + }, + renderLegacy: (container) => this.renderZoomAndPanSettings(container), + }, + { + name: t("PEN_HEAD"), + description: t("PEN_DESC"), + buildDefinitions: () => + this.toDeclarativeDefinitions(this.getPenSpecs()), + renderLegacy: (container) => + this.renderSettingSpecs(container, this.getPenSpecs()), + }, + { + name: t("GRID_HEAD"), + description: t("GRID_DESC"), + buildDefinitions: () => this.getGridDefinitions(), + renderLegacy: (container) => this.renderGridSettings(container), + }, + { + name: t("LASER_HEAD"), + description: t("LASER_DESC"), + buildDefinitions: () => this.getLaserDefinitions(), + renderLegacy: (container) => this.renderLaserSettings(container), + }, + modifierKeyPage, + ], + }; + + const linksPage: SettingsPageModel = { + name: t("LINKS_HEAD"), + description: t("LINKS_HEAD_DESC"), + children: [ + { + name: t("LINK_BEHAVIOR_HEAD"), + description: t("LINK_BEHAVIOR_DESC"), + buildDefinitions: () => [ + this.createLinkUsageDefinition(), + ...this.toDeclarativeDefinitions(this.getLinkBehaviorSpecs()), + ], + renderLegacy: (container) => + this.renderLinkBehaviorSettings(container), + }, + { + name: t("LINK_OPENING_HEAD"), + description: t("LINK_OPENING_DESC"), + buildDefinitions: () => + this.toDeclarativeDefinitions(this.getLinkOpeningSpecs()), + renderLegacy: (container) => + this.renderSettingSpecs(container, this.getLinkOpeningSpecs()), + }, + { + name: t("LINK_APPEARANCE_HEAD"), + description: t("LINK_APPEARANCE_DESC"), + buildDefinitions: () => + this.toDeclarativeDefinitions(this.getLinkAppearanceSpecs()), + renderLegacy: (container) => + this.renderSettingSpecs(container, this.getLinkAppearanceSpecs()), + }, + { + name: t("TODO_HEAD"), + description: t("TODO_GROUP_DESC"), + buildDefinitions: () => + this.toDeclarativeDefinitions(this.getTodoSpecs()), + renderLegacy: (container) => + this.renderSettingSpecs(container, this.getTodoSpecs()), + }, + { + name: t("TRANSCLUSION_HEAD"), + description: t("TRANSCLUSION_DESC"), + buildDefinitions: () => this.getTransclusionDefinitions(), + renderLegacy: (container) => + this.renderTransclusionSettings(container), + }, + ], + }; + + return [displayPage, linksPage]; + } + + private getConvertedSettingsPages(): SettingsPageModel[] { + return [...this.getCheckpoint4APages(), ...this.getCheckpoint4BPages()]; + } + private toDeclarativePage( page: SettingsPageModel, ): SettingDefinitionItem { - const items = page.children - ? page.children.map((child) => this.toDeclarativePage(child)) - : (page.buildDefinitions?.() ?? []); + const items = [ + ...(page.buildDefinitions?.() ?? []), + ...(page.children?.map((child) => this.toDeclarativePage(child)) ?? []), + ]; return { type: "page", name: page.name, @@ -521,21 +775,22 @@ export class ExcalidrawSettingTab extends PluginSettingTab { cls: `excalidraw-setting-h${headingLevel}`, }); + page.renderLegacy?.(details); + const childHeadingLevel = headingLevel === 1 ? 3 : 4; page.children?.forEach((child) => this.renderLegacyPage(details, child, childHeadingLevel), ); - page.renderLegacy?.(details); } - private buildCheckpoint4ADefinitions(): SettingDefinitionItem[] { + private buildConvertedDefinitions(): SettingDefinitionItem[] { this.declarativeSettingsAdapter.beginBuild(); return [ this.createDeclarativeUtilitiesDefinition("Root", true), this.declarativeSettingsAdapter.toDefinition( this.getSettingsLayoutSpec(), ), - ...this.getCheckpoint4APages().map((page) => + ...this.getConvertedSettingsPages().map((page) => this.toDeclarativePage(page), ), ]; @@ -554,7 +809,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab { this.declarativeDefinitionsActive = false; return []; } - const definitions = this.buildCheckpoint4ADefinitions(); + const definitions = this.buildConvertedDefinitions(); this.declarativeDefinitions = definitions; this.declarativeDefinitionsActive = definitions.length > 0; return this.declarativeDefinitionsActive ? definitions : []; @@ -679,8 +934,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab { const excalidrawViews = getExcalidrawViews(this.app, true); for (const excalidrawView of excalidrawViews) { await excalidrawView.save(false); - //debug({where:"ExcalidrawSettings.hide",file:v.view.file.name,before:"reload(true)"}) - await excalidrawView.reload(true); + await excalidrawView.reloadAfterSettingsChange(); } this.requestEmbedUpdate = true; } @@ -722,10 +976,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab { setRootElementSize(); } - this.hotkeyEditor?.unload(); - if (this.hotkeyEditor?.isDirty) { - this.plugin.registerHotkeyOverrides(); - } + this.destroyHotkeyEditor(); this.plugin.scriptEngine.updateScriptPath(); /* if(this.reloadMathJax) { this.plugin.loadMathJax(); @@ -738,6 +989,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab { this.requestReloadDrawings = false; this.declarativeDisplayPrepared = false; this.destroyFontPickers(); + this.destroyHotkeyEditor(); const { containerEl } = this; containerEl.addClass("excalidraw-settings"); this.containerEl.empty(); @@ -751,10 +1003,9 @@ export class ExcalidrawSettingTab extends PluginSettingTab { if (requireApiVersion("1.13.0")) { this.buildSetting(containerEl, this.getSettingsLayoutSpec()); } - this.renderCheckpoint4ALegacyPages(); + this.renderLegacyPages(this.getCheckpoint4APages()); this.renderAISection(); - this.renderDisplaySection(); - this.renderLinksAndTransclusionsSection(); + this.renderLegacyPages(this.getCheckpoint4BPages()); this.renderEmbedAndExportSection(); this.renderEmbeddingSettingsSection(); this.renderNonExcalidrawFeaturesSection(); @@ -765,9 +1016,11 @@ export class ExcalidrawSettingTab extends PluginSettingTab { } private async copyDeclarativeSettingsAsMarkdown(): Promise { - const markdown = declarativeSettingsToMarkdown( - this.declarativeDefinitions, - ); + // Build fresh fragments because Obsidian may consume a DocumentFragment + // while rendering a page. Rebuilding also exports unopened pages. + const definitions = this.buildConvertedDefinitions(); + this.declarativeDefinitions = definitions; + const markdown = declarativeSettingsToMarkdown(definitions); const ownerWindow = this.containerEl.ownerDocument.defaultView; if (!ownerWindow) { return; @@ -1142,8 +1395,8 @@ export class ExcalidrawSettingTab extends PluginSettingTab { ); } - private renderCheckpoint4ALegacyPages(): void { - for (const page of this.getCheckpoint4APages()) { + private renderLegacyPages(pages: readonly SettingsPageModel[]): void { + for (const page of pages) { this.containerEl.createEl("hr", { cls: "excalidraw-setting-hr" }); this.renderLegacyPage(this.containerEl, page, 1); } @@ -1904,66 +2157,64 @@ export class ExcalidrawSettingTab extends PluginSettingTab { this.plugin.settings.aiDefaultMaxResponseTokens = value; }, ); - } - private renderDisplaySection(): void { - const { containerEl } = this; - let detailsEl: HTMLElement; - // ------------------------------------------------ - // Display - // ------------------------------------------------ - containerEl.createEl("hr", { cls: "excalidraw-setting-hr" }); - containerEl.createDiv({ - text: t("DISPLAY_DESC"), - cls: "setting-item-description", - }); - detailsEl = this.containerEl.createEl("details"); - const displayDetailsEl = detailsEl; - detailsEl.createEl("summary", { - text: t("DISPLAY_HEAD"), - cls: "excalidraw-setting-h1", - }); - - this.buildSetting(detailsEl, { - name: t("ENABLE_DOUBLE_CLICK_TEXT_EDITING_NAME"), - control: { - type: "toggle", - key: "disableDoubleClickTextEditing", - negate: true, + private getDisplayEditorPreviewSpecs(): SettingSpec[] { + return [ + { + name: t("ENABLE_DOUBLE_CLICK_TEXT_EDITING_NAME"), + aliases: ["double click text", "create text"], + control: { + type: "toggle", + key: "disableDoubleClickTextEditing", + negate: true, + }, }, - }); + { + name: t("DISABLE_CONTEXT_MENU_NAME"), + desc: t("DISABLE_CONTEXT_MENU_DESC"), + aliases: ["context menu", "right click menu"], + control: { type: "toggle", key: "disableContextMenu", negate: true }, + }, + { + name: t("SHOW_DRAWING_OR_MD_IN_READING_MODE_NAME"), + desc: fragWithHTML(t("SHOW_DRAWING_OR_MD_IN_READING_MODE_DESC")), + aliases: ["reading mode", "markdown reading mode", "render image"], + control: { type: "toggle", key: "renderImageInMarkdownReadingMode" }, + }, + { + name: t("SHOW_DRAWING_OR_MD_IN_HOVER_PREVIEW_NAME"), + desc: fragWithHTML(t("SHOW_DRAWING_OR_MD_IN_HOVER_PREVIEW_DESC")), + aliases: ["hover preview", "page preview", "render image"], + control: { + type: "toggle", + key: "renderImageInHoverPreviewForMDNotes", + }, + }, + ]; + } - this.buildSetting(detailsEl, { - name: t("DISABLE_CONTEXT_MENU_NAME"), - desc: t("DISABLE_CONTEXT_MENU_DESC"), - control: { type: "toggle", key: "disableContextMenu", negate: true }, + private renderDisplayEditorPreviewSettings(container: HTMLElement): void { + const specs = this.getDisplayEditorPreviewSpecs(); + specs.forEach((spec) => { + const setting = this.buildSetting(container, spec); + if ( + spec.control.key === "renderImageInMarkdownReadingMode" && + setting !== undefined + ) { + setting.nameEl.setAttribute("id", TAG_MDREADINGMODE); + } }); + } - const readingModeEl = this.buildSetting(detailsEl, { - name: t("SHOW_DRAWING_OR_MD_IN_READING_MODE_NAME"), - desc: fragWithHTML(t("SHOW_DRAWING_OR_MD_IN_READING_MODE_DESC")), - control: { type: "toggle", key: "renderImageInMarkdownReadingMode" }, - }); - readingModeEl.nameEl.setAttribute("id", TAG_MDREADINGMODE); - - this.buildSetting(detailsEl, { - name: t("SHOW_DRAWING_OR_MD_IN_HOVER_PREVIEW_NAME"), - desc: fragWithHTML(t("SHOW_DRAWING_OR_MD_IN_HOVER_PREVIEW_DESC")), - control: { type: "toggle", key: "renderImageInHoverPreviewForMDNotes" }, - }); - - detailsEl = displayDetailsEl.createEl("details"); - detailsEl.createEl("summary", { - text: t("MODES_HEAD"), - cls: "excalidraw-setting-h3", - }); - - this.buildSetting(detailsEl, { - name: t("SHOW_TAB_TITLEBAR_BUTTONS"), - control: { - type: "toggle", - key: "showTabTitlebarButtons", + private getUIModeSpecs(): SettingSpec[] { + return [ + { + name: t("SHOW_TAB_TITLEBAR_BUTTONS"), + aliases: ["tab buttons", "titlebar buttons"], + control: { + type: "toggle", + key: "showTabTitlebarButtons", afterUpdate: (value) => { getExcalidrawViews(this.app, true).forEach((excalidrawView) => { if (value) { @@ -1971,103 +2222,157 @@ export class ExcalidrawSettingTab extends PluginSettingTab { } else { excalidrawView.removeTabTitlebarButtons(); } - }); + }); + }, }, }, - }); + { + name: t("DESKTOP_UI_MODE_NAME"), + desc: t("DESKTOP_UI_MODE_DESC"), + aliases: ["desktop mode", "full mode", "compact mode", "tray mode"], + control: { + type: "dropdown", + key: "desktopUIMode", + options: [ + { value: "full", label: t("MODE_FULL") }, + { value: "compact", label: t("MODE_COMPACT") }, + { value: "tray", label: t("MODE_TRAY") }, + ], + after: () => { + if (DEVICE.isDesktop) { + setUIMode(this.app, this.plugin.settings); + } + }, + }, + }, + { + name: t("TABLET_UI_MODE_NAME"), + desc: t("TABLET_UI_MODE_DESC"), + aliases: ["tablet mode", "full mode", "compact mode", "tray mode"], + control: { + type: "dropdown", + key: "tabletUIMode", + options: [ + { value: "full", label: t("MODE_FULL") }, + { value: "compact", label: t("MODE_COMPACT") }, + { value: "tray", label: t("MODE_TRAY") }, + ], + after: () => { + if (DEVICE.isTablet) { + setUIMode(this.app, this.plugin.settings); + } + }, + }, + }, + { + name: t("PHONE_UI_MODE_NAME"), + desc: t("PHONE_UI_MODE_DESC"), + aliases: [ + "phone mode", + "mobile mode", + "full mode", + "compact mode", + "tray mode", + ], + control: { + type: "dropdown", + key: "phoneUIMode", + options: [ + { value: "full", label: t("MODE_FULL") }, + { value: "compact", label: t("MODE_COMPACT") }, + { value: "tray", label: t("MODE_TRAY") }, + { value: "mobile", label: t("MODE_PHONE") }, + ], + after: () => { + if (DEVICE.isPhone) { + setUIMode(this.app, this.plugin.settings); + } + }, + }, + }, + { + name: t("LEFTHANDED_MODE_NAME"), + desc: fragWithHTML(t("LEFTHANDED_MODE_DESC")), + aliases: ["left handed", "tray side"], + control: { + type: "toggle", + key: "isLeftHanded", + after: (value) => setLeftHandedMode(value), + }, + }, + ]; + } - new UIModeSettingsComponent(detailsEl, this.plugin.settings, this.app, () => - this.applySettingsUpdate(), - ).render(); - addYouTubeThumbnail(detailsEl, "H8Njp7ZXYag", 999); - - detailsEl = displayDetailsEl.createEl("details"); - detailsEl.createEl("summary", { - text: t("HOTKEY_OVERRIDE_HEAD"), - cls: "excalidraw-setting-h3", - }); - detailsEl.createSpan({}, (el) => { - setSanitizedHtml(el, t("HOTKEY_OVERRIDE_DESC")); - }); - - this.hotkeyEditor = new HotkeyEditor( - detailsEl, - this.plugin.settings, - (x: boolean = false) => this.applySettingsUpdate(x), - ); - this.hotkeyEditor.onload(); - - detailsEl = displayDetailsEl.createEl("details"); - detailsEl.createEl("summary", { - text: t("THEME_HEAD"), - cls: "excalidraw-setting-h3", - }); - - this.buildSetting(detailsEl, { - name: t("OVERRIDE_OBSIDIAN_FONT_SIZE_NAME"), - desc: fragWithHTML(t("OVERRIDE_OBSIDIAN_FONT_SIZE_DESC")), - control: { type: "toggle", key: "overrideObsidianFontSize" }, - }); - - this.buildSetting(detailsEl, { - name: t("DYNAMICSTYLE_NAME"), - desc: fragWithHTML(t("DYNAMICSTYLE_DESC")), - control: { - type: "dropdown", - key: "dynamicStyling", + private getThemeSpecs(): SettingSpec[] { + return [ + { + name: t("OVERRIDE_OBSIDIAN_FONT_SIZE_NAME"), + desc: fragWithHTML(t("OVERRIDE_OBSIDIAN_FONT_SIZE_DESC")), + aliases: ["font size", "editor text size", "Obsidian font size"], + control: { type: "toggle", key: "overrideObsidianFontSize" }, + }, + { + name: t("DYNAMICSTYLE_NAME"), + desc: fragWithHTML(t("DYNAMICSTYLE_DESC")), + aliases: ["dynamic styling", "canvas color", "interface color"], + control: { + type: "dropdown", + key: "dynamicStyling", before: () => { this.requestUpdateDynamicStyling = true; }, options: [ { value: "none", label: t("DYNAMICSTYLE_OPTION_NONE") }, { value: "colorful", label: t("DYNAMICSTYLE_OPTION_COLORFUL") }, - { value: "gray", label: t("DYNAMICSTYLE_OPTION_GRAY") }, - ], + { value: "gray", label: t("DYNAMICSTYLE_OPTION_GRAY") }, + ], + }, }, - }); - addYouTubeThumbnail(detailsEl, "fypDth_-8q0"); - - this.buildSetting(detailsEl, { - name: t("IFRAME_MATCH_THEME_NAME"), - desc: fragWithHTML(t("IFRAME_MATCH_THEME_DESC")), - control: { type: "toggle", key: "iframeMatchExcalidrawTheme", reload: true }, - }); - addYouTubeThumbnail(detailsEl, "ICpoyMv6KSs"); - - this.buildSetting(detailsEl, { - name: t("MATCH_THEME_NAME"), - desc: fragWithHTML(t("MATCH_THEME_DESC")), - control: { type: "toggle", key: "matchTheme" }, - }); - - this.buildSetting(detailsEl, { - name: t("MATCH_THEME_ALWAYS_NAME"), - desc: fragWithHTML(t("MATCH_THEME_ALWAYS_DESC")), - control: { type: "toggle", key: "matchThemeAlways" }, - }); - - this.buildSetting(detailsEl, { - name: t("MATCH_THEME_TRIGGER_NAME"), - desc: fragWithHTML(t("MATCH_THEME_TRIGGER_DESC")), - control: { - type: "toggle", - key: "matchThemeTrigger", + { + name: t("IFRAME_MATCH_THEME_NAME"), + desc: fragWithHTML(t("IFRAME_MATCH_THEME_DESC")), + aliases: ["markdown embed theme", "iframe theme"], + control: { + type: "toggle", + key: "iframeMatchExcalidrawTheme", + reload: true, + }, + }, + { + name: t("MATCH_THEME_NAME"), + desc: fragWithHTML(t("MATCH_THEME_DESC")), + aliases: ["new drawing theme", "Obsidian theme"], + control: { type: "toggle", key: "matchTheme" }, + }, + { + name: t("MATCH_THEME_ALWAYS_NAME"), + desc: fragWithHTML(t("MATCH_THEME_ALWAYS_DESC")), + aliases: ["existing drawing theme", "Obsidian theme"], + control: { type: "toggle", key: "matchThemeAlways" }, + }, + { + name: t("MATCH_THEME_TRIGGER_NAME"), + desc: fragWithHTML(t("MATCH_THEME_TRIGGER_DESC")), + aliases: ["theme change", "follow theme"], + control: { + type: "toggle", + key: "matchThemeTrigger", after: (value) => { if (value) { this.plugin.addThemeObserver(); } else { this.plugin.removeThemeObserver(); - } + } + }, }, }, - }); - - this.buildSetting(detailsEl, { - name: t("DEFAULT_OPEN_MODE_NAME"), - desc: fragWithHTML(t("DEFAULT_OPEN_MODE_DESC")), - control: { - type: "dropdown", - key: "defaultMode", + { + name: t("DEFAULT_OPEN_MODE_NAME"), + desc: fragWithHTML(t("DEFAULT_OPEN_MODE_DESC")), + aliases: ["default open mode", "normal", "zen", "view mode"], + control: { + type: "dropdown", + key: "defaultMode", options: [ { value: "normal", label: t("DEFAULT_OPEN_MODE_OPTION_NORMAL") }, { value: "zen", label: t("DEFAULT_OPEN_MODE_OPTION_ZEN") }, @@ -2075,197 +2380,246 @@ export class ExcalidrawSettingTab extends PluginSettingTab { { value: "view-mobile", label: t("DEFAULT_OPEN_MODE_OPTION_VIEW_MOBILE"), - }, - ], + }, + ], + }, }, - }); - - this.buildSetting(detailsEl, { - name: t("PHONE_FOOTER_SAFE_AREA_PADDING_NAME"), - desc: fragWithHTML(t("PHONE_FOOTER_SAFE_AREA_PADDING_DESC")), - control: { - type: "toggle", - key: "phoneFooterSafeAreaPadding", - after: () => this.plugin.updateFooterSafeAreaPadding(), + { + name: t("PHONE_FOOTER_SAFE_AREA_PADDING_NAME"), + desc: fragWithHTML(t("PHONE_FOOTER_SAFE_AREA_PADDING_DESC")), + aliases: ["phone footer", "safe area", "bottom padding"], + control: { + type: "toggle", + key: "phoneFooterSafeAreaPadding", + after: () => this.plugin.updateFooterSafeAreaPadding(), + }, }, - }); - - this.buildSetting(detailsEl, { - name: t("TABLET_FOOTER_SAFE_AREA_PADDING_NAME"), - desc: fragWithHTML(t("TABLET_FOOTER_SAFE_AREA_PADDING_DESC")), - control: { - type: "toggle", - key: "tabletFooterSafeAreaPadding", - after: () => this.plugin.updateFooterSafeAreaPadding(), + { + name: t("TABLET_FOOTER_SAFE_AREA_PADDING_NAME"), + desc: fragWithHTML(t("TABLET_FOOTER_SAFE_AREA_PADDING_DESC")), + aliases: ["tablet footer", "safe area", "bottom padding"], + control: { + type: "toggle", + key: "tabletFooterSafeAreaPadding", + after: () => this.plugin.updateFooterSafeAreaPadding(), + }, }, - }); + ]; + } - detailsEl = displayDetailsEl.createEl("details"); - detailsEl.createEl("summary", { - text: t("ZOOM_AND_PAN_HEAD"), //mfuria #329 - cls: "excalidraw-setting-h3", - }); + private renderThemeSettings(container: HTMLElement): void { + const specs = this.getThemeSpecs(); + this.renderSettingSpecs(container, specs.slice(0, 2)); + addYouTubeThumbnail(container, "fypDth_-8q0"); + this.renderSettingSpecs(container, specs.slice(2, 3)); + addYouTubeThumbnail(container, "ICpoyMv6KSs"); + this.renderSettingSpecs(container, specs.slice(3)); + } - //mfuria #329. Added setting for right-click panning - this.buildSetting(detailsEl, { - name: t("PAN_WITH_RIGHT_MOUSE_BUTTON_NAME"), - desc: fragWithHTML(t("PAN_WITH_RIGHT_MOUSE_BUTTON_DESC")), - control: { type: "toggle", key: "panWithRightMouseButton", reload: true }, - }); - - this.buildSetting(detailsEl, { - name: t("DEFAULT_PINCHZOOM_NAME"), - desc: fragWithHTML(t("DEFAULT_PINCHZOOM_DESC")), - control: { - type: "toggle", - key: "allowPinchZoom", + private getZoomAndPanSpecs(): SettingSpec[] { + return [ + { + name: t("PAN_WITH_RIGHT_MOUSE_BUTTON_NAME"), + desc: fragWithHTML(t("PAN_WITH_RIGHT_MOUSE_BUTTON_DESC")), + aliases: ["right click pan", "mouse pan"], + control: { + type: "toggle", + key: "panWithRightMouseButton", + reload: true, + }, + }, + { + name: t("DEFAULT_PINCHZOOM_NAME"), + desc: fragWithHTML(t("DEFAULT_PINCHZOOM_DESC")), + aliases: ["pinch zoom", "pen mode zoom", "touch zoom"], + control: { + type: "toggle", + key: "allowPinchZoom", after: () => getExcalidrawViews(this.app, true).forEach((excalidrawView) => - excalidrawView.updatePinchZoom(), - ), + excalidrawView.updatePinchZoom(), + ), + }, }, - }); - addYouTubeThumbnail(detailsEl, "rBarRfcSxNo", 107); - - this.buildSetting(detailsEl, { - name: t("DEFAULT_WHEELZOOM_NAME"), - desc: fragWithHTML(t("DEFAULT_WHEELZOOM_DESC")), - control: { - type: "toggle", - key: "allowWheelZoom", + { + name: t("DEFAULT_WHEELZOOM_NAME"), + desc: fragWithHTML(t("DEFAULT_WHEELZOOM_DESC")), + aliases: ["wheel zoom", "mouse wheel", "scroll zoom"], + control: { + type: "toggle", + key: "allowWheelZoom", after: () => getExcalidrawViews(this.app, true).forEach((excalidrawView) => - excalidrawView.updateWheelZoom(), - ), + excalidrawView.updateWheelZoom(), + ), + }, }, - }); - - this.buildSetting(detailsEl, { - name: t("ZOOM_TO_FIT_ONOPEN_NAME"), - desc: fragWithHTML(t("ZOOM_TO_FIT_ONOPEN_DESC")), - control: { type: "toggle", key: "zoomToFitOnOpen" }, - }); - - this.buildSetting(detailsEl, { - name: t("ZOOM_TO_FIT_NAME"), - desc: fragWithHTML(t("ZOOM_TO_FIT_DESC")), - control: { type: "toggle", key: "zoomToFitOnResize" }, - }); - - this.buildSetting(detailsEl, { - name: t("ZOOM_TO_FIT_MAX_LEVEL_NAME"), - desc: t("ZOOM_TO_FIT_MAX_LEVEL_DESC"), - control: { - type: "slider", - key: "zoomToFitMaxLevel", + { + name: t("ZOOM_TO_FIT_ONOPEN_NAME"), + desc: fragWithHTML(t("ZOOM_TO_FIT_ONOPEN_DESC")), + aliases: ["zoom to fit", "file open"], + control: { type: "toggle", key: "zoomToFitOnOpen" }, + }, + { + name: t("ZOOM_TO_FIT_NAME"), + desc: fragWithHTML(t("ZOOM_TO_FIT_DESC")), + aliases: ["zoom to fit", "view resize"], + control: { type: "toggle", key: "zoomToFitOnResize" }, + }, + { + name: t("ZOOM_TO_FIT_MAX_LEVEL_NAME"), + desc: t("ZOOM_TO_FIT_MAX_LEVEL_DESC"), + aliases: ["zoom to fit maximum", "zoom level"], + control: { + type: "slider", + key: "zoomToFitMaxLevel", min: 0.5, - max: 10, - step: 0.5, + max: 10, + step: 0.5, + }, }, - }); - - this.buildSetting(detailsEl, { - name: t("ZOOM_STEP_NAME"), - desc: t("ZOOM_STEP_DESC"), - control: { - type: "slider", - key: "zoomStep", + { + name: t("ZOOM_STEP_NAME"), + desc: t("ZOOM_STEP_DESC"), + aliases: ["zoom increment", "zoom step"], + control: { + type: "slider", + key: "zoomStep", min: 1, max: 25, - step: 1, - scale: 100, + step: 1, + scale: 100, + }, }, - }); - - this.buildSetting(detailsEl, { - name: t("ZOOM_MIN_NAME"), - desc: t("ZOOM_MIN_DESC"), - control: { - type: "slider", - key: "zoomMin", + { + name: t("ZOOM_MIN_NAME"), + desc: t("ZOOM_MIN_DESC"), + aliases: ["minimum zoom", "zoom out"], + control: { + type: "slider", + key: "zoomMin", min: 1, max: 50, - step: 1, - scale: 100, + step: 1, + scale: 100, + }, }, - }); - - this.buildSetting(detailsEl, { - name: t("ZOOM_MAX_NAME"), - desc: t("ZOOM_MAX_DESC"), - control: { - type: "slider", - key: "zoomMax", + { + name: t("ZOOM_MAX_NAME"), + desc: t("ZOOM_MAX_DESC"), + aliases: ["maximum zoom", "zoom in"], + control: { + type: "slider", + key: "zoomMax", min: 500, max: 6000, - step: 100, - scale: 100, + step: 100, + scale: 100, + }, }, - }); + ]; + } - // ------------------------------------------------ - // Pen - // ------------------------------------------------ - detailsEl = displayDetailsEl.createEl("details"); - detailsEl.createEl("summary", { - text: t("PEN_HEAD"), - cls: "excalidraw-setting-h3", - }); + private renderZoomAndPanSettings(container: HTMLElement): void { + const specs = this.getZoomAndPanSpecs(); + this.renderSettingSpecs(container, specs.slice(0, 2)); + addYouTubeThumbnail(container, "rBarRfcSxNo", 107); + this.renderSettingSpecs(container, specs.slice(2)); + } - this.buildSetting(detailsEl, { - name: t("DEFAULT_PEN_MODE_NAME"), - desc: fragWithHTML(t("DEFAULT_PEN_MODE_DESC")), - control: { - type: "dropdown", - key: "defaultPenMode", + private getPenSpecs(): SettingSpec[] { + return [ + { + name: t("DEFAULT_PEN_MODE_NAME"), + desc: fragWithHTML(t("DEFAULT_PEN_MODE_DESC")), + aliases: ["pen mode", "stylus"], + control: { + type: "dropdown", + key: "defaultPenMode", options: [ { value: "never", label: t("DEFAULT_PEN_MODE_OPTION_NEVER") }, { value: "mobile", label: t("DEFAULT_PEN_MODE_OPTION_MOBILE") }, - { value: "always", label: t("DEFAULT_PEN_MODE_OPTION_ALWAYS") }, - ], + { value: "always", label: t("DEFAULT_PEN_MODE_OPTION_ALWAYS") }, + ], + }, }, + { + name: t("DISABLE_DOUBLE_TAP_ERASER_NAME"), + aliases: ["double tap eraser", "pen eraser"], + control: { type: "toggle", key: "penModeDoubleTapEraser" }, + }, + { + name: t("DISABLE_SINGLE_FINGER_PANNING_NAME"), + aliases: ["single finger pan", "pen panning"], + control: { type: "toggle", key: "penModeSingleFingerPanning" }, + }, + { + name: t("SHOW_PEN_MODE_FREEDRAW_CROSSHAIR_NAME"), + desc: fragWithHTML(t("SHOW_PEN_MODE_FREEDRAW_CROSSHAIR_DESC")), + aliases: ["pen crosshair", "freedraw crosshair"], + control: { type: "toggle", key: "penModeCrosshairVisible" }, + }, + ]; + } + + private createHotkeyEditorDefinition(): SettingDefinition { + return this.createRenderedDefinition({ + name: t("HOTKEY_OVERRIDE_CONTROL_NAME"), + desc: fragWithHTML(t("HOTKEY_OVERRIDE_DESC")), + aliases: ["hotkey override", "keyboard shortcut", "key combination"], + controlType: "hotkey editor", + render: (container) => this.renderHotkeyEditor(container), }); + } - this.buildSetting(detailsEl, { - name: t("DISABLE_DOUBLE_TAP_ERASER_NAME"), - control: { type: "toggle", key: "penModeDoubleTapEraser" }, + private renderHotkeyEditor(container: HTMLElement): () => void { + this.destroyHotkeyEditor(); + container.createSpan({}, (el) => { + setSanitizedHtml(el, t("HOTKEY_OVERRIDE_DESC")); }); + const editor = new HotkeyEditor( + container, + this.plugin.settings, + (requestReloadDrawings: boolean = false) => + this.applySettingsUpdate(requestReloadDrawings), + ); + this.hotkeyEditor = editor; + editor.onload(); + return () => this.disposeHotkeyEditor(editor); + } - this.buildSetting(detailsEl, { - name: t("DISABLE_SINGLE_FINGER_PANNING_NAME"), - control: { type: "toggle", key: "penModeSingleFingerPanning" }, - }); + private disposeHotkeyEditor(editor: HotkeyEditor): void { + editor.unload(); + if (editor.isDirty) { + this.plugin.registerHotkeyOverrides(); + } + if (this.hotkeyEditor === editor) { + this.hotkeyEditor = null; + } + } - this.buildSetting(detailsEl, { - name: t("SHOW_PEN_MODE_FREEDRAW_CROSSHAIR_NAME"), - desc: fragWithHTML(t("SHOW_PEN_MODE_FREEDRAW_CROSSHAIR_DESC")), - control: { type: "toggle", key: "penModeCrosshairVisible" }, - }); + private destroyHotkeyEditor(): void { + if (this.hotkeyEditor !== null) { + this.disposeHotkeyEditor(this.hotkeyEditor); + } + } - // ------------------------------------------------ - // Grid - // ------------------------------------------------ - detailsEl = displayDetailsEl.createEl("details"); - detailsEl.createEl("summary", { - text: t("GRID_HEAD"), - cls: "excalidraw-setting-h3", - }); + private updateGridColor(): void { + getExcalidrawViews(this.app, true).forEach((excalidrawView) => + excalidrawView.updateGridColor(), + ); + } - const updateGridColor = () => { - getExcalidrawViews(this.app, true).forEach((excalidrawView) => - excalidrawView.updateGridColor(), - ); - }; + private updateGridDirection(): void { + getExcalidrawViews(this.app, true).forEach((excalidrawView) => + excalidrawView.updateGridDirection( + this.plugin.settings.gridSettings.GRID_DIRECTION, + ), + ); + } - const updateGridDirection = () => { - getExcalidrawViews(this.app, true).forEach((excalidrawView) => - excalidrawView.updateGridDirection( - this.plugin.settings.gridSettings.GRID_DIRECTION, - ), - ); - }; - - new Setting(detailsEl) + private configureGridDirectionSetting(setting: Setting): void { + setting .setName(t("GRID_DIRECTION_NAME")) .setDesc(t("GRID_DIRECTION_DESC")) .addToggle((toggle) => @@ -2276,15 +2630,13 @@ export class ExcalidrawSettingTab extends PluginSettingTab { true, ) .onChange((value) => { - if (!this.plugin.settings.gridSettings.GRID_DIRECTION) { - this.plugin.settings.gridSettings.GRID_DIRECTION = { - horizontal: true, - vertical: true, - }; - } //2.10.1 migration + this.plugin.settings.gridSettings.GRID_DIRECTION ??= { + horizontal: true, + vertical: true, + }; this.plugin.settings.gridSettings.GRID_DIRECTION.horizontal = value; this.applySettingsUpdate(); - updateGridDirection(); + this.updateGridDirection(); }), ) .addToggle((toggle) => @@ -2294,407 +2646,594 @@ export class ExcalidrawSettingTab extends PluginSettingTab { this.plugin.settings.gridSettings.GRID_DIRECTION?.vertical ?? true, ) .onChange((value) => { - if (!this.plugin.settings.gridSettings.GRID_DIRECTION) { - this.plugin.settings.gridSettings.GRID_DIRECTION = { - horizontal: true, - vertical: true, - }; - } //2.10.1 migration + this.plugin.settings.gridSettings.GRID_DIRECTION ??= { + horizontal: true, + vertical: true, + }; this.plugin.settings.gridSettings.GRID_DIRECTION.vertical = value; this.applySettingsUpdate(); - updateGridDirection(); + this.updateGridDirection(); }), ); + } - // Dynamic color toggle - new Setting(detailsEl) + private configureDynamicGridColorSetting(setting: Setting): void { + setting .setName(t("GRID_DYNAMIC_COLOR_NAME")) .setDesc(fragWithHTML(t("GRID_DYNAMIC_COLOR_DESC"))) .addToggle((toggle) => toggle .setValue(this.plugin.settings.gridSettings.DYNAMIC_COLOR) - .onChange(async (value) => { + .onChange((value) => { this.plugin.settings.gridSettings.DYNAMIC_COLOR = value; - if (value) { - hideElement(gridColorSection); - } else { - showElement(gridColorSection); + if ( + this.gridColorSettingEl && + this.gridColorSettingEl.isConnected + ) { + if (value) { + hideElement(this.gridColorSettingEl); + } else { + showElement(this.gridColorSettingEl); + } } this.applySettingsUpdate(); - updateGridColor(); + this.updateGridColor(); + this.refreshDeclarativeDomState(); }), ); + } - // Create a div to contain color and opacity settings - const gridColorSection = detailsEl.createDiv(); + private configureGridColorSetting(setting: Setting): void { + this.gridColorSettingEl = setting.settingEl; + setting.setName(t("GRID_COLOR_NAME")).addColorPicker((colorPicker) => + colorPicker + .setValue(this.plugin.settings.gridSettings.COLOR) + .onChange((value) => { + this.plugin.settings.gridSettings.COLOR = value; + this.applySettingsUpdate(); + this.updateGridColor(); + }), + ); if (this.plugin.settings.gridSettings.DYNAMIC_COLOR) { - hideElement(gridColorSection); + hideElement(setting.settingEl); } else { - showElement(gridColorSection); + showElement(setting.settingEl); } + } - // Grid color picker - new Setting(gridColorSection) - .setName(t("GRID_COLOR_NAME")) - .addColorPicker((colorPicker) => - colorPicker - .setValue(this.plugin.settings.gridSettings.COLOR) - .onChange(async (value) => { - this.plugin.settings.gridSettings.COLOR = value; - this.applySettingsUpdate(); - updateGridColor(); - }), - ); - - // Grid opacity slider (hex value between 00 and FF) - createSliderWithText(detailsEl, { + private configureGridOpacitySetting(setting: Setting): void { + configureSliderWithText(setting, { name: t("GRID_OPACITY_NAME"), desc: t("GRID_OPACITY_DESC"), value: this.plugin.settings.gridSettings.OPACITY, min: 0, max: 100, step: 1, + minWidth: "3em", onChange: (value) => { this.plugin.settings.gridSettings.OPACITY = value; this.applySettingsUpdate(); - updateGridColor(); + this.updateGridColor(); }, - minWidth: "3em", }); + } - // ------------------------------------------------ - // Laser Pointer - // ------------------------------------------------ - detailsEl = displayDetailsEl.createEl("details"); - detailsEl.createEl("summary", { - text: t("LASER_HEAD"), - cls: "excalidraw-setting-h3", - }); - new Setting(detailsEl) - .setName(t("LASER_COLOR")) - .addColorPicker((colorPicker) => - colorPicker - .setValue(this.plugin.settings.laserSettings.COLOR) - .onChange(async (value) => { - this.plugin.settings.laserSettings.COLOR = value; - this.applySettingsUpdate(); - }), - ); + private getGridDefinitions(): SettingDefinitionItem[] { + return [ + this.createCustomSettingDefinition({ + name: t("GRID_DIRECTION_NAME"), + desc: t("GRID_DIRECTION_DESC"), + aliases: ["horizontal grid", "vertical grid", "grid direction"], + controlType: "toggle group", + configure: (setting) => this.configureGridDirectionSetting(setting), + }), + this.createCustomSettingDefinition({ + name: t("GRID_DYNAMIC_COLOR_NAME"), + desc: fragWithHTML(t("GRID_DYNAMIC_COLOR_DESC")), + aliases: ["automatic grid color", "canvas color"], + controlType: "toggle", + configure: (setting) => this.configureDynamicGridColorSetting(setting), + }), + this.createCustomSettingDefinition({ + name: t("GRID_COLOR_NAME"), + aliases: ["custom grid color"], + visible: () => !this.plugin.settings.gridSettings.DYNAMIC_COLOR, + controlType: "color picker", + configure: (setting) => this.configureGridColorSetting(setting), + }), + this.createCustomSettingDefinition({ + name: t("GRID_OPACITY_NAME"), + desc: t("GRID_OPACITY_DESC"), + aliases: ["grid transparency"], + controlType: "slider", + configure: (setting) => this.configureGridOpacitySetting(setting), + }), + ]; + } - createSliderWithText(detailsEl, { + private renderGridSettings(container: HTMLElement): void { + this.configureGridDirectionSetting(new Setting(container)); + this.configureDynamicGridColorSetting(new Setting(container)); + this.configureGridColorSetting(new Setting(container)); + this.configureGridOpacitySetting(new Setting(container)); + } + + private configureLaserColorSetting(setting: Setting): void { + setting.setName(t("LASER_COLOR")).addColorPicker((colorPicker) => + colorPicker + .setValue(this.plugin.settings.laserSettings.COLOR) + .onChange((value) => { + this.plugin.settings.laserSettings.COLOR = value; + this.applySettingsUpdate(); + }), + ); + } + + private configureLaserDecayTimeSetting(setting: Setting): void { + configureSliderWithText(setting, { name: t("LASER_DECAY_TIME_NAME"), desc: t("LASER_DECAY_TIME_DESC"), value: this.plugin.settings.laserSettings.DECAY_TIME, min: 500, max: 20000, step: 500, + minWidth: "3em", onChange: (value) => { this.plugin.settings.laserSettings.DECAY_TIME = value; this.applySettingsUpdate(); }, - minWidth: "3em", }); + } - createSliderWithText(detailsEl, { + private configureLaserDecayLengthSetting(setting: Setting): void { + configureSliderWithText(setting, { name: t("LASER_DECAY_LENGTH_NAME"), desc: t("LASER_DECAY_LENGTH_DESC"), value: this.plugin.settings.laserSettings.DECAY_LENGTH, min: 25, max: 2000, step: 25, + minWidth: "3em", onChange: (value) => { this.plugin.settings.laserSettings.DECAY_LENGTH = value; this.applySettingsUpdate(); }, - minWidth: "3em", }); + } - detailsEl = displayDetailsEl.createEl("details"); - detailsEl.createEl("summary", { - text: t("DRAG_MODIFIER_NAME"), - cls: "excalidraw-setting-h3", + private getLaserDefinitions(): SettingDefinitionItem[] { + return [ + this.createCustomSettingDefinition({ + name: t("LASER_COLOR"), + aliases: ["laser pointer color"], + controlType: "color picker", + configure: (setting) => this.configureLaserColorSetting(setting), + }), + this.createCustomSettingDefinition({ + name: t("LASER_DECAY_TIME_NAME"), + desc: t("LASER_DECAY_TIME_DESC"), + aliases: ["laser duration", "laser time"], + controlType: "slider", + configure: (setting) => this.configureLaserDecayTimeSetting(setting), + }), + this.createCustomSettingDefinition({ + name: t("LASER_DECAY_LENGTH_NAME"), + desc: t("LASER_DECAY_LENGTH_DESC"), + aliases: ["laser trail", "laser length"], + controlType: "slider", + configure: (setting) => this.configureLaserDecayLengthSetting(setting), + }), + ]; + } + + private renderLaserSettings(container: HTMLElement): void { + this.configureLaserColorSetting(new Setting(container)); + this.configureLaserDecayTimeSetting(new Setting(container)); + this.configureLaserDecayLengthSetting(new Setting(container)); + } + + private getLinkOpeningGestureSpecs(): SettingSpec[] { + return [ + { + name: t("LONG_PRESS_DESKTOP_NAME"), + desc: t("LONG_PRESS_DESKTOP_DESC"), + aliases: ["long press desktop", "embedded drawing"], + control: { + type: "slider", + key: "longPressDesktop", + min: 300, + max: 3000, + step: 100, + reload: true, + }, + }, + { + name: t("LONG_PRESS_MOBILE_NAME"), + desc: t("LONG_PRESS_MOBILE_DESC"), + aliases: ["long press mobile", "embedded drawing"], + control: { + type: "slider", + key: "longPressMobile", + min: 300, + max: 3000, + step: 100, + reload: true, + }, + }, + { + name: t("DOUBLE_CLICK_LINK_OPEN_VIEW_MODE"), + aliases: ["double click link", "view mode link"], + control: { type: "toggle", key: "doubleClickLinkOpenViewMode" }, + }, + ]; + } + + private getModifierKeyCategoryDescription( + modifierSetType: ModifierSetType, + ): string { + switch (modifierSetType) { + case "WebBrowserDragAction": + return t("WEB_BROWSER_DRAG_ACTION_DESC"); + case "LocalFileDragAction": + return t("LOCAL_FILE_DRAG_ACTION_DESC"); + case "InternalDragAction": + return t("INTERNAL_DRAG_ACTION_DESC"); + case "LinkClickAction": + return t("PANE_TARGET_DESC"); + } + } + + private createModifierKeyUsageDefinition(): SettingDefinition { + return this.createRenderedDefinition({ + name: t("MODIFIER_KEY_USAGE_NAME"), + desc: t("DRAG_MODIFIER_DESC"), + aliases: [ + "modifier key", + "shift", + "control", + "command", + "alt", + "option", + "meta", + ], + controlType: "information", + render: (container) => this.renderModifierKeyUsage(container), }); - detailsEl.createDiv({ + } + + private renderModifierKeyUsage(container: HTMLElement): void { + container.createDiv({ text: t("DRAG_MODIFIER_DESC"), cls: "setting-item-description", }); - - this.buildSetting(detailsEl, { - name: t("LONG_PRESS_DESKTOP_NAME"), - desc: t("LONG_PRESS_DESKTOP_DESC"), - control: { - type: "slider", - key: "longPressDesktop", - min: 300, - max: 3000, - step: 100, - reload: true, - }, - }); - - this.buildSetting(detailsEl, { - name: t("LONG_PRESS_MOBILE_NAME"), - desc: t("LONG_PRESS_MOBILE_DESC"), - control: { - type: "slider", - key: "longPressMobile", - min: 300, - max: 3000, - step: 100, - reload: true, - }, - }); - - this.buildSetting(detailsEl, { - name: t("DOUBLE_CLICK_LINK_OPEN_VIEW_MODE"), - control: { type: "toggle", key: "doubleClickLinkOpenViewMode" }, - }); - - new ModifierKeySettingsComponent( - detailsEl, - this.plugin.settings.modifierKeyConfig, - () => this.applySettingsUpdate(), - ).render(); - } - private renderLinksAndTransclusionsSection(): void { - const { containerEl } = this; - let detailsEl: HTMLElement; - // ------------------------------------------------ - // Links and Transclusions - // ------------------------------------------------ - containerEl.createEl("hr", { cls: "excalidraw-setting-hr" }); - containerEl.createDiv({ - text: t("LINKS_HEAD_DESC"), - cls: "setting-item-description", - }); - detailsEl = this.containerEl.createEl("details"); - detailsEl.createEl("summary", { - text: t("LINKS_HEAD"), - cls: "excalidraw-setting-h1", + private createModifierKeyCategoryDefinition( + modifierSetType: ModifierSetType, + ): SettingDefinition { + const categoryName = getModifierKeyCategoryName(modifierSetType); + const actionAliases = Object.values( + modifierKeyTooltipMessages()[modifierSetType] ?? {}, + ).filter((value): value is string => typeof value === "string"); + return this.createRenderedDefinition({ + name: categoryName + " · " + t("MODIFIER_KEY_COMBINATIONS"), + desc: this.getModifierKeyCategoryDescription(modifierSetType), + aliases: [ + categoryName, + ...actionAliases, + "shift", + "control", + "command", + "alt", + "option", + "meta", + ], + controlType: "modifier toggle matrix", + render: (container) => + this.renderModifierKeyCategory(container, modifierSetType), }); + } - detailsEl.createSpan(undefined, (el) => - setSanitizedHtml(el, t("LINKS_DESC")), - ); + private renderModifierKeyCategory( + container: HTMLElement, + modifierSetType: ModifierSetType, + ): void { + new ModifierKeySettingsComponent( + container, + this.plugin.settings.modifierKeyConfig, + () => this.applySettingsUpdate(), + ).renderCategory(modifierSetType, false); + } - this.buildSetting(detailsEl, { - name: t("ELEMENT_LINK_SYNC_NAME"), - desc: fragWithHTML(t("ELEMENT_LINK_SYNC_DESC")), - control: { type: "toggle", key: "syncElementLinkWithText" }, - }); - - this.buildSetting(detailsEl, { - name: t("SECOND_ORDER_LINKS_NAME"), - desc: fragWithHTML(t("SECOND_ORDER_LINKS_DESC")), - control: { type: "toggle", key: "showSecondOrderLinks" }, - }); - - this.buildSetting(detailsEl, { - name: t("ADJACENT_PANE_NAME"), - desc: fragWithHTML(t("ADJACENT_PANE_DESC")), - control: { type: "toggle", key: "openInAdjacentPane" }, - }); - - this.buildSetting(detailsEl, { - name: t("FOCUS_ON_EXISTING_TAB_NAME"), - desc: fragWithHTML(t("FOCUS_ON_EXISTING_TAB_DESC")), - control: { type: "toggle", key: "focusOnFileTab" }, - }); - - this.buildSetting(detailsEl, { - name: t("MAINWORKSPACE_PANE_NAME"), - desc: fragWithHTML(t("MAINWORKSPACE_PANE_DESC")), - control: { type: "toggle", key: "openInMainWorkspace" }, - }); - - this.buildSetting(detailsEl, { - name: fragWithHTML(t("LINK_BRACKETS_NAME")), - desc: fragWithHTML(t("LINK_BRACKETS_DESC")), - control: { type: "toggle", key: "showLinkBrackets", reload: true }, - }); - - this.buildSetting(detailsEl, { - name: t("LINK_PREFIX_NAME"), - desc: fragWithHTML(t("LINK_PREFIX_DESC")), - control: { - type: "text", - key: "linkPrefix", - placeholder: t("INSERT_EMOJI"), - reload: true, + private createLinkUsageDefinition(): SettingDefinition { + return this.createRenderedDefinition({ + name: t("LINK_USAGE_NAME"), + desc: fragWithHTML(t("LINKS_DESC")), + aliases: ["wiki link", "web link", "ctrl click", "link alias"], + controlType: "information", + render: (container) => { + container.createSpan({}, (el) => setSanitizedHtml(el, t("LINKS_DESC"))); }, }); + } - this.buildSetting(detailsEl, { - name: t("URL_PREFIX_NAME"), - desc: fragWithHTML(t("URL_PREFIX_DESC")), - control: { - type: "text", - key: "urlPrefix", - placeholder: t("INSERT_EMOJI"), - reload: true, + private getLinkBehaviorSpecs(): SettingSpec[] { + return [ + { + name: t("ELEMENT_LINK_SYNC_NAME"), + desc: fragWithHTML(t("ELEMENT_LINK_SYNC_DESC")), + aliases: ["element link", "text link", "sync link"], + control: { type: "toggle", key: "syncElementLinkWithText" }, }, - }); + { + name: t("SECOND_ORDER_LINKS_NAME"), + desc: fragWithHTML(t("SECOND_ORDER_LINKS_DESC")), + aliases: ["second order link", "backlink"], + control: { type: "toggle", key: "showSecondOrderLinks" }, + }, + { + name: t("HOVERPREVIEW_NAME"), + desc: fragWithHTML(t("HOVERPREVIEW_DESC")), + aliases: ["hover preview", "link preview"], + control: { type: "toggle", key: "hoverPreviewWithoutCTRL" }, + }, + { + name: t("LINK_CTRL_CLICK_NAME"), + desc: fragWithHTML(t("LINK_CTRL_CLICK_DESC")), + aliases: ["ctrl click", "command click", "open link"], + control: { type: "toggle", key: "allowCtrlClick" }, + }, + { + name: t("GET_URL_TITLE_NAME"), + desc: fragWithHTML(t("GET_URL_TITLE_DESC")), + aliases: ["oEmbed", "URL title", "web page title"], + control: { type: "toggle", key: "oEmbedAllowed" }, + }, + ]; + } - let todoPrefixSetting: TextComponent; - let donePrefixSetting: TextComponent; + private renderLinkBehaviorSettings(container: HTMLElement): void { + container.createSpan({}, (el) => setSanitizedHtml(el, t("LINKS_DESC"))); + this.renderSettingSpecs(container, this.getLinkBehaviorSpecs()); + } - this.buildSetting(detailsEl, { - name: t("PARSE_TODO_NAME"), - desc: fragWithHTML(t("PARSE_TODO_DESC")), - control: { - type: "toggle", - key: "parseTODO", - after: (value) => { - todoPrefixSetting.setDisabled(!value); - donePrefixSetting.setDisabled(!value); + private getLinkOpeningSpecs(): SettingSpec[] { + return [ + { + name: t("ADJACENT_PANE_NAME"), + desc: fragWithHTML(t("ADJACENT_PANE_DESC")), + aliases: ["adjacent pane", "reuse pane"], + control: { type: "toggle", key: "openInAdjacentPane" }, + }, + { + name: t("FOCUS_ON_EXISTING_TAB_NAME"), + desc: fragWithHTML(t("FOCUS_ON_EXISTING_TAB_DESC")), + aliases: ["existing tab", "focus tab"], + control: { type: "toggle", key: "focusOnFileTab" }, + }, + { + name: t("MAINWORKSPACE_PANE_NAME"), + desc: fragWithHTML(t("MAINWORKSPACE_PANE_DESC")), + aliases: ["main workspace", "popout link"], + control: { type: "toggle", key: "openInMainWorkspace" }, + }, + ]; + } + + private getLinkAppearanceSpecs(): SettingSpec[] { + return [ + { + name: fragWithHTML(t("LINK_BRACKETS_NAME")), + desc: fragWithHTML(t("LINK_BRACKETS_DESC")), + aliases: ["wiki link brackets", "preview brackets"], + control: { type: "toggle", key: "showLinkBrackets", reload: true }, + }, + { + name: t("LINK_PREFIX_NAME"), + desc: fragWithHTML(t("LINK_PREFIX_DESC")), + aliases: ["link icon", "link emoji", "link prefix"], + control: { + type: "text", + key: "linkPrefix", + placeholder: t("INSERT_EMOJI"), + reload: true, }, - reload: true, }, - }); - - this.buildSetting(detailsEl, { - name: t("TODO_NAME"), - desc: fragWithHTML(t("TODO_DESC")), - control: { - type: "text", - key: "todo", - placeholder: t("INSERT_EMOJI"), - capture: (text) => { - todoPrefixSetting = text; + { + name: t("URL_PREFIX_NAME"), + desc: fragWithHTML(t("URL_PREFIX_DESC")), + aliases: ["URL icon", "URL emoji", "web link prefix"], + control: { + type: "text", + key: "urlPrefix", + placeholder: t("INSERT_EMOJI"), + reload: true, }, - reload: true, }, - }); - todoPrefixSetting.setDisabled(!this.plugin.settings.parseTODO); - - const doneSetting = this.buildSetting(detailsEl, { - name: t("DONE_NAME"), - desc: fragWithHTML(t("DONE_DESC")), - control: { - type: "text", - key: "done", - placeholder: t("INSERT_EMOJI"), - capture: (text) => { - donePrefixSetting = text; + { + name: t("LINKOPACITY_NAME"), + desc: t("LINKOPACITY_DESC"), + aliases: ["link icon opacity", "link transparency"], + control: { + type: "slider", + key: "linkOpacity", + min: 0, + max: 1, + step: 0.05, + reload: true, }, - reload: true, }, - }); - doneSetting?.setDisabled(!this.plugin.settings.parseTODO); - donePrefixSetting.setDisabled(!this.plugin.settings.parseTODO); + ]; + } - this.buildSetting(detailsEl, { - name: t("LINKOPACITY_NAME"), - desc: t("LINKOPACITY_DESC"), - control: { - type: "slider", - key: "linkOpacity", - min: 0, - max: 1, - step: 0.05, - reload: true, + private getTodoSpecs(): SettingSpec[] { + return [ + { + name: t("PARSE_TODO_NAME"), + desc: fragWithHTML(t("PARSE_TODO_DESC")), + aliases: ["todo checkbox", "task checkbox", "parse task"], + control: { + type: "toggle", + key: "parseTODO", + after: (value) => { + this.todoPrefixSetting?.setDisabled(!value); + this.donePrefixSetting?.setDisabled(!value); + }, + reload: true, + }, }, - }); + { + name: t("TODO_NAME"), + desc: fragWithHTML(t("TODO_DESC")), + aliases: ["open todo", "todo icon", "unchecked task"], + control: { + type: "text", + key: "todo", + placeholder: t("INSERT_EMOJI"), + capture: (text) => { + this.todoPrefixSetting = text; + }, + disabled: () => !this.plugin.settings.parseTODO, + reload: true, + }, + }, + { + name: t("DONE_NAME"), + desc: fragWithHTML(t("DONE_DESC")), + aliases: ["completed todo", "done icon", "checked task"], + control: { + type: "text", + key: "done", + placeholder: t("INSERT_EMOJI"), + capture: (text) => { + this.donePrefixSetting = text; + }, + disabled: () => !this.plugin.settings.parseTODO, + reload: true, + }, + }, + ]; + } - this.buildSetting(detailsEl, { - name: t("HOVERPREVIEW_NAME"), - desc: fragWithHTML(t("HOVERPREVIEW_DESC")), - control: { type: "toggle", key: "hoverPreviewWithoutCTRL" }, - }); + private getTransclusionToggleSpecs(): SettingSpec[] { + return [ + { + name: t("TRANSCLUSION_WRAP_NAME"), + desc: fragWithHTML( + "![[doc#^ref]]{number} " + t("TRANSCLUSION_WRAP_DESC"), + ), + aliases: ["transclusion wrap", "force wrap", "overflow"], + control: { type: "toggle", key: "forceWrap", reload: true }, + }, + { + name: t("QUOTE_TRANSCLUSION_REMOVE_NAME"), + desc: fragWithHTML(t("QUOTE_TRANSCLUSION_REMOVE_DESC")), + aliases: ["quote transclusion", "remove quote signs"], + control: { + type: "toggle", + key: "removeTransclusionQuoteSigns", + after: () => { + this.requestEmbedUpdate = true; + }, + reload: true, + }, + }, + ]; + } - this.buildSetting(detailsEl, { - name: t("LINK_CTRL_CLICK_NAME"), - desc: fragWithHTML(t("LINK_CTRL_CLICK_DESC")), - control: { type: "toggle", key: "allowCtrlClick" }, - }); - - const s = this.buildSetting(detailsEl, { - name: t("TRANSCLUSION_WRAP_NAME"), - desc: fragWithHTML(t("TRANSCLUSION_WRAP_DESC")), - control: { type: "toggle", key: "forceWrap", reload: true }, - }); - setSanitizedHtml( - s.descEl, - `![[doc#^ref]]{number} ${t("TRANSCLUSION_WRAP_DESC")}`, - ); - - new Setting(detailsEl) - .setName(t("PAGE_TRANSCLUSION_CHARCOUNT_NAME")) - .setDesc(fragWithHTML(t("PAGE_TRANSCLUSION_CHARCOUNT_DESC"))) + private configureIntegerTextSetting( + setting: Setting, + options: { + name: string; + desc: string | DocumentFragment; + key: "pageTransclusionCharLimit" | "wordWrappingDefault"; + emptyValue: number; + }, + ): void { + setting + .setName(options.name) + .setDesc(options.desc) .addText((text) => text .setPlaceholder("Enter a number") - .setValue(this.plugin.settings.pageTransclusionCharLimit.toString()) - .onChange(async (value) => { - const intVal = parseInt(value); - if (isNaN(intVal) && value !== "") { - text.setValue( - this.plugin.settings.pageTransclusionCharLimit.toString(), - ); + .setValue(this.plugin.settings[options.key].toString()) + .onChange((value) => { + const parsedValue = parseInt(value, 10); + if (isNaN(parsedValue) && value !== "") { + text.setValue(this.plugin.settings[options.key].toString()); return; } this.requestEmbedUpdate = true; if (value === "") { - this.plugin.settings.pageTransclusionCharLimit = 10; + this.plugin.settings[options.key] = options.emptyValue; this.applySettingsUpdate(true); return; } - this.plugin.settings.pageTransclusionCharLimit = intVal; - text.setValue( - this.plugin.settings.pageTransclusionCharLimit.toString(), - ); + this.plugin.settings[options.key] = parsedValue; + text.setValue(parsedValue.toString()); this.applySettingsUpdate(true); }), ); + } - new Setting(detailsEl) - .setName(t("TRANSCLUSION_DEFAULT_WRAP_NAME")) - .setDesc(fragWithHTML(t("TRANSCLUSION_DEFAULT_WRAP_DESC"))) - .addText((text) => - text - .setPlaceholder("Enter a number") - .setValue(this.plugin.settings.wordWrappingDefault.toString()) - .onChange(async (value) => { - const intVal = parseInt(value); - if (isNaN(intVal) && value !== "") { - text.setValue( - this.plugin.settings.wordWrappingDefault.toString(), - ); - return; - } - this.requestEmbedUpdate = true; - if (value === "") { - this.plugin.settings.wordWrappingDefault = 0; - this.applySettingsUpdate(true); - return; - } - this.plugin.settings.wordWrappingDefault = intVal; - text.setValue(this.plugin.settings.wordWrappingDefault.toString()); - this.applySettingsUpdate(true); - }), - ); - - this.buildSetting(detailsEl, { - name: t("QUOTE_TRANSCLUSION_REMOVE_NAME"), - desc: fragWithHTML(t("QUOTE_TRANSCLUSION_REMOVE_DESC")), - control: { - type: "toggle", - key: "removeTransclusionQuoteSigns", - after: () => { - this.requestEmbedUpdate = true; - }, - reload: true, - }, + private createPageTransclusionLimitDefinition(): SettingDefinition { + return this.createCustomSettingDefinition({ + name: t("PAGE_TRANSCLUSION_CHARCOUNT_NAME"), + desc: fragWithHTML(t("PAGE_TRANSCLUSION_CHARCOUNT_DESC")), + aliases: ["page transclusion limit", "maximum characters"], + controlType: "number input", + configure: (setting) => + this.configureIntegerTextSetting(setting, { + name: t("PAGE_TRANSCLUSION_CHARCOUNT_NAME"), + desc: fragWithHTML(t("PAGE_TRANSCLUSION_CHARCOUNT_DESC")), + key: "pageTransclusionCharLimit", + emptyValue: 10, + }), }); + } - this.buildSetting(detailsEl, { - name: t("GET_URL_TITLE_NAME"), - desc: fragWithHTML(t("GET_URL_TITLE_DESC")), - control: { type: "toggle", key: "oEmbedAllowed" }, + private createTransclusionWrapDefaultDefinition(): SettingDefinition { + return this.createCustomSettingDefinition({ + name: t("TRANSCLUSION_DEFAULT_WRAP_NAME"), + desc: fragWithHTML(t("TRANSCLUSION_DEFAULT_WRAP_DESC")), + aliases: ["transclusion wrap default", "word wrap length"], + controlType: "number input", + configure: (setting) => + this.configureIntegerTextSetting(setting, { + name: t("TRANSCLUSION_DEFAULT_WRAP_NAME"), + desc: fragWithHTML(t("TRANSCLUSION_DEFAULT_WRAP_DESC")), + key: "wordWrappingDefault", + emptyValue: 0, + }), }); + } + private getTransclusionDefinitions(): SettingDefinitionItem[] { + const specs = this.getTransclusionToggleSpecs(); + return [ + this.declarativeSettingsAdapter.toDefinition(specs[0]), + this.createPageTransclusionLimitDefinition(), + this.createTransclusionWrapDefaultDefinition(), + this.declarativeSettingsAdapter.toDefinition(specs[1]), + ]; + } + + private renderTransclusionSettings(container: HTMLElement): void { + const specs = this.getTransclusionToggleSpecs(); + this.buildSetting(container, specs[0]); + this.configureIntegerTextSetting(new Setting(container), { + name: t("PAGE_TRANSCLUSION_CHARCOUNT_NAME"), + desc: fragWithHTML(t("PAGE_TRANSCLUSION_CHARCOUNT_DESC")), + key: "pageTransclusionCharLimit", + emptyValue: 10, + }); + this.configureIntegerTextSetting(new Setting(container), { + name: t("TRANSCLUSION_DEFAULT_WRAP_NAME"), + desc: fragWithHTML(t("TRANSCLUSION_DEFAULT_WRAP_DESC")), + key: "wordWrappingDefault", + emptyValue: 0, + }); + this.buildSetting(container, specs[1]); } private renderEmbedAndExportSection(): void { @@ -3077,7 +3616,6 @@ export class ExcalidrawSettingTab extends PluginSettingTab { desc: fragWithHTML(t("EXPORT_BOTH_DARK_AND_LIGHT_DESC")), control: { type: "toggle", key: "autoExportLightAndDark" }, }); - } private renderEmbeddingSettingsSection(): void { @@ -3204,14 +3742,8 @@ export class ExcalidrawSettingTab extends PluginSettingTab { .setName(t("MD_DEFAULT_FONT_NAME")) .setDesc(fragWithHTML(t("MD_DEFAULT_FONT_DESC"))); this.fontPickers.push( - new FontPickerComponent( - markdownFontSetting.controlEl, - this.app, - () => - getSelectableFontOptions( - this.app, - this.plugin.settings.fontAssetsPath, - ), + new FontPickerComponent(markdownFontSetting.controlEl, this.app, () => + getSelectableFontOptions(this.app, this.plugin.settings.fontAssetsPath), ) .setAriaLabel(t("MD_DEFAULT_FONT_NAME")) .setValue(this.plugin.settings.mdFont) @@ -3263,7 +3795,6 @@ export class ExcalidrawSettingTab extends PluginSettingTab { reload: true, }, }); - } private renderNonExcalidrawFeaturesSection(): void { @@ -3299,7 +3830,8 @@ export class ExcalidrawSettingTab extends PluginSettingTab { min: 1, max: 10, step: 0.5, - afterUpdate: () => this.plugin.excalidrawConfig.updateValues(this.plugin), + afterUpdate: () => + this.plugin.excalidrawConfig.updateValues(this.plugin), }, }); @@ -3325,7 +3857,6 @@ export class ExcalidrawSettingTab extends PluginSettingTab { }, }, }); - } private renderFontsSection(): void { @@ -3373,13 +3904,10 @@ export class ExcalidrawSettingTab extends PluginSettingTab { .setName(t("FOURTH_FONT_NAME")) .setDesc(fragWithHTML(t("FOURTH_FONT_DESC"))); this.fontPickers.push( - new FontPickerComponent( - fourthFontSetting.controlEl, - this.app, - () => - getSelectableFontOptions( - this.app, - this.plugin.settings.fontAssetsPath, + new FontPickerComponent(fourthFontSetting.controlEl, this.app, () => + getSelectableFontOptions( + this.app, + this.plugin.settings.fontAssetsPath, ["Virgil"], ), ) @@ -3427,7 +3955,6 @@ export class ExcalidrawSettingTab extends PluginSettingTab { name: t("LOAD_KOREAN_FONTS_NAME"), control: { type: "toggle", key: "loadKoreanFonts" }, }); - } private renderExperimentalFeaturesSection(): void { @@ -3557,13 +4084,10 @@ export class ExcalidrawSettingTab extends PluginSettingTab { capture: (text) => { taskboneAPIKeyText = text; configurePasswordTextInput(taskboneAPIKeyText); - taskboneAPIKeyText.setDisabled( - !this.plugin.settings.taskboneEnabled, - ); + taskboneAPIKeyText.setDisabled(!this.plugin.settings.taskboneEnabled); }, }, }); - } private renderExcalidrawAutomateSection(): void { @@ -3977,5 +4501,4 @@ export class ExcalidrawSettingTab extends PluginSettingTab { }); } } - } diff --git a/src/core/settings/LegacySettingsAdapter.ts b/src/core/settings/LegacySettingsAdapter.ts index 1a099efb..23ccfcdb 100644 --- a/src/core/settings/LegacySettingsAdapter.ts +++ b/src/core/settings/LegacySettingsAdapter.ts @@ -47,6 +47,10 @@ export class LegacySettingsAdapter { /** Configures a row supplied by either the legacy or declarative host. */ configure(setting: Setting, spec: SettingSpec): void { const control = spec.control; + const disabled = + typeof control.disabled === "function" + ? control.disabled() + : (control.disabled ?? false); if (control.type === "slider") { configureSliderWithText(setting, { name: spec.name, @@ -58,6 +62,7 @@ export class LegacySettingsAdapter { minWidth: control.minWidth, onChange: (value) => this.bindings.setLegacySpecValue(spec, value), }); + setting.setDisabled(disabled); return; } @@ -65,13 +70,6 @@ export class LegacySettingsAdapter { if (spec.desc) { setting.setDesc(spec.desc); } - const disabled = - typeof control.disabled === "function" - ? control.disabled() - : (control.disabled ?? false); - if (disabled) { - setting.setDisabled(true); - } switch (control.type) { case "toggle": @@ -82,7 +80,7 @@ export class LegacySettingsAdapter { this.bindings.setLegacySpecValue(spec, value), ), ); - return; + break; case "text": setting.addText((text) => { control.capture?.(text); @@ -107,7 +105,7 @@ export class LegacySettingsAdapter { ); } }); - return; + break; case "dropdown": setting.addDropdown((dropdown) => { for (const option of control.options) { @@ -119,7 +117,7 @@ export class LegacySettingsAdapter { this.bindings.setLegacySpecValue(spec, value), ); }); - return; + break; case "number-dropdown": setting.addDropdown((dropdown) => { for (const option of control.options) { @@ -132,5 +130,9 @@ export class LegacySettingsAdapter { ); }); } + // Setting#setDisabled only affects controls that already exist. Apply the + // initial predicate after configuring the row so dependent controls start + // in the same state in both legacy and declarative render paths. + setting.setDisabled(disabled); } } diff --git a/src/core/settingsDefaults.ts b/src/core/settingsDefaults.ts index 4341663f..8497751c 100644 --- a/src/core/settingsDefaults.ts +++ b/src/core/settingsDefaults.ts @@ -561,7 +561,7 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = { urlPrefix: "", parseTODO: false, todo: "☐", - done: "🗹", + done: "☑", hoverPreviewWithoutCTRL: false, linkOpacity: 1, openInAdjacentPane: true, diff --git a/src/lang/locale/en.ts b/src/lang/locale/en.ts index 48c6c7b1..ad28ed3b 100644 --- a/src/lang/locale/en.ts +++ b/src/lang/locale/en.ts @@ -751,6 +751,9 @@ export default { DISPLAY_HEAD: "Excalidraw appearance and behavior", DISPLAY_DESC: "In the 'appearance and behavior' section of Excalidraw Settings, you can fine-tune how Excalidraw appears and behaves. This includes options for dynamic styling, left-handed mode, matching Excalidraw and Obsidian themes, default modes, and more.", + DISPLAY_EDITOR_PREVIEWS_HEAD: "Editing and previews", + DISPLAY_EDITOR_PREVIEWS_DESC: + "Configure canvas editing gestures and how Excalidraw files appear in reading mode and hover previews.", OVERRIDE_OBSIDIAN_FONT_SIZE_NAME: "Limit Obsidian Font Size to Editor Text", OVERRIDE_OBSIDIAN_FONT_SIZE_DESC: "Obsidian's custom font size setting affects the entire interface, including Excalidraw and themes that depend on the default font size. " + @@ -831,6 +834,8 @@ export default { }'>Markdown Reading Mode under 'Appearance and Behavior' further above.
` + `⚠️ You must close and reopen the Excalidraw/markdown file for changes to take effect. ⚠️`, MODES_HEAD: "UI Modes", + MODES_DESC: + "Choose device-specific Excalidraw interface layouts, title-bar controls, and left- or right-handed tray placement.", DESKTOP_UI_MODE_NAME: "Preferred Desktop Mode", DESKTOP_UI_MODE_DESC: "Select the default UI mode for desktop devices.", TABLET_UI_MODE_NAME: "Preferred Tablet Mode", @@ -843,12 +848,19 @@ export default { MODE_PHONE: "Phone-mode", REAPPLY_UI_MODE_BUTTON: "Reapply UI mode now", HOTKEY_OVERRIDE_HEAD: "Hotkey overrides", + HOTKEY_OVERRIDE_GROUP_DESC: + "Manage Excalidraw key combinations that should take priority over conflicting Obsidian hotkeys.", + HOTKEY_OVERRIDE_CONTROL_NAME: "Manage hotkey overrides", HOTKEY_OVERRIDE_DESC: `Some of the Excalidraw hotkeys such as ${labelCTRL()}+Enter to edit text or ${labelCTRL()}+K to create an element link ` + "conflict with Obsidian hotkey settings. The hotkey combinations you add below will override Obsidian's hotkey settings while using Excalidraw, thus " + `you can add ${labelCTRL()}+G if you want to default to Group Object in Excalidraw instead of opening Graph View.`, THEME_HEAD: "Theme and styling", + THEME_DESC: + "Control interface styling, drawing and embed themes, opening mode, and mobile safe-area spacing.", ZOOM_AND_PAN_HEAD: "Zoom and Pan", + ZOOM_AND_PAN_DESC: + "Configure mouse, touch, opening, resizing, and zoom-range behavior.", PAN_WITH_RIGHT_MOUSE_BUTTON_NAME: "Right-click drag to pan", PAN_WITH_RIGHT_MOUSE_BUTTON_DESC: "Right-click and drag to pan the canvas (Miro-style). Press 'm' to open the context menu.", @@ -881,7 +893,11 @@ export default { ZOOM_MAX_DESC: "Upper zoom limit. Default: 3000%. Usually no need to change; included for completeness.", PEN_HEAD: "Pen", + PEN_DESC: + "Configure automatic pen mode, touch gestures, the eraser, and the freedraw crosshair.", GRID_HEAD: "Grid", + GRID_DESC: + "Configure grid direction, automatic or custom color, and opacity.", GRID_DYNAMIC_COLOR_NAME: "Dynamic grid color", GRID_DYNAMIC_COLOR_DESC: "Toggle ON:Change grid color to match the canvas color
Toggle OFF:Use the color below as the grid color", @@ -895,6 +911,8 @@ export default { GRID_HORIZONTAL: "Render horizontal grid", GRID_VERTICAL: "Render vertical grid", LASER_HEAD: "Laser pointer", + LASER_DESC: + "Configure the laser pointer color and how quickly and how far its trail fades.", LASER_COLOR: "Laser pointer color", LASER_DECAY_TIME_NAME: "Laser pointer decay time", LASER_DECAY_TIME_DESC: @@ -914,6 +932,21 @@ export default { "When Obsidian files change, the matching [[link]] in your drawings will also change. " + "If you don't want text accidentally changing in your drawings use [[links|with aliases]].", DRAG_MODIFIER_NAME: "Link Click and Drag&Drop Modifier Keys", + DRAG_MODIFIER_GROUP_DESC: + "Configure link-opening gestures and platform-specific modifier combinations for clicks and drag-and-drop actions.", + LINK_OPENING_GESTURES_HEAD: "Link-opening gestures", + LINK_OPENING_GESTURES_DESC: + "Configure long-press delays and double-click link opening for embedded drawings and view mode.", + WEB_BROWSER_DRAG_ACTION_DESC: + "Choose modifier combinations for links, images, imports, and embeddables dragged from a web browser.", + LOCAL_FILE_DRAG_ACTION_DESC: + "Choose modifier combinations for links, images, imports, and embeddables dragged from the operating system.", + INTERNAL_DRAG_ACTION_DESC: + "Choose modifier combinations for links, images, full-size images, and embeddables dragged inside Obsidian.", + PANE_TARGET_DESC: + "Choose modifier combinations that determine where clicked links open.", + MODIFIER_KEY_USAGE_NAME: "Configuring modifier keys", + MODIFIER_KEY_COMBINATIONS: "Modifier combinations", DRAG_MODIFIER_DESC: `Modifier key behavior when clicking links and dragging and dropping elements. ` + `Excalidraw will not validate your configuration... pay attention to avoid conflicting settings. ` + @@ -1011,6 +1044,22 @@ export default { "Use the http" + "s://noembed" + ".com/embed?url= to get title of page when dropping an HTTPS link into Excalidraw", + LINK_BEHAVIOR_HEAD: "Link behavior", + LINK_BEHAVIOR_DESC: + "Configure link synchronization, related links, hover previews, click handling, and web-page title lookup.", + LINK_USAGE_NAME: "Using links in Excalidraw", + LINK_OPENING_HEAD: "Pane and tab behavior", + LINK_OPENING_DESC: + "Choose whether opened links reuse, focus, or move between panes, tabs, and the main workspace.", + LINK_APPEARANCE_HEAD: "Link appearance", + LINK_APPEARANCE_DESC: + "Configure brackets, prefixes, icons, and opacity used when links are displayed.", + TODO_HEAD: "TODOs", + TODO_GROUP_DESC: + "Configure TODO parsing and the icons used for open and completed tasks.", + TRANSCLUSION_HEAD: "Text transclusions", + TRANSCLUSION_DESC: + "Configure character limits, wrapping, and quote cleanup for transcluded Markdown text.", PDF_TO_IMAGE: "PDF to Image", PDF_TO_IMAGE_SCALE_NAME: "PDF to Image conversion scale", PDF_TO_IMAGE_SCALE_DESC: diff --git a/src/lang/locale/es.ts b/src/lang/locale/es.ts index 7281f082..e7d0c76c 100644 --- a/src/lang/locale/es.ts +++ b/src/lang/locale/es.ts @@ -724,6 +724,9 @@ export default { DISPLAY_HEAD: "Apariencia y Comportamiento de Excalidraw", DISPLAY_DESC: "En la sección 'Apariencia y Comportamiento' de la Configuración de Excalidraw, puedes ajustar cómo se ve y se comporta Excalidraw. Esto incluye opciones para estilos dinámicos, modo para zurdos, coincidencia de temas de Excalidraw y Obsidian, modos predeterminados y más.", + DISPLAY_EDITOR_PREVIEWS_HEAD: "Edición y vistas previas", + DISPLAY_EDITOR_PREVIEWS_DESC: + "Configura los gestos de edición del lienzo y cómo aparecen los archivos de Excalidraw en el modo de lectura y las vistas previas al pasar el cursor.", OVERRIDE_OBSIDIAN_FONT_SIZE_NAME: "Limitar tamaño de fuente de Obsidian al texto del editor", OVERRIDE_OBSIDIAN_FONT_SIZE_DESC: @@ -803,13 +806,22 @@ export default { }'>Modo de Lectura de Markdown en 'Apariencia y Comportamiento' más arriba.
` + `⚠️ Debes cerrar y volver a abrir el archivo de Excalidraw/Markdown para que los cambios surtan efecto. ⚠️`, MODES_HEAD: "Modos", + MODES_DESC: + "Elige diseños de interfaz específicos para cada dispositivo, controles de la barra de título y la posición de la bandeja para diestros o zurdos.", HOTKEY_OVERRIDE_HEAD: "Anulaciones de atajos de teclado", + HOTKEY_OVERRIDE_GROUP_DESC: + "Administra las combinaciones de Excalidraw que deben tener prioridad sobre los atajos de Obsidian en conflicto.", + HOTKEY_OVERRIDE_CONTROL_NAME: "Administrar anulaciones de atajos", HOTKEY_OVERRIDE_DESC: `Algunos de los atajos de teclado de Excalidraw, como ${labelCTRL()}+Enter para editar texto o ${labelCTRL()}+K para crear un enlace de elemento ` + "entran en conflicto con la configuración de atajos de teclado de Obsidian. Las combinaciones de atajos de teclado que agregues a continuación anularán la configuración de atajos de teclado de Obsidian mientras usas Excalidraw. Por lo tanto, " + `puedes agregar ${labelCTRL()}+G si quieres que el comportamiento predeterminado sea Agrupar Objeto en Excalidraw en lugar de abrir la Vista de Gráfico.`, THEME_HEAD: "Tema y estilo", + THEME_DESC: + "Controla el estilo de la interfaz, los temas de dibujos e incrustaciones, el modo de apertura y el espacio seguro en móviles.", ZOOM_AND_PAN_HEAD: "Zoom y panorámica", + ZOOM_AND_PAN_DESC: + "Configura el comportamiento del ratón, el tacto, la apertura, el cambio de tamaño y el intervalo de zoom.", PAN_WITH_RIGHT_MOUSE_BUTTON_NAME: "Desplazar el lienzo con el botón derecho del mouse (abrir menú con 'm')", PAN_WITH_RIGHT_MOUSE_BUTTON_DESC: @@ -843,7 +855,11 @@ export default { ZOOM_MAX_DESC: "Límite superior del zoom. Predeterminado: 3000%. Por lo general, no es necesario cambiarlo; se incluye para ser exhaustivos.", PEN_HEAD: "Lápiz", + PEN_DESC: + "Configura el modo lápiz automático, los gestos táctiles, el borrador y la cruz de dibujo libre.", GRID_HEAD: "Cuadrícula", + GRID_DESC: + "Configura la dirección de la cuadrícula, el color automático o personalizado y la opacidad.", GRID_DYNAMIC_COLOR_NAME: "Color de cuadrícula dinámica", GRID_DYNAMIC_COLOR_DESC: "Activado: Cambia el color de la cuadrícula para que coincida con el color del lienzo
Desactivado:[[enlaces|con alias]].", DRAG_MODIFIER_NAME: "Teclas modificadoras para click de enlace y Arrastrar y Soltar(Drag&Drop)", + DRAG_MODIFIER_GROUP_DESC: + "Configura gestos para abrir enlaces y combinaciones de modificadores para clics y acciones de arrastrar y soltar.", + LINK_OPENING_GESTURES_HEAD: "Gestos para abrir enlaces", + LINK_OPENING_GESTURES_DESC: + "Configura retrasos de pulsación prolongada y la apertura con doble clic en dibujos incrustados y el modo de vista.", + WEB_BROWSER_DRAG_ACTION_DESC: + "Elige modificadores para enlaces, imágenes, importaciones e incrustaciones arrastradas desde un navegador web.", + LOCAL_FILE_DRAG_ACTION_DESC: + "Elige modificadores para enlaces, imágenes, importaciones e incrustaciones arrastradas desde el sistema operativo.", + INTERNAL_DRAG_ACTION_DESC: + "Elige modificadores para enlaces, imágenes, imágenes a tamaño completo e incrustaciones arrastradas dentro de Obsidian.", + PANE_TARGET_DESC: + "Elige combinaciones de modificadores que determinan dónde se abren los enlaces.", + MODIFIER_KEY_USAGE_NAME: "Configurar teclas modificadoras", + MODIFIER_KEY_COMBINATIONS: "Combinaciones de modificadores", DRAG_MODIFIER_DESC: `Comportamiento de la tecla modificadora al hacer click en enlaces y arrastrar y soltar elementos. ` + `Excalidraw no validará tu configuración... presta atención para evitar configuraciones conflictivas. ` + @@ -976,6 +1009,22 @@ export default { "Usa http" + "s://noembed" + ".com/embed?url= para obtener el título de la página al soltar un enlace HTTPS en Excalidraw.", + LINK_BEHAVIOR_HEAD: "Comportamiento de enlaces", + LINK_BEHAVIOR_DESC: + "Configura la sincronización, enlaces relacionados, vistas previas, clics y la búsqueda de títulos web.", + LINK_USAGE_NAME: "Usar enlaces en Excalidraw", + LINK_OPENING_HEAD: "Comportamiento de paneles y pestañas", + LINK_OPENING_DESC: + "Elige si los enlaces reutilizan, enfocan o cambian entre paneles, pestañas y el espacio de trabajo principal.", + LINK_APPEARANCE_HEAD: "Apariencia de enlaces", + LINK_APPEARANCE_DESC: + "Configura corchetes, prefijos, iconos y opacidad al mostrar enlaces.", + TODO_HEAD: "Tareas pendientes", + TODO_GROUP_DESC: + "Configura el análisis de tareas y los iconos para tareas abiertas y completadas.", + TRANSCLUSION_HEAD: "Transclusiones de texto", + TRANSCLUSION_DESC: + "Configura límites de caracteres, ajuste de línea y limpieza de citas para texto Markdown transcluido.", PDF_TO_IMAGE: "PDF a Image", PDF_TO_IMAGE_SCALE_NAME: "Escala de conversión de PDF a imagen", PDF_TO_IMAGE_SCALE_DESC: diff --git a/src/lang/locale/ru.ts b/src/lang/locale/ru.ts index a90f3fa2..9173e66f 100644 --- a/src/lang/locale/ru.ts +++ b/src/lang/locale/ru.ts @@ -667,6 +667,9 @@ export default { DISPLAY_HEAD: "Внешний вид и поведение Excalidraw", DISPLAY_DESC: "В разделе 'Внешний вид и поведение' раздела Настройки Excalidraw вы можете настроить внешний вид и поведение Excalidraw. Сюда входят опции динамической стилизации, режима для левой руки, соответствия тем Excalidraw и Obsidian, режимов по умолчанию и многое другое.", + DISPLAY_EDITOR_PREVIEWS_HEAD: "Редактирование и предпросмотр", + DISPLAY_EDITOR_PREVIEWS_DESC: + "Настройте жесты редактирования холста и отображение файлов Excalidraw в режиме чтения и предпросмотре при наведении.", DYNAMICSTYLE_NAME: "Динамическая стилизация", DYNAMICSTYLE_DESC: "Изменение цветов пользовательского интерфейса Excalidraw в соответствии с цветом холста", @@ -729,13 +732,23 @@ export default { "
  • Если заблокировать, то в PDF будет отображаться разметка документа.
  • " + `См. другие связанные настройки для режима чтения разметки в разделе 'Внешний вид и поведение' выше.
    ` + "⚠️ Обратите внимание, что необходимо закрыть активный файл excalidraw/markdown и открыть его снова, чтобы изменения вступили в силу. ⚠️", + MODES_HEAD: "Режимы интерфейса", + MODES_DESC: + "Выберите интерфейс Excalidraw для каждого устройства, кнопки заголовка и расположение панели для правой или левой руки.", HOTKEY_OVERRIDE_HEAD: "Переопределение горячих клавиш", + HOTKEY_OVERRIDE_GROUP_DESC: + "Управляйте сочетаниями Excalidraw, которые должны иметь приоритет над конфликтующими горячими клавишами Obsidian.", + HOTKEY_OVERRIDE_CONTROL_NAME: "Управление переопределениями клавиш", HOTKEY_OVERRIDE_DESC: `Некоторые горячие клавиши Excalidraw, такие как ${labelCTRL()}+Enter для редактирования текста или ${labelCTRL()}+K создания ссылки на элемент ` + "конфликтуют с настройками горячих клавиш Obsidian. Комбинации горячих клавиш, которые вы добавите ниже, отменят настройки горячих клавиш Obsidian при использовании Excalidraw, таким образом " + `Вы можете добавить ${labelCTRL()}+G, если хотите по умолчанию перейти к Группе Объектов в Excalidraw вместо открытия Режима просмотра Графиков.`, THEME_HEAD: "Тема и стиль", + THEME_DESC: + "Настройте стиль интерфейса, темы рисунков и вставок, режим открытия и безопасные отступы на мобильных устройствах.", ZOOM_AND_PAN_HEAD: "Масштаб и панорамирование", + ZOOM_AND_PAN_DESC: + "Настройте поведение мыши, сенсорного ввода, открытия, изменения размера и диапазона масштаба.", PAN_WITH_RIGHT_MOUSE_BUTTON_NAME: "Перемещение холста правой кнопкой мыши (открыть меню с 'm')", PAN_WITH_RIGHT_MOUSE_BUTTON_DESC: @@ -760,7 +773,12 @@ export default { "Увеличение до максимального уровня масштабирования", ZOOM_TO_FIT_MAX_LEVEL_DESC: "Установите максимальный уровень, до которого масштабирование будет увеличивать чертеж. Минимальное значение - 0,5 (50 %), максимальное - 10 (1000 %).", + PEN_HEAD: "Перо", + PEN_DESC: + "Настройте автоматический режим пера, сенсорные жесты, ластик и перекрестие свободного рисования.", GRID_HEAD: "Сетка", + GRID_DESC: + "Настройте направление сетки, автоматический или пользовательский цвет и прозрачность.", GRID_DYNAMIC_COLOR_NAME: "Динамический цвет сетки", GRID_DYNAMIC_COLOR_DESC: "Переключатель ВКЛ:Измените цвет сетки, чтобы он соответствовал цвету холста
    Переключатель ВЫКЛ:Используйте цвет, указанный ниже, в качестве цвета сетки", @@ -770,6 +788,8 @@ export default { "Прозрачность сетки также будет управлять прозрачностью поля привязки при привязке стрелки к элементу.
    " + "Установите прозрачность сетки. 0 - прозрачная, 100 - непрозрачная.", LASER_HEAD: "Лазерный указатель", + LASER_DESC: + "Настройте цвет лазерного указателя, скорость и длину затухания его следа.", LASER_COLOR: "Цвет лазерного указателя", LASER_DECAY_TIME_NAME: "Время затухания лазерного указателя", LASER_DECAY_TIME_DESC: @@ -789,6 +809,21 @@ export default { "Когда файлы Obsidian изменяются, соответствующие [[link]] в ваших чертежах также изменится. " + "Если вы не хотите, чтобы текст случайно менялся в ваших чертежах, используйте [[links|with aliases]].", DRAG_MODIFIER_NAME: "Щелкните ссылку и перетащите клавиши-модификаторы", + DRAG_MODIFIER_GROUP_DESC: + "Настройте жесты открытия ссылок и платформенные сочетания модификаторов для щелчков и перетаскивания.", + LINK_OPENING_GESTURES_HEAD: "Жесты открытия ссылок", + LINK_OPENING_GESTURES_DESC: + "Настройте задержку долгого нажатия и открытие ссылок двойным щелчком во встроенных рисунках и режиме просмотра.", + WEB_BROWSER_DRAG_ACTION_DESC: + "Выберите модификаторы для ссылок, изображений, импорта и вставок, перетаскиваемых из веб-браузера.", + LOCAL_FILE_DRAG_ACTION_DESC: + "Выберите модификаторы для ссылок, изображений, импорта и вставок, перетаскиваемых из операционной системы.", + INTERNAL_DRAG_ACTION_DESC: + "Выберите модификаторы для ссылок, изображений, полноразмерных изображений и вставок внутри Obsidian.", + PANE_TARGET_DESC: + "Выберите сочетания модификаторов, определяющие место открытия ссылок.", + MODIFIER_KEY_USAGE_NAME: "Настройка клавиш-модификаторов", + MODIFIER_KEY_COMBINATIONS: "Сочетания модификаторов", DRAG_MODIFIER_DESC: `Поведение клавиши-модификатора при нажатии на ссылки и перетаскивании элементов. ` + `Excalidraw не будет проверять вашу конфигурацию... обратите внимание, чтобы избежать конфликтов настроек. ` + @@ -885,6 +920,22 @@ export default { "Используйте http" + "s://noembed" + ".com/embed?url= для получения заголовка страницы при переходе по HTTPS-ссылке в Excalidraw", + LINK_BEHAVIOR_HEAD: "Поведение ссылок", + LINK_BEHAVIOR_DESC: + "Настройте синхронизацию ссылок, связанные ссылки, предпросмотр, щелчки и получение заголовков веб-страниц.", + LINK_USAGE_NAME: "Использование ссылок в Excalidraw", + LINK_OPENING_HEAD: "Поведение панелей и вкладок", + LINK_OPENING_DESC: + "Выберите, будут ли ссылки повторно использовать, фокусировать или переключать панели, вкладки и главное рабочее пространство.", + LINK_APPEARANCE_HEAD: "Внешний вид ссылок", + LINK_APPEARANCE_DESC: + "Настройте скобки, префиксы, значки и прозрачность отображаемых ссылок.", + TODO_HEAD: "Задачи TODO", + TODO_GROUP_DESC: + "Настройте распознавание TODO и значки открытых и завершенных задач.", + TRANSCLUSION_HEAD: "Текстовые включения", + TRANSCLUSION_DESC: + "Настройте ограничения символов, перенос строк и очистку цитат для включенного текста Markdown.", PDF_TO_IMAGE: "PDF в изображение", PDF_TO_IMAGE_SCALE_NAME: "Шкала преобразования PDF в изображения", PDF_TO_IMAGE_SCALE_DESC: diff --git a/src/lang/locale/zh-cn.ts b/src/lang/locale/zh-cn.ts index 1bca239c..60452296 100644 --- a/src/lang/locale/zh-cn.ts +++ b/src/lang/locale/zh-cn.ts @@ -680,6 +680,9 @@ export default { DISPLAY_HEAD: "界面 & 行为", DISPLAY_DESC: "包括:左手模式、动态样式、匹配 Excalidraw 和 Obsidian 主题、默认运行模式等。", + DISPLAY_EDITOR_PREVIEWS_HEAD: "编辑与预览", + DISPLAY_EDITOR_PREVIEWS_DESC: + "配置画布编辑手势,以及 Excalidraw 文件在阅读模式和悬停预览中的显示方式。", OVERRIDE_OBSIDIAN_FONT_SIZE_NAME: "限制 Obsidian 字体大小为编辑器文本", OVERRIDE_OBSIDIAN_FONT_SIZE_DESC: "Obsidian 的自定义字体大小设置会影响整个界面,包括 Excalidraw 和依赖默认字体大小的主题。" + @@ -754,6 +757,8 @@ export default { `请参阅下方 PDF 导出设置。
    ` + `⚠️ 关闭并重新打开 Excalidraw/Markdown 文件后生效。`, MODES_HEAD: "UI 模式", + MODES_DESC: + "选择不同设备的 Excalidraw 界面布局、标题栏控件和左右手托盘位置。", DESKTOP_UI_MODE_NAME: "桌面端偏好模式", DESKTOP_UI_MODE_DESC: "桌面端设备默认 UI 模式。", TABLET_UI_MODE_NAME: "平板端偏好模式", @@ -766,12 +771,19 @@ export default { MODE_PHONE: "Phone-mode", REAPPLY_UI_MODE_BUTTON: "重新应用 UI 模式", HOTKEY_OVERRIDE_HEAD: "热键覆盖", + HOTKEY_OVERRIDE_GROUP_DESC: + "管理应优先于冲突 Obsidian 热键的 Excalidraw 按键组合。", + HOTKEY_OVERRIDE_CONTROL_NAME: "管理热键覆盖", HOTKEY_OVERRIDE_DESC: `一些 Excalidraw 的热键,如 ${labelCTRL()}+Enter 用于编辑文本,或 ${labelCTRL()}+K 用于创建元素链接,` + "与 Obsidian 的热键设置冲突。您在下面添加的热键组合将在使用 Excalidraw 时覆盖 Obsidian 的热键设置," + `因此如果您希望在 Excalidraw 中默认“编组”,而不是“查看关系图谱”(核心插件 - 关系图谱),您可以添加 ${labelCTRL()}+G。`, THEME_HEAD: "主题和样式", + THEME_DESC: + "控制界面样式、绘图和嵌入主题、打开模式以及移动设备安全区域间距。", ZOOM_AND_PAN_HEAD: "缩放和平移", + ZOOM_AND_PAN_DESC: + "配置鼠标、触控、打开、调整大小和缩放范围行为。", PAN_WITH_RIGHT_MOUSE_BUTTON_NAME: "右键拖动平移", PAN_WITH_RIGHT_MOUSE_BUTTON_DESC: "右键点击并拖动来平移绘图(和在线白板工具 Miro 类似)。按 'm' 键打开上下文菜单。", @@ -804,7 +816,9 @@ export default { ZOOM_MAX_DESC: "绘图放大的极限。默认:3000%。通常无需修改,考虑完整性而提供。", PEN_HEAD: "手写笔", + PEN_DESC: "配置自动手写笔模式、触控手势、橡皮擦和自由绘制十字线。", GRID_HEAD: "网格", + GRID_DESC: "配置网格方向、自动或自定义颜色以及不透明度。", GRID_DYNAMIC_COLOR_NAME: "动态网格颜色", GRID_DYNAMIC_COLOR_DESC: "开启:更改网格颜色以匹配绘图颜色。
    关闭:将以下颜色用作网格颜色。", @@ -817,6 +831,7 @@ export default { GRID_HORIZONTAL: "渲染水平网格", GRID_VERTICAL: "渲染垂直网格", LASER_HEAD: "激光笔工具(更多工具 > 激光笔)", + LASER_DESC: "配置激光笔颜色及其轨迹淡出的速度和长度。", LASER_COLOR: "激光笔颜色", LASER_DECAY_TIME_NAME: "激光笔消失时间", LASER_DECAY_TIME_DESC: "单位是毫秒,默认 1000(即 1 秒)。", @@ -835,6 +850,20 @@ export default { "链接的源文件被重命名时,绘图中相应的 [[内部链接]] 也会同步更新。" + "若您不愿绘图中的链接外观因此而变化,可使用 [[内部链接|别名]]。", DRAG_MODIFIER_NAME: "修饰键", + DRAG_MODIFIER_GROUP_DESC: + "配置链接打开手势,以及点击和拖放操作的平台特定修饰键组合。", + LINK_OPENING_GESTURES_HEAD: "链接打开手势", + LINK_OPENING_GESTURES_DESC: + "配置嵌入绘图和查看模式中的长按延迟与双击打开链接。", + WEB_BROWSER_DRAG_ACTION_DESC: + "选择从网页浏览器拖入链接、图片、导入项和嵌入内容时的修饰键组合。", + LOCAL_FILE_DRAG_ACTION_DESC: + "选择从操作系统拖入链接、图片、导入项和嵌入内容时的修饰键组合。", + INTERNAL_DRAG_ACTION_DESC: + "选择在 Obsidian 内拖动链接、图片、全尺寸图片和嵌入内容时的修饰键组合。", + PANE_TARGET_DESC: "选择决定点击链接打开位置的修饰键组合。", + MODIFIER_KEY_USAGE_NAME: "配置修饰键", + MODIFIER_KEY_COMBINATIONS: "修饰键组合", DRAG_MODIFIER_DESC: `在您按住点击链接或拖动元素时,可以触发某些行为。您可以为这些行为添加修饰键。` + `Excalidraw 不会检查您的设置是否合理,因此请谨慎设置,避免冲突。` + @@ -930,6 +959,20 @@ export default { "拖动链接到 Excalidraw 时,使用 http" + "s://noembed" + ".com/embed?url= 来获取 HTTPS 页面标题。", + LINK_BEHAVIOR_HEAD: "链接行为", + LINK_BEHAVIOR_DESC: + "配置链接同步、相关链接、悬停预览、点击处理和网页标题查询。", + LINK_USAGE_NAME: "在 Excalidraw 中使用链接", + LINK_OPENING_HEAD: "窗格和标签页行为", + LINK_OPENING_DESC: + "选择链接是否复用、聚焦或切换窗格、标签页和主工作区。", + LINK_APPEARANCE_HEAD: "链接外观", + LINK_APPEARANCE_DESC: "配置链接显示时使用的括号、前缀、图标和不透明度。", + TODO_HEAD: "待办事项", + TODO_GROUP_DESC: "配置待办事项解析以及未完成和已完成任务使用的图标。", + TRANSCLUSION_HEAD: "文本嵌入", + TRANSCLUSION_DESC: + "配置嵌入 Markdown 文本的字符限制、换行和引用符号清理。", PDF_TO_IMAGE: "以图像形式嵌入到绘图中的 PDF", PDF_TO_IMAGE_SCALE_NAME: "分辨率", PDF_TO_IMAGE_SCALE_DESC: diff --git a/src/lang/locale/zh-tw.ts b/src/lang/locale/zh-tw.ts index d7fdb13a..98d65000 100644 --- a/src/lang/locale/zh-tw.ts +++ b/src/lang/locale/zh-tw.ts @@ -680,6 +680,9 @@ export default { DISPLAY_HEAD: "介面 & 行為", DISPLAY_DESC: "包括:左手模式、動態樣式、匹配 Excalidraw 和 Obsidian 主題、預設執行模式等。", + DISPLAY_EDITOR_PREVIEWS_HEAD: "編輯與預覽", + DISPLAY_EDITOR_PREVIEWS_DESC: + "設定畫布編輯手勢,以及 Excalidraw 檔案在閱讀模式和懸停預覽中的顯示方式。", OVERRIDE_OBSIDIAN_FONT_SIZE_NAME: "限制 Obsidian 字型大小為編輯器文字", OVERRIDE_OBSIDIAN_FONT_SIZE_DESC: "Obsidian 的自定義字型大小設定會影響整個介面,包括 Excalidraw 和依賴預設字型大小的主題。" + @@ -754,6 +757,8 @@ export default { `請參閱下方 PDF 匯出設定。
    ` + `⚠️ 關閉並重新開啟 Excalidraw/Markdown 檔案後生效。`, MODES_HEAD: "UI 模式", + MODES_DESC: + "選擇不同裝置的 Excalidraw 介面配置、標題列控制項和左右手托盤位置。", DESKTOP_UI_MODE_NAME: "桌面端偏好模式", DESKTOP_UI_MODE_DESC: "桌面端裝置預設 UI 模式。", TABLET_UI_MODE_NAME: "平板端偏好模式", @@ -766,12 +771,19 @@ export default { MODE_PHONE: "Phone-mode", REAPPLY_UI_MODE_BUTTON: "重新應用 UI 模式", HOTKEY_OVERRIDE_HEAD: "熱鍵覆蓋", + HOTKEY_OVERRIDE_GROUP_DESC: + "管理應優先於衝突 Obsidian 熱鍵的 Excalidraw 按鍵組合。", + HOTKEY_OVERRIDE_CONTROL_NAME: "管理熱鍵覆蓋", HOTKEY_OVERRIDE_DESC: `一些 Excalidraw 的熱鍵,如 ${labelCTRL()}+Enter 用於編輯文字,或 ${labelCTRL()}+K 用於建立元素連結,` + "與 Obsidian 的熱鍵設定衝突。您在下面新增的熱鍵組合將在使用 Excalidraw 時覆蓋 Obsidian 的熱鍵設定," + `因此如果您希望在 Excalidraw 中預設“編組”,而不是“檢視關係圖譜”(核心外掛 - 關係圖譜),您可以新增 ${labelCTRL()}+G。`, THEME_HEAD: "主題和樣式", + THEME_DESC: + "控制介面樣式、繪圖和嵌入主題、開啟模式以及行動裝置安全區域間距。", ZOOM_AND_PAN_HEAD: "縮放和平移", + ZOOM_AND_PAN_DESC: + "設定滑鼠、觸控、開啟、調整大小和縮放範圍行為。", PAN_WITH_RIGHT_MOUSE_BUTTON_NAME: "右鍵拖動平移", PAN_WITH_RIGHT_MOUSE_BUTTON_DESC: "右鍵點選並拖動來平移繪圖(和線上白板工具 Miro 類似)。按 'm' 鍵開啟上下文選單。", @@ -804,7 +816,9 @@ export default { ZOOM_MAX_DESC: "繪圖放大的極限。預設:3000%。通常無需修改,考慮完整性而提供。", PEN_HEAD: "手寫筆", + PEN_DESC: "設定自動手寫筆模式、觸控手勢、橡皮擦和自由繪製十字線。", GRID_HEAD: "網格", + GRID_DESC: "設定網格方向、自動或自訂顏色以及不透明度。", GRID_DYNAMIC_COLOR_NAME: "動態網格顏色", GRID_DYNAMIC_COLOR_DESC: "開啟:更改網格顏色以匹配繪圖顏色。
    關閉:將以下顏色用作網格顏色。", @@ -817,6 +831,7 @@ export default { GRID_HORIZONTAL: "渲染水平網格", GRID_VERTICAL: "渲染垂直網格", LASER_HEAD: "雷射筆工具(更多工具 > 雷射筆)", + LASER_DESC: "設定雷射筆顏色及其軌跡淡出的速度和長度。", LASER_COLOR: "雷射筆顏色", LASER_DECAY_TIME_NAME: "雷射筆消失時間", LASER_DECAY_TIME_DESC: "單位是毫秒,預設 1000(即 1 秒)。", @@ -835,6 +850,20 @@ export default { "連結的原始檔被重新命名時,繪圖中相應的 [[內部連結]] 也會同步更新。" + "若您不願繪圖中的連結外觀因此而變化,可使用 [[內部連結|別名]]。", DRAG_MODIFIER_NAME: "修飾鍵", + DRAG_MODIFIER_GROUP_DESC: + "設定連結開啟手勢,以及點擊和拖放操作的平台特定修飾鍵組合。", + LINK_OPENING_GESTURES_HEAD: "連結開啟手勢", + LINK_OPENING_GESTURES_DESC: + "設定嵌入繪圖和檢視模式中的長按延遲與雙擊開啟連結。", + WEB_BROWSER_DRAG_ACTION_DESC: + "選擇從網頁瀏覽器拖入連結、圖片、匯入項目和嵌入內容時的修飾鍵組合。", + LOCAL_FILE_DRAG_ACTION_DESC: + "選擇從作業系統拖入連結、圖片、匯入項目和嵌入內容時的修飾鍵組合。", + INTERNAL_DRAG_ACTION_DESC: + "選擇在 Obsidian 內拖動連結、圖片、完整尺寸圖片和嵌入內容時的修飾鍵組合。", + PANE_TARGET_DESC: "選擇決定點擊連結開啟位置的修飾鍵組合。", + MODIFIER_KEY_USAGE_NAME: "設定修飾鍵", + MODIFIER_KEY_COMBINATIONS: "修飾鍵組合", DRAG_MODIFIER_DESC: `在您按住點選連結或拖動元素時,可以觸發某些行為。您可以為這些行為新增修飾鍵。` + `Excalidraw 不會檢查您的設定是否合理,因此請謹慎設定,避免衝突。` + @@ -930,6 +959,20 @@ export default { "拖動連結到 Excalidraw 時,使用 http" + "s://noembed" + ".com/embed?url= 來獲取 HTTPS 頁面標題。", + LINK_BEHAVIOR_HEAD: "連結行為", + LINK_BEHAVIOR_DESC: + "設定連結同步、相關連結、懸停預覽、點擊處理和網頁標題查詢。", + LINK_USAGE_NAME: "在 Excalidraw 中使用連結", + LINK_OPENING_HEAD: "窗格和分頁行為", + LINK_OPENING_DESC: + "選擇連結是否重複使用、聚焦或切換窗格、分頁和主要工作區。", + LINK_APPEARANCE_HEAD: "連結外觀", + LINK_APPEARANCE_DESC: "設定連結顯示時使用的括號、前綴、圖示和不透明度。", + TODO_HEAD: "待辦事項", + TODO_GROUP_DESC: "設定待辦事項解析以及未完成和已完成任務使用的圖示。", + TRANSCLUSION_HEAD: "文字嵌入", + TRANSCLUSION_DESC: + "設定嵌入 Markdown 文字的字元限制、換行和引用符號清理。", PDF_TO_IMAGE: "以影像形式嵌入到繪圖中的 PDF", PDF_TO_IMAGE_SCALE_NAME: "解析度", PDF_TO_IMAGE_SCALE_DESC: diff --git a/src/shared/Dialogs/Messages.ts b/src/shared/Dialogs/Messages.ts index ac44160b..78e00e97 100644 --- a/src/shared/Dialogs/Messages.ts +++ b/src/shared/Dialogs/Messages.ts @@ -29,6 +29,7 @@ I build this plugin as a labor of love. Curious about the philosophy behind it? ## Fixed - Rapid text editing in Excalidraw settings no longer loses focus or collapses the active section. Settings writes are coalesced and serialized. Excalidraw now keeps a device-local last-known-good recovery copy: corrupted synchronized settings are rejected and repaired from memory while running, or restored automatically from recovery at startup. If the settings file is deliberately removed, Excalidraw asks whether to restore that backup or reset to factory defaults. +- Changing a rendering-related Excalidraw setting no longer resets the live scroll and zoom position in open drawings. The default completed-TODO marker for new configurations is now ☑. - The Excalidraw color palette now uses its natural height when space is available instead of being unnecessarily limited to a short, vertically scrolling panel. Its native color control also remains aligned with the hex input. - The text-to-diagram chat history menu is visible again, allowing saved chats to be restored and deleted. - Stencil library is persisted with tab-indented JSON to support Git diffs. [#2883](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2883) diff --git a/src/shared/Dialogs/ModifierKeySettings.ts b/src/shared/Dialogs/ModifierKeySettings.ts index dd04df7d..5966c6b7 100644 --- a/src/shared/Dialogs/ModifierKeySettings.ts +++ b/src/shared/Dialogs/ModifierKeySettings.ts @@ -8,17 +8,26 @@ import { } from "src/utils/modifierkeyHelper"; import { setStyle } from "src/utils/styleUtils"; -type ModifierKeyCategories = Partial<{ - [modifierSetType in ModifierSetType]: string; -}>; - -const CATEGORIES: ModifierKeyCategories = { +const CATEGORIES: Record = { WebBrowserDragAction: t("WEB_BROWSER_DRAG_ACTION"), LocalFileDragAction: t("LOCAL_FILE_DRAG_ACTION"), InternalDragAction: t("INTERNAL_DRAG_ACTION"), LinkClickAction: t("PANE_TARGET"), }; +/** Modifier-key categories rendered by the settings component. */ +export const MODIFIER_KEY_CATEGORIES = [ + "WebBrowserDragAction", + "LocalFileDragAction", + "InternalDragAction", + "LinkClickAction", +] as const satisfies readonly ModifierSetType[]; + +/** Returns the localized heading for one modifier-key category. */ +export const getModifierKeyCategoryName = ( + modifierSetType: ModifierSetType, +): string => CATEGORIES[modifierSetType]; + export class ModifierKeySettingsComponent { private isMacOS: boolean; @@ -28,12 +37,22 @@ export class ModifierKeySettingsComponent { Mac: Record; Win: Record; }, - private update?: () => void, + private update: () => void, ) { this.isMacOS = DEVICE.isMacOS || DEVICE.isIOS; } - render() { + render(): void { + MODIFIER_KEY_CATEGORIES.forEach((modifierSetType) => + this.renderCategory(modifierSetType, true), + ); + } + + /** Renders one modifier-key category, optionally with its legacy fold. */ + renderCategory( + modifierSetType: ModifierSetType, + includeSummary: boolean, + ): void { const platform = this.isMacOS ? "Mac" : "Win"; const modifierKeysConfig = this.modifierKeyConfig[platform]; const tooltipMessages = modifierKeyTooltipMessages() as Record< @@ -41,102 +60,104 @@ export class ModifierKeySettingsComponent { Record >; - Object.entries(CATEGORIES).forEach(([modifierSetType, label]) => { - const detailsEl = this.contentEl.createEl("details"); + const detailsEl = includeSummary + ? this.contentEl.createEl("details") + : this.contentEl; + if (includeSummary) { detailsEl.createEl("summary", { - text: label, + text: getModifierKeyCategoryName(modifierSetType), cls: "excalidraw-setting-h4", }); + } - const modifierKeys = modifierKeysConfig[modifierSetType]; - detailsEl.createDiv({ - text: - t("DEFAULT_ACTION_DESC") + - (tooltipMessages[modifierSetType]?.[modifierKeys.defaultAction] ?? - ""), - cls: "setting-item-description", - }); - // Ensure all LinkClickAction rules have ctrl_cmd enabled - if (modifierSetType === "LinkClickAction") { - let dirty = false; - modifierKeys.rules.forEach((rule) => { - if (!rule.ctrl_cmd) { - rule.ctrl_cmd = true; - dirty = true; - } - }); - if (dirty) { - this.update?.(); + const modifierKeys = modifierKeysConfig[modifierSetType]; + detailsEl.createDiv({ + text: + t("DEFAULT_ACTION_DESC") + + (tooltipMessages[modifierSetType]?.[modifierKeys.defaultAction] ?? + ""), + cls: "setting-item-description", + }); + // Ensure all LinkClickAction rules have ctrl_cmd enabled + if (modifierSetType === "LinkClickAction") { + let dirty = false; + modifierKeys.rules.forEach((rule) => { + if (!rule.ctrl_cmd) { + rule.ctrl_cmd = true; + dirty = true; } + }); + if (dirty) { + this.update(); } + } - // Column header row - const headerSetting = new Setting(detailsEl); - headerSetting.settingEl.addClass("modifier-key-header-row"); - headerSetting.infoEl.remove(); - [ - "SHIFT", - this.isMacOS ? "CMD" : "CTRL", - this.isMacOS ? "OPT" : "ALT", - this.isMacOS ? "CTRL" : "META", - ].forEach((key) => { - headerSetting.controlEl.createSpan({ - text: key, - cls: "modifier-key-col-header", - }); + // Column header row + const headerSetting = new Setting(detailsEl); + headerSetting.settingEl.addClass("modifier-key-header-row"); + headerSetting.infoEl.remove(); + [ + "SHIFT", + this.isMacOS ? "CMD" : "CTRL", + this.isMacOS ? "OPT" : "ALT", + this.isMacOS ? "CTRL" : "META", + ].forEach((key) => { + headerSetting.controlEl.createSpan({ + text: key, + cls: "modifier-key-col-header", + }); + }); + + modifierKeys.rules.forEach((rule) => { + const setting = new Setting(detailsEl).setName( + tooltipMessages[modifierSetType]?.[rule.result], + ); + + setting.addToggle((toggle) => + toggle + .setValue(rule.shift) + .setTooltip("SHIFT") + .onChange((value) => { + rule.shift = value; + this.update(); + }), + ); + setting.addToggle((toggle) => { + const isLinkClick = modifierSetType === "LinkClickAction"; + toggle + .setValue(isLinkClick ? true : rule.ctrl_cmd) + .setTooltip(this.isMacOS ? "CMD" : "CTRL") + .onChange((value) => { + rule.ctrl_cmd = value; + this.update(); + }); + if (isLinkClick || this.isMacOS) { + // CMD is always required for link-click actions (Excalidraw detects + // the click via CMD being held). On macOS, CMD is also reserved for + // non-link-click actions. + toggle.setDisabled(true); + setStyle(toggle.toggleEl, { opacity: "0.5" }); + } }); - Object.entries(modifierKeys.rules).forEach(([_, rule]) => { - const setting = new Setting(detailsEl).setName( - tooltipMessages[modifierSetType]?.[rule.result], - ); - - setting.addToggle((toggle) => - toggle - .setValue(rule.shift) - .setTooltip("SHIFT") - .onChange((value) => { - rule.shift = value; - this.update(); - }), - ); - setting.addToggle((toggle) => { - const isLinkClick = modifierSetType === "LinkClickAction"; - toggle - .setValue(isLinkClick ? true : rule.ctrl_cmd) - .setTooltip(this.isMacOS ? "CMD" : "CTRL") - .onChange((value) => { - rule.ctrl_cmd = value; - this.update(); - }); - if (isLinkClick || this.isMacOS) { - // CMD is always required for link-click actions (Excalidraw detects - // the click via CMD being held). On macOS, CMD is also reserved for - // non-link-click actions. - toggle.setDisabled(true); - setStyle(toggle.toggleEl, { opacity: "0.5" }); - } - }); - - setting.addToggle((toggle) => - toggle - .setValue(rule.alt_opt) - .setTooltip(this.isMacOS ? "OPT" : "ALT") - .onChange((value) => { - rule.alt_opt = value; - this.update(); - }), - ); - setting.addToggle((toggle) => - toggle - .setValue(rule.meta_ctrl) - .setTooltip(this.isMacOS ? "CTRL" : "META") - .onChange((value) => { - rule.meta_ctrl = value; - this.update(); - }), - ); - }); + setting.addToggle((toggle) => + toggle + .setValue(rule.alt_opt) + .setTooltip(this.isMacOS ? "OPT" : "ALT") + .onChange((value) => { + rule.alt_opt = value; + this.update(); + }), + ); + setting.addToggle((toggle) => + toggle + .setValue(rule.meta_ctrl) + .setTooltip(this.isMacOS ? "CTRL" : "META") + .onChange((value) => { + rule.meta_ctrl = value; + this.update(); + }), + ); }); } } diff --git a/src/view/ExcalidrawView.ts b/src/view/ExcalidrawView.ts index 617d8b11..c596a70c 100644 --- a/src/view/ExcalidrawView.ts +++ b/src/view/ExcalidrawView.ts @@ -2171,16 +2171,26 @@ export default class ExcalidrawView } /** - * reload is triggered by the modifyEventHandler in main.ts whenever an excalidraw drawing that is currently open - * in a workspace leaf is modified. There can be two reasons for the file change: - * - The user saves the drawing in the active view (either force-save or autosave) - * - The file is modified by some other process, typically as a result of background sync, or because the drawing is open - * side by side, e.g. the canvas in one view and markdown view in the other. - * @param fullreload - * @param file - * @returns + * Reloads scene content after a rendering-related plugin setting changes, + * while retaining the live viewport that is intentionally not persisted as + * an ordinary drawing edit. */ - public async reload(fullreload: boolean = false, file?: TFile) { + public async reloadAfterSettingsChange(): Promise { + await this.reload(true, undefined, true); + } + + /** + * Reloads an open drawing after a local save or an external file change. + * + * @param fullreload - Whether to parse the complete drawing data again. + * @param file - Modified file when the reload originated from a file event. + * @param preserveViewport - Whether to retain live scroll and zoom values. + */ + public async reload( + fullreload: boolean = false, + file?: TFile, + preserveViewport: boolean = false, + ) { const loadOnModifyTrigger = file && file === this.file; //once you've finished editing the embeddable, the first time the file @@ -2229,7 +2239,12 @@ export default class ExcalidrawView await this.excalidrawData.setTextMode(this.textMode); } this.excalidrawData.scene.appState.theme = api.getAppState().theme; - await this.loadDrawing(loadOnModifyTrigger, undefined, true); + await this.loadDrawing( + loadOnModifyTrigger, + undefined, + true, + preserveViewport, + ); this.clearDirty(); } @@ -3052,17 +3067,30 @@ export default class ExcalidrawView } /** + * Loads the parsed scene into the Excalidraw runtime. * - * @param justloaded - a flag to trigger zoom to fit after the drawing has been loaded + * @param justloaded - Whether to trigger initial-load behavior such as zoom to fit. + * @param deletedElements - Deleted elements retained during save-related reloads. + * @param isReloading - Whether this replaces an already loaded scene. + * @param preserveViewport - Whether to omit persisted scroll and zoom state. */ public async loadDrawing( justloaded: boolean, deletedElements?: ExcalidrawElement[], isReloading: boolean = false, + preserveViewport: boolean = false, ) { const excalidrawData = this.excalidrawData.scene; const isOpenInMultipleLeaves = getExcalidraAndMarkdowViewsForFile(this.app, this.file).length > 1; + const appState = + isReloading && (isOpenInMultipleLeaves || preserveViewport) + ? deleteAppStateKeys(excalidrawData.appState as AppState, [ + "scrollX", + "scrollY", + "zoom", + ]) + : excalidrawData.appState; this.semaphores.justLoaded = justloaded; this.clearDirty(); const om = this.excalidrawData.getOpenMode(); @@ -3091,13 +3119,7 @@ export default class ExcalidrawView this.updateScene({ //elements: excalidrawData.elements.concat(deletedElements??[]), //need to preserve deleted elements during autosave if images, links, etc. are updated appState: { - ...(isReloading && isOpenInMultipleLeaves - ? deleteAppStateKeys(excalidrawData.appState as AppState, [ - "scrollX", - "scrollY", - "zoom", - ]) - : excalidrawData.appState), + ...appState, ...(this.excalidrawData.selectedElementIds //https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/609 ? this.excalidrawData.selectedElementIds : {}), @@ -3146,13 +3168,7 @@ export default class ExcalidrawView await this.instantiateExcalidraw({ elements: excalidrawData.elements, appState: { - ...(isReloading && isOpenInMultipleLeaves - ? deleteAppStateKeys(excalidrawData.appState as AppState, [ - "scrollX", - "scrollY", - "zoom", - ]) - : excalidrawData.appState), + ...appState, ...(excalidrawData.appState.frameRendering && excalidrawData.appState.frameRendering.markerName === undefined ? { diff --git a/styles.css b/styles.css index 5aa36d2f..7830fc2e 100644 --- a/styles.css +++ b/styles.css @@ -1615,7 +1615,7 @@ button.excalidraw-font-picker { overflow-y: auto; } -.excalidraw-settings .setting-item.excalidraw-declarative-full-width { +.setting-item.excalidraw-declarative-full-width { display: block; width: 100%; }