diff --git a/docs/plugin-sdk/API_REFERENCE.md b/docs/plugin-sdk/API_REFERENCE.md index 47c2ddabf3..a290c52993 100644 --- a/docs/plugin-sdk/API_REFERENCE.md +++ b/docs/plugin-sdk/API_REFERENCE.md @@ -6101,8 +6101,11 @@ async function scheduleReminder(title, body, dateTime) { | `visibleWhen` | לא | מגרסה 0.9.98.3. `"always"` (ברירת מחדל): הכפתור תמיד מוצג. `"nonEmptyText"`: מוצג רק כשיש טקסט בשדה (רווחים נחשבים לטקסט), כמו כפתור הניקוי; כפתור שיש לו סשן פתוח נשאר מוצג גם כשהשדה התרוקן. | | `mode` | לא | מגרסה 0.9.98.3. `"session"` (ברירת מחדל): סשן והאירוע `search.fieldAction.invoked`. `"providerBooksFilter"`: סינון מקור הספרים באיתור הספרים, ראו להלן. | | `libraryOnlyIcon` | לא | מגרסה 0.9.98.3, רק עם `mode: "providerBooksFilter"`: האייקון במצב "ספרי הספרייה בלבד". בלעדיו משמש `icon`. | +| `when` | לא | מגרסה 0.9.99. תנאי [`when`](#when--תרומה-תלוית-הגדרה) על הגדרה או על ערך אחסון של התוסף. הכפתור מוצג רק כשהתנאי מתקיים, ומופיע/נעלם מיד כשהערך משתנה, בלי להעיר את מנוע התוסף. חל על שני המצבים (`session` ו-`providerBooksFilter`) ומצטרף ל-`visibleWhen` ול-`fields`: כל התנאים חייבים להתקיים. | -עד 2 כפתורים לתוסף, ועד 3 כפתורים של תוספים בשדה אחד. +עד 2 כפתורים לתוסף, ועד 3 כפתורים של תוספים בשדה אחד. המכסות סופרות כפתורים +**רשומים**, לא רק מוצגים: כפתור שה-`when` שלו כבוי עדיין תופס מקום במכסה, כך +שהפעלה של הגדרה לא דוחקת החוצה כפתור של תוסף אחר. השדות הנתמכים: @@ -6182,7 +6185,8 @@ Otzaria.on('search.fieldAction.ended', ({ sessionId, reason }) => { /* ניקו **זיהוי תמיכה.** בגרסה ללא התכונה הכפתור לא יוצג, ו-`search.setFieldText` מחזיר `error.unknown_method`. הכפתור עצמו דורש `minAppVersion: "0.9.98.1"`, אבל המפתחות שנוספו מגרסה 0.9.98.3 (`visibleWhen`, `mode`, `libraryOnlyIcon`, וגם `persist` -ו-`type: "switch"` ב-`searchDialogItems`) דורשים `minAppVersion: "0.9.98.3"`: +ו-`type: "switch"` ב-`searchDialogItems`) דורשים `minAppVersion: "0.9.98.3"`, +ו-`when` דורש `minAppVersion: "0.9.99"`: מארח ישן יותר דוחה את המניפסט על מפתח לא מוכר, ולא מתעלם ממנו. ### מהדורות מקבילות חיצוניות (externalEditions) @@ -6508,7 +6512,7 @@ UTF-8 תקין, מציגה הודעה כללית; הצלחה בלי `message` ר ### when — תרומה תלוית-הגדרה -מ-`minAppVersion: 0.9.97`. כל פריט ב-`toolbarItems`, `contextMenuItems` ו-`searchDialogItems`, וכן כל איבר ב-`activationEvents`, יכול לשאת אובייקט `when`. הפריט נרשם תמיד; הוא מוצג רק כשהתנאי מתקיים, ומופיע/נעלם מיד כשהערך משתנה — בלי לטעון את מנוע ה-JS של התוסף. +מ-`minAppVersion: 0.9.97`. כל פריט ב-`toolbarItems`, `contextMenuItems` ו-`searchDialogItems`, וכן כל איבר ב-`activationEvents`, יכול לשאת אובייקט `when`. כפתור ב-`searchFieldActions` יכול לשאת אותו מ-`minAppVersion: 0.9.99`. הפריט נרשם תמיד; הוא מוצג רק כשהתנאי מתקיים, ומופיע/נעלם מיד כשהערך משתנה — בלי לטעון את מנוע ה-JS של התוסף. > אל תבלבלו עם ה-`when` של `startup.programs` — שם זו סכימה אחרת לגמרי (`{op, value}`) שמחליטה אם התכנית בכלל רצה. ה-`when` שמתואר כאן חל על תרומות, ומבנהו `setting`/`storage`. diff --git a/docs/plugin-sdk/README.md b/docs/plugin-sdk/README.md index 7567ec4052..269f886f73 100644 --- a/docs/plugin-sdk/README.md +++ b/docs/plugin-sdk/README.md @@ -177,7 +177,7 @@ my-plugin/ | `contributes.startup` | `null` | פקדים, פריטי תפריט ונתונים שאוצריא טוענת ישירות מהמניפסט בלי להפעיל WebView. | | `contributes.startup.programs` | `[]` | תכניות חישוב Host מוולדות, ללא JavaScript; ראו `API_REFERENCE.md` §תכניות Host ללא WebView. | | `contributes.startup.searchDialogItems` | `[]` | שורות סטטיות, `checkbox` או `switch` (מגרסה 0.9.98.3); `persist: false` הופך בחירה לחד-פעמית (מגרסה 0.9.98.3); `openPluginOnSubmit` יכול לנתב את אישור החיפוש לתוסף, ו-`resultsAction` (מגרסה 0.9.98.3) מוסיף כפתור בטאב החיפוש שמעביר אליו את החיפוש אחרי שהסתיים. | -| `contributes.startup.searchFieldActions` | `[]` | כפתורים בתוך שדות החיפוש (מגרסה 0.9.98.1). לחיצה פותחת סשן שבו התוסף כותב לשדה דרך `search.setFieldText`. מגרסה 0.9.98.3: `visibleWhen: "nonEmptyText"` (כפתור רק כשיש טקסט), הקשר חיפוש מלא באירוע (`request`, `pluginSelections`, `categoryPath`), ו-`mode: "providerBooksFilter"` לסינון ספרי התוסף באיתור הספרים. | +| `contributes.startup.searchFieldActions` | `[]` | כפתורים בתוך שדות החיפוש (מגרסה 0.9.98.1). לחיצה פותחת סשן שבו התוסף כותב לשדה דרך `search.setFieldText`. מגרסה 0.9.98.3: `visibleWhen: "nonEmptyText"` (כפתור רק כשיש טקסט), הקשר חיפוש מלא באירוע (`request`, `pluginSelections`, `categoryPath`), ו-`mode: "providerBooksFilter"` לסינון ספרי התוסף באיתור הספרים. מגרסה 0.9.99: `when` (כפתור שמוצג רק כשתנאי על הגדרה או על ערך אחסון מתקיים). | | `contributes.startup.externalEditions` | `[]` | קונפיגורציית מהדורות מקבילות של ספק חיצוני (טבלת מיפוי במקור DB מוכרז); ראו `API_REFERENCE.md` §מהדורות מקבילות חיצוניות. | | `contributes.startup.libraryBooks` | `[]` | ספק ספרים שמצטרף לאיתור הספרים במסך הספרייה. לחיצה על ספריו נמסרת לתוסף, או מבצעת `openAction` בלי להעיר את המנוע. מגרסה 0.9.98; ראו `API_REFERENCE.md` §ספרים בחיפוש הספרייה. | | `contributes.startup.activationEvents` | `[]` | אירועים שמעירים את מנוע הרקע בעצלנות; כל נושא דורש גם הרשאת subscribe מתאימה. | diff --git a/lib/plugins/models/plugin_search_field_action.dart b/lib/plugins/models/plugin_search_field_action.dart index a983682a9c..c289652641 100644 --- a/lib/plugins/models/plugin_search_field_action.dart +++ b/lib/plugins/models/plugin_search_field_action.dart @@ -1,3 +1,5 @@ +import 'package:otzaria/plugins/models/plugin_when_condition.dart'; + /// שדות החיפוש שבהם תוסף יכול להוסיף כפתור פעולה. השם (`name`) הוא המזהה /// במניפסט ובאירועים. enum PluginSearchField { @@ -73,6 +75,10 @@ class PluginSearchFieldAction { final PluginSearchFieldActionVisibility visibleWhen; final PluginSearchFieldActionMode mode; + /// תנאי הצגה על ערכי הגדרות/אחסון — null = מוצג תמיד. הכפתור נרשם תמיד + /// (וסופר במכסות); התנאי קובע רק אם הוא מצויר כרגע. + final PluginWhenCondition? when; + const PluginSearchFieldAction({ required this.id, required this.title, @@ -82,6 +88,7 @@ class PluginSearchFieldAction { this.libraryOnlyIcon, this.visibleWhen = PluginSearchFieldActionVisibility.always, this.mode = PluginSearchFieldActionMode.session, + this.when, }); bool showsIn(PluginSearchField field) => fields.contains(field); @@ -107,6 +114,7 @@ class PluginSearchFieldAction { 'fields', 'visibleWhen', 'mode', + 'when', }; if (payload.keys.any((key) => !allowedFields.contains(key))) { throw const PluginSearchFieldActionException( @@ -155,6 +163,14 @@ class PluginSearchFieldAction { 'mode must be "session" or "providerBooksFilter"', ); } + PluginWhenCondition? when; + if (payload['when'] != null) { + try { + when = PluginWhenCondition.fromJson(payload['when']); + } on PluginWhenConditionException catch (error) { + throw PluginSearchFieldActionException('when is invalid: $error'); + } + } final isFilter = mode == PluginSearchFieldActionMode.providerBooksFilter; if (libraryOnlyIcon != null && !isFilter) { throw const PluginSearchFieldActionException( @@ -196,6 +212,7 @@ class PluginSearchFieldAction { fields: Set.unmodifiable(fields), visibleWhen: visibleWhen, mode: mode, + when: when, ); } diff --git a/lib/plugins/services/plugin_extended_validator.dart b/lib/plugins/services/plugin_extended_validator.dart index 8eae4db595..6f6ec6fc52 100644 --- a/lib/plugins/services/plugin_extended_validator.dart +++ b/lib/plugins/services/plugin_extended_validator.dart @@ -334,6 +334,7 @@ class PluginExtendedValidator { static const String _whenConditionMinVersion = '0.9.97'; static const String _headlessMinVersion = '0.9.98'; static const String _searchFieldActionsMinVersion = '0.9.98.1'; + static const String _searchFieldActionWhenMinVersion = '0.9.99'; /// `newTab` בלחצן או בפריט תפריט הקשר פותח מופע נוסף של התוסף, ולכן דורש /// `allowMultipleInstances`. הדרישה ל-`openPlugin` ולסוג הערך נבדקת בניתוח @@ -593,6 +594,15 @@ class PluginExtendedValidator { ); } } + // תנאי פגום נדחה כבר בפרסינג; כאן רק מפתח הגדרה שחסום לתוספים, שמוערך + // כ-false בזמן ריצה (כמו ב-_validateWhenConditions). + for (final key in parsed.when?.settingKeys ?? const {}) { + if (!PluginSettingsAccessPolicy.isReadable(key)) { + errors.add( + '$field: when קורא הגדרה שאינה זמינה לתוספים ("$key")', + ); + } + } for (final name in PluginSearchFieldAction.unknownFieldNames(item)) { warnings.add('$field: שדה החיפוש "$name" אינו מוכר ולא יוצג'); } @@ -617,6 +627,14 @@ class PluginExtendedValidator { errors, ); } + if (startup.searchFieldActions.any((item) => item.containsKey('when'))) { + _requireMinVersion( + manifest, + _searchFieldActionWhenMinVersion, + '$field: when', + errors, + ); + } // כפתור סינון אינו שולח אירוע ואינו פותח דף, ולכן ההרשאה לא משנה לו. final hasSessionAction = startup.searchFieldActions.any( (item) => diff --git a/lib/plugins/services/plugin_startup_contributions_service.dart b/lib/plugins/services/plugin_startup_contributions_service.dart index 1b1ab20c71..3d39ba56aa 100644 --- a/lib/plugins/services/plugin_startup_contributions_service.dart +++ b/lib/plugins/services/plugin_startup_contributions_service.dart @@ -393,6 +393,7 @@ class PluginStartupContributionsService { ...startup.toolbarItems, ...startup.contextMenuItems, ...startup.searchDialogItems, + ...startup.searchFieldActions, ...startup.libraryBooks, ]) { final raw = item['when']; diff --git a/lib/plugins/view/plugin_search_field_actions.dart b/lib/plugins/view/plugin_search_field_actions.dart index 7846520159..a871f94df7 100644 --- a/lib/plugins/view/plugin_search_field_actions.dart +++ b/lib/plugins/view/plugin_search_field_actions.dart @@ -6,6 +6,7 @@ import 'package:flutter/material.dart'; import 'package:otzaria/core/windowing/app_window_keys.dart'; import 'package:otzaria/plugins/models/plugin_library_books_filter.dart'; import 'package:otzaria/plugins/models/plugin_search_field_action.dart'; +import 'package:otzaria/plugins/services/plugin_condition_evaluator.dart'; import 'package:otzaria/plugins/services/plugin_library_books_registry.dart'; import 'package:otzaria/plugins/services/plugin_search_field_actions_registry.dart'; import 'package:otzaria/plugins/services/plugin_search_field_session_service.dart'; @@ -37,6 +38,8 @@ class PluginSearchFieldActions extends StatefulWidget { final PluginSearchFieldSessionService? sessions; @visibleForTesting final PluginLibraryBooksRegistry? libraryBooks; + @visibleForTesting + final PluginConditionEvaluator? conditions; const PluginSearchFieldActions({ super.key, @@ -50,6 +53,7 @@ class PluginSearchFieldActions extends StatefulWidget { this.registry, this.sessions, this.libraryBooks, + this.conditions, }); @override @@ -65,6 +69,8 @@ class _PluginSearchFieldActionsState extends State widget.sessions ?? PluginSearchFieldSessionService.instance; PluginLibraryBooksRegistry get _libraryBooks => widget.libraryBooks ?? PluginLibraryBooksRegistry.instance; + PluginConditionEvaluator get _conditions => + widget.conditions ?? PluginConditionEvaluator.instance; // הכפתור יושב בתוך השדה, ובדסקטופ השדה מזיז את הסמן כבר ב-tap down (לפני // onPressed). הסשן צריך את הבחירה שהייתה ברגע הלחיצה. @@ -124,7 +130,11 @@ class _PluginSearchFieldActionsState extends State widget.invocationContext?.call() ?? const {}; /// כפתור עם סשן פתוח נשאר גלוי גם כשהטקסט התרוקן, כדי שאפשר יהיה לעצור אותו. + /// + /// תנאי `when` גובר גם על סשן פתוח: כשהוא כבה הכפתור נעלם, כמו כל תרומה + /// אחרת, והסשן ממשיך עד שייסגר כרגיל. bool _isShown(String pluginId, PluginSearchFieldAction action) => + _conditions.isVisible(pluginId, action.when) && (action.isVisibleFor(widget.controller.text) || _sessions.sessionFor(this, pluginId, action.id) != null) && (!action.isProviderBooksFilter || _libraryBooks.hasProviderFor(pluginId)); @@ -142,12 +152,16 @@ class _PluginSearchFieldActionsState extends State ]), builder: (context, _) { final registered = _registry.actionsFor(widget.field); - // האזנה לכל הקשה רק כשיש כפתור שתלוי בטקסט. - if (!registered.any((entry) => entry.$2.showOnlyWithText)) { - return _buildRow(context, registered); - } + // האזנה לכל הקשה רק כשיש כפתור שתלוי בטקסט, ולשינויי הגדרות ואחסון + // רק כשיש כפתור עם תנאי `when`. + final dependencies = [ + if (registered.any((entry) => entry.$2.showOnlyWithText)) + widget.controller, + if (registered.any((entry) => entry.$2.when != null)) _conditions, + ]; + if (dependencies.isEmpty) return _buildRow(context, registered); return ListenableBuilder( - listenable: widget.controller, + listenable: Listenable.merge(dependencies), builder: (context, _) => _buildRow(context, registered), ); }, diff --git a/test/plugins/models/plugin_search_field_action_test.dart b/test/plugins/models/plugin_search_field_action_test.dart index b7a14042df..25b575c3cd 100644 --- a/test/plugins/models/plugin_search_field_action_test.dart +++ b/test/plugins/models/plugin_search_field_action_test.dart @@ -1,6 +1,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:otzaria/plugins/models/plugin_search_field_action.dart'; import 'package:otzaria/plugins/models/plugin_startup_contributions.dart'; +import 'package:otzaria/plugins/models/plugin_when_condition.dart'; import 'package:otzaria/plugins/services/plugin_search_field_actions_registry.dart'; void main() { @@ -136,6 +137,113 @@ void main() { } }); + group('when', () { + test('בלי when — מוצג תמיד', () { + final action = PluginSearchFieldAction.fromPayload({ + 'id': 'a', + 'title': 'א', + }); + expect(action.when, isNull); + }); + + test('תנאי תקף מפורסר דרך המנוע המשותף, בשני המצבים', () { + final condition = { + 'all': [ + { + 'storage': {'key': 'showButton', 'equals': true}, + }, + { + 'setting': {'key': 'key-dark-mode', 'exists': true}, + }, + ], + }; + final session = PluginSearchFieldAction.fromPayload({ + 'id': 'a', + 'title': 'א', + 'when': condition, + }); + expect(session.when!.kind, PluginWhenConditionKind.all); + expect(session.when!.storageKeys, {'showButton'}); + expect(session.when!.settingKeys, {'key-dark-mode'}); + expect(session.when!.toJson(), condition); + + final filter = PluginSearchFieldAction.fromPayload({ + 'id': 'f', + 'title': 'מקור', + 'mode': 'providerBooksFilter', + 'when': condition, + }); + expect(filter.when, isNotNull); + expect(filter.isProviderBooksFilter, isTrue); + }); + + for (final (name, badWhen) in <(String, Object?)>[ + ('לא אובייקט', 'always'), + ('אובייקט ריק', {}), + ('אופרטור לא מוכר', {'maybe': true}), + ( + 'עלה בלי אופרטור', + { + 'storage': {'key': 'k'}, + }, + ), + ( + 'שני אופרטורים בעלה', + { + 'storage': {'key': 'k', 'equals': 1, 'exists': true}, + }, + ), + ( + 'מפתח ריק', + { + 'setting': {'key': '', 'exists': true}, + }, + ), + ('all ריק', {'all': []}), + ]) { + test('נדחה: when $name', () { + expect( + () => PluginSearchFieldAction.fromPayload({ + 'id': 'a', + 'title': 'א', + 'when': badWhen, + }), + throwsA( + isA().having( + (error) => error.message, + 'message', + startsWith('when is invalid'), + ), + ), + ); + }); + } + + test('כפתור מוסתר עדיין נרשם וסופר במכסות', () { + final registry = PluginSearchFieldActionsRegistry.forTesting(); + final never = { + 'storage': {'key': 'k', 'exists': true}, + }; + registry.registerPayload('p1', {'id': 'a', 'title': 'א', 'when': never}); + registry.registerPayload('p1', {'id': 'b', 'title': 'ב', 'when': never}); + expect( + () => registry.registerPayload('p1', {'id': 'c', 'title': 'ג'}), + throwsA(isA()), + ); + registry.registerPayload('p2', {'id': 'a', 'title': 'א'}); + registry.registerPayload('p3', {'id': 'a', 'title': 'א'}); + registry.registerPayload('p4', {'id': 'a', 'title': 'א'}); + + // שלושת הכפתורים הראשונים תופסים את המכסה גם אם התנאי שלהם כבוי. + expect( + registry + .actionsFor(PluginSearchField.library) + .map((e) => '${e.$1}/${e.$2.id}'), + ['p1/a', 'p1/b', 'p2/a'], + ); + }); + }); + test('searchFieldActions במניפסט מעיר את מנוע הרקע ונשמר בהמרה', () { final startup = PluginStartupContributions.fromJson({ 'searchFieldActions': [ diff --git a/test/plugins/services/plugin_extended_validator_startup_test.dart b/test/plugins/services/plugin_extended_validator_startup_test.dart index ebf189b47c..726f8d8b0e 100644 --- a/test/plugins/services/plugin_extended_validator_startup_test.dart +++ b/test/plugins/services/plugin_extended_validator_startup_test.dart @@ -304,6 +304,98 @@ void main() { expect(report.errors, contains(contains('visibleWhen'))); }); + group('when', () { + const storageWhen = { + 'storage': {'key': 'showDictate', 'equals': true}, + }; + + test('תנאי תקף עובר מ-0.9.99 ושגוי על גרסה ישנה', () { + final items = [ + {'id': 'a', 'title': 'א', 'when': storageWhen}, + ]; + expect( + _run( + tempDir, + actionsManifest(minAppVersion: '0.9.99', items: items), + ).errors, + isEmpty, + ); + final old = _run( + tempDir, + actionsManifest(minAppVersion: '0.9.98.3', items: items), + ); + expect(old.errors, contains(contains('searchFieldActions: when'))); + expect(old.errors, contains(contains('0.9.99'))); + }); + + test('כפתור סינון ספרי תוסף עם when תקף', () { + final report = _run( + tempDir, + _manifest( + permissions: const [ + 'app.startup_contributions', + 'search.field_actions', + 'library.books.provide', + ], + minAppVersion: '0.9.99', + startup: { + 'libraryBooks': [ + {'id': 'books', 'provider': 'mylib', 'title': 'הספרייה שלי'}, + ], + 'searchFieldActions': [ + { + 'id': 'source', + 'title': 'מקור', + 'mode': 'providerBooksFilter', + 'when': storageWhen, + }, + ], + }, + ), + ); + expect(report.errors, isEmpty); + }); + + test('תנאי פגום נדחה פעם אחת באותה הודעה כמו תרומות אחרות', () { + final report = _run( + tempDir, + actionsManifest( + minAppVersion: '0.9.99', + items: [ + { + 'id': 'a', + 'title': 'א', + 'when': {'maybe': true}, + }, + ], + ), + ); + expect( + report.errors.where((e) => e.contains('when is invalid')), + hasLength(1), + ); + }); + + test('הגדרת תוכנה חסומה לתוספים — שגיאה', () { + final report = _run( + tempDir, + actionsManifest( + minAppVersion: '0.9.99', + items: [ + { + 'id': 'a', + 'title': 'א', + 'when': { + 'setting': {'key': 'key-bookmarks', 'exists': true}, + }, + }, + ], + ), + ); + expect(report.errors, contains(contains('key-bookmarks'))); + }); + }); + test('mode בלבד דורש minAppVersion 0.9.98.3', () { final items = [ {'id': 'a', 'title': 'א', 'mode': 'session'}, diff --git a/test/plugins/services/plugin_startup_contributions_service_test.dart b/test/plugins/services/plugin_startup_contributions_service_test.dart index 7423ee9c2b..6a338a3b40 100644 --- a/test/plugins/services/plugin_startup_contributions_service_test.dart +++ b/test/plugins/services/plugin_startup_contributions_service_test.dart @@ -334,6 +334,43 @@ void main() { expect(endReasons, ['closed']); expect(fieldSessions.hasSessionsFor(field), isFalse); }); + + test('מפתח האחסון של when נטען, והכפתור נרשם גם כשהתנאי כבוי', () async { + final evaluator = PluginConditionEvaluator.forTesting(); + addTearDown(evaluator.dispose); + final conditionalService = PluginStartupContributionsService.forTesting( + toolbarRegistry: toolbar, + contextMenuRegistry: contextMenu, + activationService: activation, + searchFieldActionsRegistry: fieldActions, + searchFieldSessions: fieldSessions, + conditionEvaluator: evaluator, + ); + const when = { + 'storage': {'key': 'showDictate', 'equals': true}, + }; + repo.grantedByPlugin['p1'] = { + 'app.startup_contributions', + 'search.field_actions', + }; + await conditionalService.sync([ + _plugin( + startup: { + 'searchFieldActions': [ + {'id': 'dictate', 'title': 'דיבור', 'when': when}, + ], + }, + ), + ], repo); + + final action = fieldActions + .actionsFor(PluginSearchField.library) + .single + .$2; + expect(evaluator.isVisible('p1', action.when), isFalse); + evaluator.onStorageValueChanged('p1', 'showDictate', true); + expect(evaluator.isVisible('p1', action.when), isTrue); + }); }); test('registers all contributions when permissions are granted', () async { diff --git a/test/plugins/view/plugin_search_field_actions_test.dart b/test/plugins/view/plugin_search_field_actions_test.dart index 135c7c0fb9..9f06dba1e1 100644 --- a/test/plugins/view/plugin_search_field_actions_test.dart +++ b/test/plugins/view/plugin_search_field_actions_test.dart @@ -24,6 +24,20 @@ class _EmptyRepository implements PluginRegistryRepository { dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); } +class _KvRepository extends _EmptyRepository { + final Map values = {}; + + @override + Future> getKVMany( + String pluginId, + String namespace, + Iterable keys, + ) async => { + for (final key in keys) + if (values.containsKey(key)) key: values[key]!, + }; +} + void main() { group('OtzariaSearchField', () { tearDown( @@ -215,6 +229,7 @@ void main() { PluginSearchField field = PluginSearchField.fullText, Map Function()? invocationContext, PluginLibraryBooksRegistry? libraryBooks, + PluginConditionEvaluator? conditions, }) => tester.pumpWidget( MaterialApp( home: Scaffold( @@ -225,6 +240,7 @@ void main() { registry: registry, sessions: sessions, libraryBooks: libraryBooks, + conditions: conditions, ), ), ), @@ -253,6 +269,151 @@ void main() { expect(find.byKey(_buttonKey), findsNothing); }); + group('when', () { + const storageWhen = { + 'storage': {'key': 'showDictate', 'equals': true}, + }; + + testWidgets('ערך אחסון: הכפתור מופיע ונעלם מיד כשהערך משתנה', ( + tester, + ) async { + final repository = _KvRepository(); + final conditions = PluginConditionEvaluator.forTesting(); + addTearDown(conditions.dispose); + await conditions.registerStorageKeys('voice', { + 'showDictate', + }, repository); + registry.registerPayload('voice', { + 'id': 'dictate', + 'title': 'חיפוש בדיבור', + 'icon': 'mic_24_regular', + 'when': storageWhen, + }); + final controller = TextEditingController(); + addTearDown(controller.dispose); + await pumpActions(tester, controller, conditions: conditions); + expect(find.byKey(_buttonKey), findsNothing); + + conditions.onStorageValueChanged('voice', 'showDictate', true); + await tester.pump(); + expect(find.byKey(_buttonKey), findsOneWidget); + + conditions.onStorageValueChanged('voice', 'showDictate', false); + await tester.pump(); + expect(find.byKey(_buttonKey), findsNothing); + + conditions.onStorageRemoved('voice', 'showDictate'); + conditions.onStorageValueChanged('voice', 'showDictate', true); + await tester.pump(); + expect(find.byKey(_buttonKey), findsOneWidget); + }); + + testWidgets('הגדרת תוכנה: ההחלפה מורגשת בלי מנוע התוסף', (tester) async { + Object? darkMode = false; + final conditions = PluginConditionEvaluator.forTesting( + settingReader: (_) => darkMode, + ); + addTearDown(conditions.dispose); + registry.registerPayload('voice', { + 'id': 'dictate', + 'title': 'חיפוש בדיבור', + 'when': { + 'setting': {'key': 'key-dark-mode', 'equals': true}, + }, + }); + final controller = TextEditingController(); + addTearDown(controller.dispose); + await pumpActions(tester, controller, conditions: conditions); + expect(find.byKey(_buttonKey), findsNothing); + + darkMode = true; + conditions.notifySettingsChanged(); + await tester.pump(); + expect(find.byKey(_buttonKey), findsOneWidget); + expect(sent, isEmpty); + }); + + testWidgets('מצטרף ל-visibleWhen: שני התנאים חייבים להתקיים', ( + tester, + ) async { + final conditions = PluginConditionEvaluator.forTesting(); + addTearDown(conditions.dispose); + await conditions.registerStorageKeys('voice', { + 'showDictate', + }, _KvRepository()); + registry.registerPayload('voice', { + 'id': 'dictate', + 'title': 'חיפוש בדיבור', + 'visibleWhen': 'nonEmptyText', + 'when': storageWhen, + }); + final controller = TextEditingController(text: 'ברכות'); + addTearDown(controller.dispose); + await pumpActions(tester, controller, conditions: conditions); + expect(find.byKey(_buttonKey), findsNothing); + + conditions.onStorageValueChanged('voice', 'showDictate', true); + await tester.pump(); + expect(find.byKey(_buttonKey), findsOneWidget); + + controller.clear(); + await tester.pump(); + expect(find.byKey(_buttonKey), findsNothing); + }); + + testWidgets('כפתור סינון ספרי תוסף מכבד when', (tester) async { + final conditions = PluginConditionEvaluator.forTesting(); + addTearDown(conditions.dispose); + await conditions.registerStorageKeys('voice', { + 'showDictate', + }, _KvRepository()); + registry.removeAll('voice'); + registry.registerPayload('voice', { + 'id': 'source', + 'title': 'מקור הספרים', + 'mode': 'providerBooksFilter', + 'when': storageWhen, + }); + final books = PluginLibraryBooksRegistry.forTesting( + conditions: conditions, + repository: _EmptyRepository(), + ); + addTearDown(books.dispose); + books.registerPayload('voice', { + 'id': 'books', + 'provider': 'mylib', + 'title': 'הספרייה שלי', + }); + final controller = TextEditingController(); + addTearDown(controller.dispose); + await pumpActions( + tester, + controller, + field: PluginSearchField.library, + libraryBooks: books, + conditions: conditions, + ); + expect(find.byKey(_filterKey), findsNothing); + + conditions.onStorageValueChanged('voice', 'showDictate', true); + await tester.pump(); + expect(find.byKey(_filterKey), findsOneWidget); + }); + + testWidgets('כפתור בלי when לא מאזין להגדרות ולאחסון', (tester) async { + final conditions = PluginConditionEvaluator.forTesting(); + addTearDown(conditions.dispose); + final controller = TextEditingController(); + addTearDown(controller.dispose); + await pumpActions(tester, controller, conditions: conditions); + expect(find.byKey(_buttonKey), findsOneWidget); + + conditions.notifySettingsChanged(); + await tester.pump(); + expect(find.byKey(_buttonKey), findsOneWidget); + }); + }); + testWidgets('ההקשר של השדה מצורף לאירוע, ובחירות רק של התוסף הקורא', ( tester, ) async {