Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
docs: Update new feature tutorial for changes and toy feature.
Lauryn Menarddb3b574d918a
diff --git a/docs/tutorials/new-feature-tutorial.md b/docs/tutorials/new-feature-tutorial.mdindex e13950b5ea3..e1f415c546e 100644--- a/docs/tutorials/new-feature-tutorial.md+++ b/docs/tutorials/new-feature-tutorial.md@@ -36,39 +36,47 @@ organization in Zulip). The following files are involved in the process:**Backend**- `zerver/models/realms.py`: Defines the database model.-- `zerver/views/realm.py`: The view function that implements the API endpoint- for editing realm objects.-- `zerver/actions/realm_settings.py`: Contains code for updating and interacting with the database.-- `zerver/lib/events.py`: Ensures that the state Zulip sends to clients is always- consistent and correct.+- `zerver/views/realm.py`: Contains the view function that implements the+ API endpoint for editing Realm objects.+- `zerver/actions/realm_settings.py`: Contains code for updating and+ interacting with the database.+- `zerver/lib/events.py`: Ensures that the state Zulip sends to clients+ is always consistent and correct.**Frontend**-- `web/templates/settings/organization_permissions_admin.hbs`: defines- the structure of the admin permissions page (checkboxes for each organization- permission setting).-- `web/src/settings_org.ts`: handles organization setting form submission.-- `web/src/server_events_dispatch.js`: handles events coming from the server- (ex: pushing an organization change to other open browsers and updating- the application's state).+- `web/src/state_data.ts`: Defines the expected state of the data that+ is received from the Zulip server.+- `web/templates/settings/organization_settings_admin.hbs`: Defines+ the structure of the organization settings admin modal.+- `web/src/admin.ts`: Handles building the organization settings admin+ modal.+- `web/src/settings_org.ts`: Handles form submission for changes to an+ organization's settings.+- `web/src/server_events_dispatch.js`: Handles events coming from the+ server.**Backend testing**-- `zerver/tests/test_realm.py`: end-to-end API tests for updating realm settings.-- `zerver/tests/test_events.py`: tests for possible race bugs in the- zerver/lib/events.py implementation.+- `zerver/tests/test_realm.py`: Contains end-to-end API tests for+ updating realm settings.+- `zerver/tests/test_events.py`: Tests for possible race bugs in the+ implementation of events.**Frontend testing**-- `web/e2e-tests/admin.test.ts`: end-to-end tests for the organization- admin settings pages.-- `web/tests/dispatch.test.cjs`+- `web/e2e-tests/admin.test.ts`: Contains end-to-end tests for the+ organization admin settings pages.+- `web/tests/dispatch.test.cjs`: Unit tests for handling of events.**Documentation**-- `zerver/openapi/zulip.yaml`: OpenAPI definitions for the Zulip REST API.-- `api_docs/changelog.md`: documentation listing all changes to the Zulip Server API.-- `help/...`: end user facing documentation (help center) for the application.+- `zerver/openapi/zulip.yaml`: Contains OpenAPI definitions for the+ Zulip REST API.+- `api_docs/changelog.md`: Documentation listing all changes to the+ Zulip Server API.+- `starlight_help/...`: The user-facing documentation (help center)+ for the application.### Adding a field to the database@@ -100,19 +108,19 @@ the flow of events even if the `property_types` framework means you don'thave to write much code for a new setting.**Database interaction:** Add any necessary code for updating and-interacting with the database in `zerver/actions/realm_settings.py`. It should-update the database and send an event announcing the change.+interacting with the database in `zerver/actions/realm_settings.py`.+It should update the database and send an event announcing the change.**Application state:** Modify the `fetch_initial_state_data` and`apply_event` functions in `zerver/lib/events.py` to update the state-based on the event you just created.+based on the field you just created.**Backend implementation:** Make any other modifications to the backendrequired for your feature to do what it's supposed to do (this willbe unique to the feature you're implementing).**New views:** Add any new application views to `zproject/urls.py`, or-update the appropriate existing view in `zerver/views/`. This+update the appropriate existing view in `zerver/views/...`. Thisincludes both views that serve HTML (new pages on Zulip) as well as newAPI endpoints that serve JSON-formatted data.@@ -137,16 +145,15 @@ Handlebars templates located in `web/templates`. Templates areprecompiled as part of the build/deploy process.Zulip is fully internationalized, so when writing both HTML templates-or JavaScript/TypeScript/Python code that generates user-facing strings, be sure to-[tag those strings for translation](../translating/translating.md).+or JavaScript/TypeScript/Python code that generates user-facing strings,+be sure to [tag those strings for translation](../translating/translating.md).**Testing:** There are two types of frontend tests: node-based unittests and blackbox end-to-end tests. The blackbox tests are run in aheadless Chromium browser using Puppeteer and are located in-`web/e2e-tests/`. The unit tests use Node's `assert`-module are located in `web/tests/`. For more-information on writing and running tests, see the-[testing documentation](../testing/testing.md).+`web/e2e-tests/`. The unit tests use Node's `assert` module are located+in `web/tests/`. For more information on writing and running tests, see+the [testing documentation](../testing/testing.md).### Documentation changes@@ -156,10 +163,10 @@ For detailed information on the kinds of documentation Zulip has, see[Documentation](../documentation/overview.md).**Help center documentation:** You will likely need to at least update,-extend and link to articles in the `help/` directory that are related-to your new feature. [Writing help center articles](../documentation/helpcenter.md)+extend and link to articles in the `starlight_help/` directory that are+related to your new feature. [Writing help center articles](../documentation/helpcenter.md)provides more detailed information about writing and editing feature-`help/` directory articles.+`starlight_help/` directory articles.**API documentation:** A new feature will probably impact the REST APIdocumentation as well, which will mean updating `zerver/openapi/zulip.yaml`@@ -170,20 +177,24 @@ guide to adding or updating documentation for an API endpoint.## Example feature-This example describes the process of adding a new setting to Zulip: a-flag that allows an admin to require topics on channel messages (the default-behavior is that topics can have no subject). This flag is an-actual Zulip feature. You can review [the original commit](https://github.com/zulip/zulip/pull/5660/commits/aeeb81d3ff0e0cc201e891cec07e1d2cd0a2060d)-in the Zulip repo. (This commit displays the work of setting up a checkbox-for the feature on the admin settings page, communicating and saving updates-to the setting to the database, and updating the state of the application-after the setting is updated. For the code that accomplishes the underlying-task of requiring messages to have a topic, you can [view this commit](https://github.com/zulip/zulip/commit/90e2f5053f5958b44ea9b2362cadcb076deaa975).)+This example describes the process of adding a new realm setting to Zulip.+For the purposes of this tutorial, this new setting will be called+`my_fantastic_feature`.++:::{tip}++A useful tool that we'll highlight throughout this tutorial is+`git-grep`. If you're unfamiliar with using `git-grep`, then check out+[this blog post](https://laurynmm.github.io/2021/12/22/git-grep.html)+for an introduction to it, as well as the [official `git-grep`+documentation](https://git-scm.com/docs/git-grep.)++:::### Update the modelFirst, update the database and model to store the new setting. Add a new-boolean field, `mandatory_topics`, to the Realm model in+boolean field, `my_fantastic_feature`, to the Realm model in`zerver/models/realms.py`.```diff@@ -191,16 +202,20 @@ boolean field, `mandatory_topics`, to the Realm model inclass Realm(models.Model):# ...- emails_restricted_to_domains = models.BooleanField(default=True)- invite_required = models.BooleanField(default=False)-+ mandatory_topics = models.BooleanField(default=False)+ require_unique_names = models.BooleanField(default=False)+ name_changes_disabled = models.BooleanField(default=False)+ email_changes_disabled = models.BooleanField(default=False)+ avatar_changes_disabled = models.BooleanField(default=False)+++ # My fantastic feature for the new feature tutorial.++ my_fantastic_feature = models.BooleanField(default=False)```The Realm model also contains an attribute, `property_types`, which-other backend functions use to handle most realm settings without any custom-code for the setting (more on this process below). The attribute is a-dictionary, where the key is the name of the realm field and the value-is the field's type. Add the new field to the `property_types`+other backend functions use to handle most realm settings without any+custom code for the setting (more on this process below). The attribute+is a dictionary, where the key is the name of the realm field and the+value is the field's type. Add the new field to the `property_types`dictionary.```diff@@ -209,35 +224,32 @@ dictionary.class Realm(models.Model)# ...# Define the types of the various automatically managed properties- property_types = dict(- add_custom_emoji_policy=int,- allow_edit_history=bool,+ property_types: dict[str, type | UnionType] = dict(+ allow_message_editing=bool,+ avatar_changes_disabled=bool,# ...-+ mandatory_topics=bool,++ my_fantastic_feature=bool,# ...```-**The majority of realm settings can be included in-`property_types`.** However, there are some properties that need custom-logic and thus cannot use this framework. For example:+**The majority of realm settings can be included in `property_types`.**+However, there are some properties that need custom logic and thus cannot+use this framework. Any properties that define a relationship to another+model (e.g., a `ForeignKey` field) do not use the `property_types`+framework, for example `moderation_request_channel` property and the+`can_add_custom_emoji_group` property.-- The realm `authentication_methods` attribute is a bitfield and needs- additional code for validation and updating.-- The `allow_message_editing` and `message_content_edit_limit_seconds`- fields depend on one another, so they are also handled separately and- not included in `property_types`.--When creating a realm property that is not a boolean, Text or+When creating a realm property that is not a boolean, character orinteger field, or when adding a field that is dependent on other fields,-do not add the field to the `property_types` dictionary. The steps-below will point out where to write additional code for these cases.+do not add the field to the `property_types` dictionary. The steps below+will point out where to write additional code for these cases.### Create the migrationCreate the migration file using the Django `makemigrations` command:-`./manage.py makemigrations`. Make sure to commit the generated file to git:-`git add zerver/migrations/NNNN_realm_mandatory_topics.py`-(NNNN is a number that is equal to the number of migrations.)+`./manage.py makemigrations`. Make sure to commit the generated file to+git: `git add zerver/migrations/NNNN_my_fantastic_feature.py` (NNNN is a+number that is equal to the current number of migrations.)If you run into problems, the[Django migration documentation](https://docs.djangoproject.com/en/5.0/topics/migrations/)@@ -258,7 +270,7 @@ Synchronizing apps without migrations:Installing custom SQL...Running migrations:Rendering model states... DONE- Applying zerver.NNNN_realm_mandatory_topics... OK+ Applying zerver.NNNN_my_fantastic_feature... OK```Once you've run the migration, [restart the development@@ -266,16 +278,16 @@ server](../development/remote.md#running-the-development-server).### Handle database interactions-Next, we will implement the backend part of this feature.-Like typical apps, we will need our backend to update the database and-send some response to the client that made the request.+Next, we will implement the backend part of this feature. Like typical+apps, we will need our backend to update the database and send some+response to the client that made the request.-Beyond that, we need to orchestrate notifications about the setting change-to _other_ clients (or other users, if you will). Clients-find out about settings through two closely related code paths. When a client-first contacts the server, the server sends the client its-initial state. Subsequently, clients subscribe to "events," which can-(among other things) indicate that settings have changed.+Beyond that, we need to orchestrate notifications about the setting+change to _other_ clients (or other users, if you will). Clients find out+about settings through two closely related code paths. When a client+first contacts the server, the server sends the client its initial state.+Subsequently, clients subscribe to "events," which can (among other+things) indicate that settings have changed.For the backend piece, we will need our action to make a call to`send_event_on_commit` to send the event to clients that are active@@ -285,14 +297,15 @@ commits, hence the name). We will also need to modifyclients. See [our event system docs](../subsystems/events-system.md)for all the gory details.-Anyway, getting back to implementation details...+Getting back to implementation details...If you are working on a feature that is in the realm `property_types`-dictionary, you will not need to add code to `zerver/actions/realm_settings.py`, but-we will describe what the process in that file does:+dictionary, you will not need to add code to+`zerver/actions/realm_settings.py`, but we will describe what the+process in that file does:-In `zerver/actions/realm_settings.py`, the function `do_set_realm_property` takes-in the name of a realm property to update and the value it should+In `zerver/actions/realm_settings.py`, the function `do_set_realm_property`+takes in the name of a realm property to update and the value it shouldhave. This function updates the database and triggers an event tonotify clients about the change. It uses the field's type, specifiedin the `Realm.property_types` dictionary, to validate the type of the@@ -301,122 +314,106 @@ help catch coding mistakes, not to check for bad user input.After updating the given realm field, `do_set_realm_property` createsan 'update' event with the name of the property and the new value. It-then calls `send_event_on_commit`, passing the event and the list of users whose-browser sessions should be notified as the second argument. The latter-argument can be a single user (if the setting is a personal one, like-time display format), members in a particular channel only or all-active users in a realm.+then calls `send_event_on_commit`, passing the event and the list of+users whose browser sessions should be notified as the second argument.+The latter argument can be a single user (if the setting is a personal+one, like time display format), members in a particular channel only or+all active users in an realm.-```python-# zerver/actions/realm_settings.py+:::{tip}-def do_set_realm_property(- realm: Realm, name: str, value: Any, *, acting_user: Optional[UserProfile]-) -> None:- """Takes in a realm object, the name of an attribute to update, the- value to update and the user who initiated the update.- """- property_type = Realm.property_types[name]- assert isinstance(value, property_type), (- 'Cannot update %s: %s is not an instance of %s' % (- name, value, property_type,))-- setattr(realm, name, value)- realm.save(update_fields=[name])- event = dict(- type='realm',- op='update',- property=name,- value=value,- )- send_event_on_commit(realm, event, active_user_ids(realm))-```+Use git-grep to find and read the `do_set_realm_property`+function. Are there `property_types` that are handled differently in+that function? Which ones? Does the function indicate why?++:::If the new realm property being added does not fit into the-`property_types` framework (such as the `authentication_methods`+`property_types` framework (such as the `moderation_request_channel`field), you'll need to create a new function to explicitly update thisfield and send an event. For example:```python# zerver/actions/realm_settings.py-def do_set_realm_authentication_methods(- realm: Realm, authentication_methods: Dict[str, bool], *, acting_user: Optional[UserProfile]+def do_set_realm_stream(+ realm: Realm,+ field: Literal[+ "moderation_request_channel",+ "new_stream_announcements_stream",+ "signup_announcements_stream",+ "zulip_update_announcements_stream",+ ],+ stream: Stream | None,+ stream_id: int,+ *,+ acting_user: UserProfile | None,) -> None:- for key, value in authentication_methods.items():- index = getattr(realm.authentication_methods, key).number- realm.authentication_methods.set_bit(index, int(value))- realm.save(update_fields=['authentication_methods'])- event = dict(- type="realm",- op="update_dict",- property='default',- data=dict(authentication_methods=realm.authentication_methods_dict())- )- send_event_on_commit(realm, event, active_user_ids(realm))+ # We could calculate more of these variables from `field`, but+ # it's probably more readable to not do so.+ if field == "moderation_request_channel":+ old_value = realm.moderation_request_channel_id+ realm.moderation_request_channel = stream+ property = "moderation_request_channel_id"```### Update application state-`zerver/lib/events.py` contains code to ensure that your new setting is included-in the data sent down to clients: both when a new client is loaded-and when changes happen. This file also automatically-handles realm settings in the `property_types` dictionary, so you would-not need to change this file if your setting fits that framework.+`zerver/lib/events.py` contains code to ensure that your new setting is+included in the data sent down to clients: both when a new client is+loaded and when changes happen. This file also automatically handles+realm settings in the `property_types` dictionary, so you would not need+to change this file if your setting fits that framework.-The `fetch_initial_state_data` function is responsible for sending data when-a client is loaded (data added to the `state` here will be available both-in `page_params` in the browser, as well as to API clients like the mobile-apps). The `apply_event` function in `zerver/lib/events.py` is important for-making sure the `state` is always correct, even in the event of rare-race conditions.+The `fetch_initial_state_data` function is responsible for sending data+when a client is loaded (data added to the `state` here will be available+both in `page_params` in the browser, as well as to API clients like the+mobile app). The `apply_event` function in `zerver/lib/events.py` is+important for making sure the `state` is always correct, even in the+event of rare race conditions.```python# zerver/lib/events.py-def fetch_initial_state_data(user_profile, event_types, queue_id, include_subscribers=True):+def fetch_initial_state_data(+ user_profile: UserProfile | None,# ...- if want('realm'):+ if want("realm"):+ # The realm bundle includes both realm properties and server+ # properties, since it's rare that one would want one and not+ # the other. We expect most clients to want it.+ # ...for property_name in Realm.property_types:- state['realm_' + property_name] = getattr(user_profile.realm, property_name)- state['realm_authentication_methods'] = user_profile.realm.authentication_methods_dict()- state['realm_allow_message_editing'] = user_profile.realm.allow_message_editing+ state["realm_" + property_name] = getattr(realm, property_name)++ for setting_name in Realm.REALM_PERMISSION_GROUP_SETTINGS:+ setting_group_id = getattr(realm, setting_name + "_id")+ state["realm_" + setting_name] = get_group_setting_value_for_register_api(+ setting_group_id, anonymous_group_membership_data_dict+ )# ...-def apply_event+def apply_event(user_profile: UserProfile,# ...) -> None:- for event in events:- # ...- elif event['type'] == 'realm':- field = 'realm_' + event['property']- state[field] = event['value']+ # ...+ elif event["type"] == "realm":+ if event["op"] == "update":+ field = "realm_" + event["property"]+ state[field] = event["value"]# ...```-If your new realm property fits the `property_types`-framework, you don't need to change `fetch_initial_state_data` or-`apply_event`. However, if you are adding a-property that is handled separately, you will need to explicitly add-the property to the `state` dictionary in the `fetch_initial_state_data`-function. E.g., for `authentication_methods`:--```python-# zerver/lib/events.py--def fetch_initial_state_data(user_profile, event_types, queue_id, include_subscribers=True):- # ...- if want('realm'):- # ...- state['realm_authentication_methods'] = user_profile.realm.authentication_methods_dict()- # ...-```+If your new realm property fits the `property_types` framework, you don't+need to change `fetch_initial_state_data` or `apply_event`. However, if+you are adding a property that is handled separately, you will need to+explicitly add the property to the `state` dictionary in the+`fetch_initial_state_data` function.-For this setting, one won't need to change `apply_event` since its-default code for `realm` event types handles this case correctly, but-for a totally new type of feature, a few lines in that function may be-needed.+For our example, one won't need to change `apply_event` since its default+code for `realm` event types handles this case correctly, but for a+totally new type of feature, a few lines in that function may be needed.### Add a new view@@ -435,22 +432,24 @@ annotation).```diff# zerver/views/realm.py- @typed_endpoint- def update_realm(- request: HttpRequest,- user_profile: UserProfile,+@require_realm_admin+@typed_endpoint+def update_realm(+ request: HttpRequest,+ user_profile: UserProfile,*,- name: str | None,+ allow_message_editing: Json[bool] | None = None,+ authentication_methods: Json[dict[str, Any]] | None = None,# ...-+ mandatory_topics: Json[bool] | None = None,++ my_fantastic_feature: Json[bool] | None = None,# ...):# ...```-If this feature fits the `property_types` framework and does-not require additional validation, this is the only change to make-to `zerver/views/realm.py`.+If this feature fits the `property_types` framework and does not+require additional validation, this is the only change to make to+`zerver/views/realm.py`.Text fields or other realm properties that need additional validationcan be handled at the beginning of `update_realm`.@@ -458,12 +457,10 @@ can be handled at the beginning of `update_realm`.```python# zerver/views/realm.py-# Additional validation/error checking beyond types go here, so-# the entire request can succeed or fail atomically.-if default_language is not None and default_language not in get_available_language_codes():- raise JsonableError(_("Invalid language '%s'" % (default_language,)))-if description is not None and len(description) > 100:- raise JsonableError(_("Realm description cannot exceed 100 characters."))+ # Additional validation/error checking beyond types go here, so+ # the entire request can succeed or fail atomically.+ if default_language is not None and default_language not in get_available_language_codes():+ raise JsonableError(_("Invalid language '{language}'").format(language=default_language))# ...```@@ -473,23 +470,38 @@ the request.If the new feature is not in `property_types`, you will need to write codeto call the function you wrote in `actions.py` that updates the database-with the new value. E.g., for `authentication_methods`, we created-`do_set_realm_authentication_methods`, which we will call here:+with the new value. E.g., for `moderation_request_channel`, we created+`do_set_realm_moderation_request_channel`, which we will call here:```python# zerver/views/realm.py# import do_set_realm_authentication_methods from actions.pyfrom zerver.actions.realm_settings import (- do_reactivate_realm,- do_set_realm_authentication_methods,+ # ...+ do_set_realm_moderation_request_channel,# ...)# ...# ...-if authentication_methods is not None and realm.authentication_methods_dict() != authentication_methods:- do_set_realm_authentication_methods(realm, authentication_methods, acting_user=user_profile)- data['authentication_methods'] = authentication_methods+ # Channel-valued settings are not yet fully supported by the+ # property_types framework, and thus have explicit blocks here.+ if moderation_request_channel_id is not None and (+ realm.moderation_request_channel is None+ or realm.moderation_request_channel.id != moderation_request_channel_id+ ):+ new_moderation_request_channel_id = None+ if moderation_request_channel_id >= 0:+ (new_moderation_request_channel_id, sub) = access_stream_by_id(+ user_profile, moderation_request_channel_id, require_content_access=False+ )+ do_set_realm_moderation_request_channel(+ realm,+ new_moderation_request_channel_id,+ moderation_request_channel_id,+ acting_user=user_profile,+ )+ data["moderation_request_channel_id"] = moderation_request_channel_id# ...```@@ -500,119 +512,134 @@ write automated backend tests for your new feature.To test the new setting syncs correctly with the `property_types`framework, one usually just needs to add a line in each of-`test_events.py` and `test_realm.py` with a list of values to switch-between in the test. In the case of a boolean field, no action is-required, because those tests will correctly assume that the only-values to test are `True` and `False`.+`zerver/tests/test_events.py` and `zerver/tests/test_realm.py` with a+list of values to switch between in the test. In the case of a boolean+field, no action is required, because those tests will correctly assume+that the only values to test are `True` and `False`.In `test_events.py`, the function that runs tests for the `property_types`framework is `do_set_realm_property_test`, and in `test_realm.py`, it is`do_test_realm_update_api`.-One still needs to add a test for whether the setting actually-controls the feature it is supposed to control, however (e.g., for this-example feature, whether sending a message without a topic fails with-the setting enabled).+One would still need to add tests for whether the setting actually+controls the feature it is supposed to control. At this time, our example,+`my_fantastic_feature`, does not change any behavior on the backend, so+we don't need to add any additional tests. If you're using this tutorial+as a guide for creating an actual new feature, then at this point you+should add any necessary backend tests.Visit Zulip's [Django testing](../testing/testing-with-django.md)documentation to learn more about the backend testing framework.+:::{tip}++Pick one of the other `Realm.property_types` settings and+use `git-grep` to find examples of backend tests that were written for+that setting: `git grep REALM_SETTING zerver/tests/`.++:::+Also note that you may already need to update the API documentation foryour new feature to pass new or existing backend tests at this point.The tutorial for [writing REST API endpoints](../documentation/api.md)can be a helpful resource, especially the section on [debugging schemavalidation errors](../documentation//api.md#debugging-schema-validation-errors).-### Update the frontend+### What is my fantastic feature?-After completing the process of adding a new feature on the backend,-you should make the required frontend changes: in this case, a checkbox needs-to be added to the admin page (and its value added to the data sent back-to server when a realm is updated) and the change event needs to be-handled on the client.+Since you've now set up the backend for your new fantastic feature, let's+take a moment to discuss what that feature actually will be. Here's where+you get to be creative!-To add the checkbox to the admin page, modify the relevant template in-`web/templates/settings/`, which can be-`organization_permissions_admin.hbs` or `organization_settings_admin.hbs`-(omitted here since it is relatively straightforward).+Think of some fun, visual change that you could make to the Zulip web app+in your development environment. Maybe toggling `my_fantastic_feature` will+change the app font to [Dingbats](https://en.wikipedia.org/wiki/Dingbat).+Maybe it will change the color of the font in the message feed. Maybe it+will make all user status emoji render upside down 🙃. That's up to you!-If you're adding a non-checkbox field, you'll need to specify the type-of the field via the `data-setting-widget-type` attribute in the HTML-template.+The next part of this tutorial will go through the process of setting up+the toggle for turning your feature on and off via the organization+settings admin modal in the web-app. After that, your final challenge will+be to make the changes to the codebase to make your fantastic idea into a+reality in your development environment.-Then add the new form control in `web/src/admin.ts`.+### Update the frontend++After completing the process of adding a new realm setting on the backend,+you'll want make the required frontend changes.++Since we've updated the data sent for a realm to include a new property,+we need to update the `realm_schema` on the frontend to match our changes+in `zerver/lib/events.py`. This can be done in `web/src/state_data.ts`:```diff- // web/src/admin.ts+ // web/src/state_data.ts- export function build_page() {- const options = {- custom_profile_field_types: realm.custom_profile_field_types,- full_name: current_user.full_name,- realm_name: realm.realm_name,- // ...-+ realm_mandatory_topics: realm.realm_mandatory_topics,- // ...+ // Sync this with zerver.lib.events.do_events_register.+ export const realm_schema = z.object({+ // ...+ realm_move_messages_within_stream_limit_seconds: z.nullable(z.number()),++ realm_my_fantastic_feature: z.boolean(),+ realm_name_changes_disabled: z.boolean(),+ // ...```-The JavaScript code for organization settings and permissions can be found in-`web/src/settings_org.ts`.+In order for an admin user to enable and disable our new realm setting, a+checkbox needs to be added to the organization settings page (and its+value added to the data sent back to server when a realm is updated) and+the change event needs to be handled on the client.-In frontend, we have split the `property_types` into three objects:+To add the checkbox to the organization settings admin modal, you'll need+to modify one of the templates for the organization settings modal:+`web/templates/settings/organization...`. If you're adding a non-checkbox+field, you'll need to specify the type of the field via the+`data-setting-widget-type` attribute in the Handlebars template.-- `org_profile`: This contains properties for the "organization- profile" settings page.+For simplicity, let's add the checkbox for `realm_my_fantastic_feature` to+the "Message feed" section in `web/templates/settings/organization_settings_admin.hbs`.+Since there are a number of realm settings controlled via checkbox, there+is a `settings_checkbox` partial template already set up for you to reuse.-- `org_settings`: This contains properties for the "organization- settings" page. Settings belonging to this section generally- decide what features should be available to a user like deleting a- message, message edit history etc. Our `mandatory_topics` feature- belongs in this section.+:::{tip}-- `org_permissions`: This contains properties for the "organization- permissions" section. These properties control security controls- like who can join the organization and whether normal users can- create channels or upload custom emoji.+Use `git-grep` to see where the other realm settings in the+"Message feed" section of that template are in the `web/` directory.-Once you've determined whether the new setting belongs, the next step-is to find the right subsection of that page to put the setting-in. For example in this case of `mandatory_topics` it will lie in-"Compose settings" (`org-compose-settings`) subsection.+Also, if you're not familiar with the organization settings modal, log in+as Iago in your development environment and follow the Zulip help center+instructions for [customizing organization settings](https://zulip.com/help/customize-organization-settings).-_If you're not sure in which section your feature belongs, it's-better to discuss it in-[the Zulip development community](https://zulip.com/development-community/)-before implementing it._+:::-Note that some settings, like `realm_msg_edit_limit_setting`,-require special treatment, because they don't match the common-pattern. We can't extract the property name and compare the value of-such input elements with those in `page_params`, so we have to-manually handle such situations in a couple key functions:+Then add the new form control in `web/src/admin.ts`.-- `settings_org.get_property_value`: This processes the property name- when it doesn't match a corresponding key in `page_params`, and- returns the current value of that property, which we can use to- compare and set the values of corresponding DOM element.+```diff+ // web/src/admin.ts-- `settings_org.update_dependent_subsettings`: This handles settings- whose value and state depend on other elements. For example,- `realm_waiting_period_threshold_custom_input` is only shown for with- the right state of `realm_waiting_period_threshold`.+ export function build_page() {+ const options = {+ custom_profile_field_types: realm.custom_profile_field_types,+ full_name: current_user.full_name,+ // ...++ realm_my_fantastic_feature: realm.realm_my_fantastic_feature,+ // ...+```-Finally, update `server_events_dispatch.js` to handle related events coming from-the server. There is an object, `realm_settings`, in the function-`dispatch_normal_event`. The keys in this object are setting names and the-values are the UI updating functions to run when an event has occurred.+You'll also want to add a label to the `admin_settings_label` object+in that same file. Note that these labels are marked for+[translation](../translating/internationalization.md).-If there is no relevant UI change to make other than in settings page-itself, the value should be `noop` (this is the case for-`mandatory_topics`, since this setting only has an effect on the-backend, so no UI updates are required.).+Finally, update `server_events_dispatch.js` to handle related events+coming from the server. There is an object, `realm_settings`, in the+function `dispatch_normal_event`. The keys in this object are setting+names and the values are the UI updating functions to run when an event+has occurred.-However, if you had written a function to update the UI after a given-setting has changed, your function should be referenced in the-`realm_settings` of `server_events_dispatch.js`. See for example+If there is no relevant UI change to make other than in settings page+itself, the value should be `noop`. However, if you are writing a+function to update the UI after a given setting has changed, your+function should be referenced in the `realm_settings` of+`server_events_dispatch.js`. See for example`settings_emoji.update_custom_emoji_ui`.```diff@@ -626,7 +653,7 @@ setting has changed, your function should be referenced in theadd_custom_emoji_policy: settings_emoji.update_custom_emoji_ui,allow_edit_history: noop,// ...-+ mandatory_topics: noop,++ my_fantastic_feature: ???,// ...};```@@ -638,11 +665,18 @@ The rest of the `dispatch_normal_events` function updates the state of theapplication if an update event has occurred on a realm property and runsthe associated function to update the application's UI, if necessary.-Here are few important cases you should consider when testing your changes:+Now that you've got the admin checkbox set up to toggle your new feature+on and off, you should work on implementing your fantastic idea! Remember+to use `git-grep` to help as you become familiar with the codebase.++### Manually test++Here are few important cases you should consider when manually testing+your changes:- For organization settings where we have a "save/discard" model, makesure both the "Save" and "Discard changes" buttons are working- properly.+ properly when toggling the realm setting.- If your setting is dependent on another setting, carefully checkthat both are properly synchronized. For example, the input element@@ -666,39 +700,34 @@ A great next step is to write frontend tests. There are two types offrontend tests: [node-based unit tests](../testing/testing-with-node.md) and[Puppeteer end-to-end tests](../testing/testing-with-puppeteer.md).-At the minimum, if you created a new function to update UI in-`settings_org.ts`, you will need to mock that function in-`web/tests/dispatch.test.cjs`. Add the name of the UI-function you created to the following object with `noop` as the value:--```js-// web/tests/dispatch.test.cjs--set_global('settings_org', {- update_email_change_display: noop,- update_name_change_display: noop,-});-```+At the minimum, you'll want to update `web/tests/lib/example_realm.cjs`+for the new realm setting that you've added.Beyond that, you should add any applicable tests that verify thebehavior of the setting you just created.+:::{tip}++If you've identified a similar feature on the frontend to the+one that you're creating, use your `git-grep` skills to find and read+through the frontend tests for that feature.++:::+### Update documentation-Nice job! You've added a new feature to Zulip that will improve user-and contributor experiences with the app, which is why it's really-important to make sure that your new feature is well documented.+If you're using this tutorial as a guide to add an actual new feature to+Zulip, it's really important to make sure that your new feature is well+documented.-This example feature adds new functionality that requires messages to-have topics if the setting is enabled. A recommended way to document-this feature would be to update and/or augment Zulip's existing-[help center documentation](https://zulip.com/help/) to reflect your-changes and additions.+A recommended way to document a new feature is to update and/or augment+Zulip's existing [help center documentation](https://zulip.com/help/)+to reflect your changes and additions.At the very least, this will involve modifying (or adding) a Markdown-file documenting the feature in the `help/` directory of the main Zulip-server repository, where the source for Zulip's end user documentation-is stored. Details about writing, editing and testing these Markdown+file documenting the feature in the `starlight_help/` directory of the+main Zulip server repository, where the source for Zulip's end user+documentation is stored. Details about writing, editing and testing thesefiles can be found in:[Writing help center articles](../documentation/helpcenter.md).@@ -713,10 +742,19 @@ documentation is to read more about Zulip's[REST API documentation process](../documentation/api.md)and [OpenAPI configuration](../documentation/openapi.md).-In particular, if there is an API change, **make sure** you document-your new feature in `api_docs/changelog.md` and bump the-`API_FEATURE_LEVEL` in `version.py`. The API feature level allows the+In particular, if there is an API change, you should use the+`create-api-changelog` tool to create a file for the API changelog+entry for your your new feature. The API feature level allows thedevelopers of mobile clients and other tools using the Zulip API toprogrammatically determine whether the Zulip server they areinteracting with supports a given feature; see the[Zulip release lifecycle](../overview/release-lifecycle.md).++### Share your fantastic feature++If you're using this tutorial to learn about the codebase and have+created a fun, fantastic feature, share a screenshot and/or a GIF+from your development environment of your unique changes to the+web-app UI in the Zulip development community's+[new members](https://chat.zulip.org/#topics/channel/95-new-members)+channel!