add UI conventions doc and convo log up to 261030

This commit is contained in:
2026-10-31 19:39:11 -04:00
parent c6ee18c1d3
commit 3d5135c8b8
2 changed files with 582 additions and 0 deletions

View File

@@ -0,0 +1,532 @@
# NearBeach UI Conventions
How to build a new view so it matches the existing NearBeach look, layout and behaviour.
NearBeach has no written style guide. Everything here was taken from the code. When in doubt, copy the reference file listed in each section rather than inventing new markup.
Paths are relative to the `NearBeach/` repo root. Templates live under `NearBeach/templates/NearBeach/`, and Vue components live under `src/js/components/`.
---
## 1. How a page is built
Each page is built in four steps:
1. A Django view renders a thin template.
2. That template mounts one page-level Vue component inside `#app`, passing the data as props.
3. The Vue component draws the UI.
4. Later saves and loads go back to Django as AJAX POSTs.
```
Django view ──► template (extends partials/template.html)
└─ <my-page-component v-bind:...="{{ json }}"> ← compiled in-browser by Vue
└─ Bootstrap card + Naive UI inputs
└─ this.axios.post(`${rootUrl}...`) ──► Django JSON/HTML endpoint
```
### 1.1 Base templates
| Use for | Extend | Container |
|---|---|---|
| Information, new-object and search/list pages (the default) | `partials/template.html` | `.container` (max 1020px) |
| Wide pages (sprint, my planner, GDPR wizard) | `partials/template_wide.html` | `.container-wide` |
| Kanban board (full width, no version footer) | `partials/template_wide_empty_footer.html` | `.container-wide` |
| Public, unauthenticated share pages | `partials/template_public.html` | — |
A page only overrides `{% block content %}`. The base template already provides these:
- the navbar (`partials/header.html`)
- the loading splash (`partials/simple_loader.html`)
- `<render-toasts>` for notifications
- the JS bundle (`partials/footer.html`)
- a "Permission denied" fallback for anonymous users
`partials/template.html`:
```django
{% extends "NearBeach/master.html" %}
{% block template %}
<main class="container" role="main">
<div id="app">
{% if user.is_authenticated %}
{% block content %}{% endblock %}
{% else %} ...Permission denied... {% endif %}
<render-toasts></render-toasts>
</div>
</main>
{% endblock %}
```
### 1.2 Template patterns
**Information page.** The object's component goes first, then a spacer, then the shared tab modules. Reference: `requirements/requirement_information.html` (others use `<br/>` instead of the spacer div).
```django
{% extends "NearBeach/partials/template.html" %}
{% load static %}
{% block content %}
<requirement-information
v-bind:requirement-is-closed="{{ requirement_is_closed }}"
v-bind:requirement-results="{{requirement_results}}"
v-bind:status-options="{{status_options}}"
v-bind:theme="`{{ theme }}`"
v-bind:user-level="{{user_level}}"
></requirement-information>
<div class="spacer"></div>
<parent-modules
v-bind:destination="'requirement'"
v-bind:is-read-only="{{ requirement_is_closed }}"
v-bind:location-id="{{requirement_id}}"
v-bind:user-level="{{ user_level }}"
v-bind:user-extra-permissions="{{ user_extra_permissions }}"
v-bind:root-url="`{% url 'dashboard' %}`"
v-bind:static-url="`{% static '/' %}`"
v-bind:theme="`{{ theme }}`"
></parent-modules>
{% endblock %}
```
**New-object page.** References: `tasks/new_task.html` (full) and `organisations/new_organisations.html` (minimal).
**Search/list page.** Reference: `search/search_organisations.html`.
```django
{% block content %}
<search-organisations v-bind:organisation-results="{{organisation_results}}"
v-bind:root-url="`{% url 'dashboard' %}`"
v-bind:static-url="`{% static '/' %}`"
></search-organisations>
{% endblock %}
```
### 1.3 Passing Django data into props
The browser compiles everything inside `#app` as a Vue template. That makes each `v-bind:` value a JavaScript expression.
| Data | Syntax |
|---|---|
| Object or list (from `serializers.serialize` or `json.dumps`) | `v-bind:task-results="{{task_results}}"` |
| String from Django | backtick literal: ``v-bind:theme="`{{ theme }}`"``, ``v-bind:root-url="`{% url 'dashboard' %}`"``, ``v-bind:static-url="`{% static '/' %}`"`` |
| Fixed string | `v-bind:destination="'task'"` |
| Integer | `v-bind:location-id="{{task_id}}"` |
| Boolean | The view sets the string `"true"` or `"false"`, then: `v-bind:is-read-only="{{ task_is_closed }}"` |
Prop names are kebab-case in the template and camelCase in the component.
> ⚠️ **Never put raw user text inside a `v-bind` expression.** Django's escaping is undone by the browser before Vue reads the expression, so a stray quote can break out of the string and run as code. If a page must echo user input, serialise it with `json.dumps` in the view, or pass it some other way. `search/search.html` currently does `v-bind:search-input="'{{search_input}}'"`, which is unsafe; do not copy it.
---
## 2. Django view conventions
Reference: `task_information` in `NearBeach/views/task_views.py`.
```python
@login_required(login_url="login", redirect_field_name="")
@check_specific_object_permissions(min_permission_level=1, object_lookup="task")
def task_information(request, task_id, *args, **kwargs):
t = loader.get_template("NearBeach/tasks/task_information.html")
...
c = {
"nearbeach_title": f"Task Information {task_id}", # sets <title>
"need_tinymce": True, # loads the TinyMCE script in <head>
"status_options": json.dumps(list(status_options), cls=DjangoJSONEncoder),
"task_id": task_id,
"task_is_closed": task_is_closed, # "true"/"false" string
"task_results": serializers.serialize("json", [task_results]),
"theme": get_theme(request), # NearBeach/views/theme_views.py
"user_extra_permissions": get_user_group_permission(request.user, ["document", "task_note"]),
"user_level": kwargs["user_level"], # injected by the permission decorator
}
return HttpResponse(t.render(c, request))
```
**Context keys every page should set:**
- `nearbeach_title`
- `need_tinymce`
- `theme`
- `user_level`, when the page is permission-gated
**Decorator order** (outermost first). The permission decorators add `user_level` to kwargs, so views must accept `*args, **kwargs`.
```python
@require_http_methods(["POST"]) # only on POST/AJAX endpoints
@login_required(login_url="login", redirect_field_name="")
@check_specific_object_permissions(min_permission_level=2, object_lookup="task")
```
**Permission levels:**
- 1 = read
- 2 = edit/save
- 3 = create
- 4 = delete/admin (superusers always get 4)
The decorators live in `NearBeach/decorators/check_user_permissions/`.
**URL names** (in `NearBeach/urls.py`). URLs are flat, and each `name` matches its path:
| Page | URL path | URL name |
|---|---|---|
| New-object page | `new_task/` | `new_task` |
| Its save endpoint | `new_task/save/` | `new_task_save` |
| Information page | `task_information/<int:task_id>/` | `task_information` |
| Its sub-actions | `task_information/<id>/save/` | — |
| Search page | `search/organisation/` | `search_organisation` |
| Search data endpoint (POST, returns JSON) | `search/organisation/data/` | `search_organisation_data` |
---
## 3. Navigation
The navbar in `partials/header.html` is hard-coded and has no registry. To make a new page reachable, add a `<li><a class="dropdown-item" href="{% url '...' %}">` to the right dropdown:
- **New Object** for `new_*` pages
- **Find Objects** for `search*` pages
- **Schedule**
- **Administration** (wrapped in a superuser check)
- **User**
The navbar is always dark (`navbar-dark bg-dark`), whatever the user's theme.
---
## 4. Vue component structure
All components use the **Options API**. None use `<script setup>`. `setup()` appears only for `return { v$: useVuelidate() }`.
### 4.1 Page skeleton
References: `projects/ProjectInformation.vue`, `requirements/RequirementInformation.vue` and `projects/NewProject.vue`.
```vue
<template>
<n-config-provider :theme="useNBTheme(theme)">
<div class="card">
<div class="card-body project-border"> <!-- object colour stripe, see §7 -->
<h1>Project Information</h1>
<hr/>
<div v-if="projectIsClosed" class="alert alert-info">
Project is currently closed
</div>
<!-- One section = explanation on the left, fields on the right -->
<div class="row">
<div class="col-md-4">
<h2>Description</h2> <!-- or <strong> for minor sections -->
<p class="text-instructions">
Edit the project information and then click the "Update Project" button...
</p>
</div>
<div class="col-md-8">
<div class="form-group">
<label>Project Name
<validation-rendering :error-list="v$.projectNameModel.$errors"></validation-rendering>
</label>
<input v-model="projectNameModel" type="text" class="form-control" :disabled="isReadOnly"/>
</div>
</div>
</div>
<hr/>
<!-- Status/priority style: text col-md-4 + two col-md-4 selects -->
<div class="row">
<div class="col-md-4"><strong>Status</strong><p class="text-instructions">...</p></div>
<div class="col-md-4">
<label>Status</label>
<n-select v-model:value="projectStatusModel" :options="statusOptions" :disabled="isReadOnly"/>
</div>
<div class="col-md-4">...</div>
</div>
<!-- Save row -->
<hr v-if="!isReadOnly"/>
<div v-if="!isReadOnly" class="row submit-row">
<div class="col-md-12">
<button class="btn btn-primary save-changes" @click="updateProject">Update Project</button>
</div>
</div>
</div>
</div>
</n-config-provider>
</template>
```
**Rules:**
- Header text is `"<Object> Information"`, `"New <Object>"` or `"Search <Objects>"`, followed by `<hr/>`.
- Sections are separated by `<hr/>`. Use `col-md-4` for headings and instructions and `col-md-8` for fields; a row of two inputs uses `col-md-4` + `col-md-4` + `col-md-4`.
- Name the v-model data fields `xxxModel` (`projectNameModel`).
- The save button sits at the bottom, full row, as `btn btn-primary save-changes`. It is labelled "Update X" or "Save X".
### 4.2 Script skeleton
```js
import {mapGetters} from "vuex";
import {NSelect} from "naive-ui";
import {useVuelidate} from "@vuelidate/core";
import {required} from "@vuelidate/validators";
import ValidationRendering from "Components/validation/ValidationRendering.vue";
import {useNBTheme} from "Composables/theme/useNBTheme";
export default {
name: "ProjectInformation", // matches the file name
components: { NSelect, ValidationRendering },
props: {
projectResults: { type: Array, default: () => [] },
theme: { type: String, default: "" },
userLevel: { type: Number, default: 0 },
rootUrl: { type: String, default: "/" }, // needed if no <parent-modules> on the page
staticUrl: { type: String, default: "/" },
},
setup() { return { v$: useVuelidate() }; },
data() {
return {
isReadOnly: false,
projectNameModel: this.projectResults[0].fields.project_name, // Django serialiser shape
};
},
computed: {
...mapGetters({ rootUrl: "getRootUrl", staticUrl: "getStaticUrl", skin: "getSkin", contentCss: "getContentCss" }),
},
validations: { projectNameModel: { required } },
async beforeMount() {
await this.$store.dispatch("processThemeUpdate", { theme: this.theme });
},
mounted() {
this.$store.commit({ type: "updateUrl", rootUrl: this.rootUrl, staticUrl: this.staticUrl });
this.$store.commit({ type: "updateUserLevel", userLevel: this.userLevel });
this.setReadOnly();
},
methods: {
useNBTheme, // composables are exposed via methods
setReadOnly() {
if (/* status is closed */) { this.isReadOnly = true; return; }
if (this.userLevel <= 1) this.isReadOnly = true;
},
},
};
```
**Lifecycle and data rules:**
- **Theme:** `beforeMount` dispatches `processThemeUpdate`, which sets the TinyMCE skin and content CSS in Vuex.
- **Store setup:** `mounted` commits `updateUrl` and `updateUserLevel`. `ProjectInformation.vue` skips this because `<parent-modules>` on the same page commits them. **Any standalone page must commit them itself.** See `NewProject.vue`.
- **Read-only:** a page is read-only when the object's status is closed (`*_higher_order_status === "Closed"`) or when `userLevel <= 1`. Every input binds `:disabled="isReadOnly"`, and the save row is hidden.
- **Incoming data:** it arrives in Django-serialiser shape, `[{ model, pk, fields: {...} }]`, so read it as `xResults[0].fields.x_name` and `xResults[0].pk`.
---
## 5. Which library for which element
| Element | Use | Notes |
|---|---|---|
| Layout, cards, grid, text inputs, buttons, alerts, tables, pagination, tabs, modals, toasts | **Bootstrap 5** classes | `form-control`, `btn btn-primary`, `card`, `row/col-md-*`, `table`, `alert alert-info` |
| Dropdowns / multi-selects | **Naive UI** `n-select` | `v-model:value`, `:options` = `[{label, value}]` |
| Dates and datetimes | `<between-dates>` (`dates/BetweenDates.vue`) for start/end pairs, otherwise `n-date-picker type="datetime"` | Values are millisecond timestamps |
| Numbers / toggles / colours | `n-input-number`, `n-switch`, `n-color-picker` | |
| Rich text | TinyMCE `<editor>` (`@tinymce/tinymce-vue`) | Set `need_tinymce: True` in the view |
| Icons | `src/js/components/icons/Carbon*.vue`, `Mdi*.vue` | Import locally and use as `<carbon-information>` |
Import Naive UI components locally in each component (`import {NSelect} from "naive-ui"`). Don't use Naive UI for layout, buttons, messages or notifications.
**Standard TinyMCE block.** The placeholder image shows until the editor loads.
```vue
<img :src="`${staticUrl}NearBeach/images/placeholder/body_text.svg`" class="loader-image" alt="loading image for Tinymce"/>
<editor
v-model="projectDescriptionModel"
license-key="gpl"
:init="{
license_key: 'gpl', height: 500, menubar: false, paste_data_images: true, relative_urls: false,
images_upload_handler: useUploadImage,
plugins: ['lists', 'image', 'codesample', 'table'],
toolbar: 'undo redo | blocks | bold italic strikethrough underline backcolor | alignleft aligncenter ' +
'alignright alignjustify | bullist numlist outdent indent | removeformat | table image codesample',
skin: `${skin}`, content_css: `${contentCss}`,
}"
:disabled="isReadOnly"
/>
```
Copy the exact `toolbar` string from `ProjectInformation.vue`. On new-object pages:
- use `useNewObjectUploadImage` as the upload handler
- pass the description through `useReplaceIncorrectImageUrl` before submitting
---
## 6. Shared building blocks to reuse
| Need | Reuse |
|---|---|
| Tabs under an object (groups, documents, links, notes, tags, sprints, delete) | `<parent-modules>` (`modules/ParentModules.vue`); sub-modules live in `modules/sub_modules/` |
| Modal dialog | Copy a wizard from `modules/wizards/`, e.g. `AddTagWizard.vue` |
| Form validation messages | `validation/ValidationRendering.vue` with Vuelidate |
| Object result cards / tables | `render/RenderObjectCard.vue`, `render/RenderObjectTable.vue` |
| Search results with pagination | `search/ListSearchResults.vue` with `composables/pagintation/getSetOfPages.js` |
| Date formatting | `composables/datetime/useNiceDate.js`, `useNiceDatetime.js` |
| Image uploads in the editor | `composables/uploads/*` |
| Light/dark switch for Naive UI | `composables/theme/useNBTheme.js` |
| Shared state | Vuex (`src/js/vuex-store.js` with modules in `src/js/vuex/`); read via `mapGetters`, write via `this.$store.commit({type, ...})` |
**Modal pattern** (Bootstrap, not Naive UI):
```vue
<div id="addTagModal" class="modal fade" tabindex="-1" aria-hidden="true">
<div class="modal-dialog"><div class="modal-content">
<div class="modal-header">
<h2>Add Tags Wizard</h2>
<button id="addTagsCloseButton" type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body"><!-- same col-md-4 / col-md-8 rows --></div>
<div class="modal-footer">
<button class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button class="btn btn-primary" @click="save">Add</button>
</div>
</div></div>
</div>
```
- **Open:** `import {Modal} from "bootstrap"; new Modal(document.getElementById("addTagModal")).show();`
- **Close:** `document.getElementById("addTagsCloseButton").click();`
- Put modals at the bottom of the page component's card.
---
## 7. HTTP calls and user feedback
**Requests.** Use the global `this.axios`, which `app.js` sets up with the CSRF cookie and header. Don't import axios directly.
Send a POST with a `FormData` body to a URL built from `rootUrl`:
```js
const data_to_send = new FormData();
data_to_send.set("project_name", this.projectNameModel);
data_to_send.set("project_end_date", this.projectEndDateModel.toISOString());
// lists: data_to_send.append("tag_list", id) per item
this.$store.dispatch("newToast", {
header: "Project Currently Saving", message: "Please wait whilst we save the project",
extra_classes: "bg-warning text-dark", unique_type: "save", delay: 0,
});
this.axios.post(`${this.rootUrl}project_information/${this.projectResults[0].pk}/save/`, data_to_send)
.then(() => {
this.$store.dispatch("newToast", {
header: "Project Saved", message: "Project Saved",
extra_classes: "bg-success", unique_type: "save",
});
})
.catch((error) => {
this.$store.dispatch("newToast", {
header: "Project Could not save",
message: `There was an error saving the project. Error -> ${error}`,
extra_classes: "bg-danger", unique_type: "save", delay: 0,
});
});
```
**Toast rules:**
- **While saving:** `bg-warning text-dark`.
- **On success:** `bg-success`.
- **On error:** `bg-danger`.
- **`delay: 0`** keeps the toast on screen. The default is 20 seconds.
- **The same `unique_type`** makes a new toast replace the previous one.
**Other feedback:**
- **Validate first:** `if (!(await this.v$.$validate())) return;`
- **New-object pages:** disable the submit button while sending (`:disabled="disableSubmitButton"`). On success, go to the URL the server returns: `window.location.href = response.data`.
- **Loading:** the page-level splash loader is handled by `app.js`. There are no spinners; don't add `n-spin`.
---
## 8. Styling and theming
**Light/dark:**
- `master.html` sets `<html data-bs-theme="{{ theme }}">`.
- `src/sass/themes/_light_theme.scss` and `_dark_theme.scss` override the Bootstrap `--bs-*` variables and define NearBeach tokens, e.g. `--nb-background-color`, `--nb-text-instructions` and `--nb-object-card--border`.
- Naive UI follows the same theme through `useNBTheme(theme)` on `<n-config-provider>`.
**Rules:**
- **No hard-coded colours.** Add a new `--nb-*` token to **both** theme files and use `var(--nb-...)`.
- **New styles** go in a new partial `src/sass/components/_my_feature.scss`, imported in `src/sass/main.scss`.
- **Existing styles to rely on:**
- `.text-instructions` (lighter, muted help text)
- `.card h1` / `.card h2` sizes and the green `.card hr` from `components/_cards.scss`
- `.spacer` from `components/_body.scss`
- the object border stripes `.project-border`, `.task-border`, `.requirement-border`, etc., from `components/_project.scss`, etc.
- **New object types** get their own `.<object>-border` class.
---
## 9. Registering the component and building
A page-level component needs three changes to be usable in a template:
1. `src/js/components.js`: add an async export in alphabetical order.
```js
MyFeature = defineAsyncComponent(() =>
import(
/* webpackChunkName: "my-feature" */
"./components/my_feature/MyFeature.vue"
)
),
```
2. `src/js/app.js`: add `MyFeature` to the import list from `./components`.
3. `src/js/app.js`: add `MyFeature` to `createApp({ components: { ... } })`.
Child components are registered locally in the parent's `components: {}`.
**Naming:**
- **Files:** PascalCase, in a domain folder (`src/js/components/<domain>/XxxInformation.vue`, `NewXxx.vue`, `SearchXxx.vue`).
- **Template tags:** kebab-case.
- **Custom events:** snake_case (`@update_dates`).
- **Import aliases:** `Components/`, `Composables/` and `Modules/`.
**Build:** `npm run watch` for development, `npm run prod` for release. The bundles are written to `NearBeach/static/NearBeach/`.
---
## 10. Tests
- **Unit tests (Vitest):** put them in `tests/unit/<domain>/MyFeature.unit.js`. The `.unit.js` suffix is required, or Vitest won't pick the file up. Run with `npm run unit-test`.
```js
import { describe, expect, test } from "vitest";
import {mount} from "@vue/test-utils";
import MyFeature from "/src/js/components/my_feature/MyFeature.vue";
import { store } from "/src/js/vuex-store";
const axios = require("axios");
describe("MyFeature.vue - rendering component", () => {
const wrapper = mount(MyFeature, {
props: { theme: "light", userLevel: 4 /* + Django-shaped result arrays */ },
global: { plugins: [store], mocks: { axios } },
});
test("renders header", () => { expect(wrapper.text()).toContain("My Feature"); });
});
```
The existing tests are mostly mount-only smoke tests. Prefer real assertions.
- **Backend view tests:** under `NearBeach/tests/` (`tests_views`, `tests_user_permissions`). Run with `python manage.py test`.
- **End-to-end tests (Playwright):** `tests/e2e/`.
---
## 11. New-view checklist
- [ ] **View:** `loader.get_template` + context with `nearbeach_title`, `need_tinymce`, `theme`, `user_level`.
- [ ] **Decorators:** `login_required`, then the right permission decorator at the right level; add `require_http_methods(["POST"])` on save endpoints.
- [ ] **URLs:** names follow `new_x` / `x_information` / `search/x/` (§2).
- [ ] **Template:** extends `partials/template.html` (or `template_wide.html`) and fills only `{% block content %}`.
- [ ] **Props:** passed with the right syntax (§1.3); no raw user text inside `v-bind`.
- [ ] **Component layout:** Options API, `n-config-provider` → `card` → `card-body <object>-border` → `<h1>` + `<hr/>`.
- [ ] **Sections:** `col-md-4` instructions + `col-md-8` fields, separated by `<hr/>`.
- [ ] **Inputs:** Bootstrap for text inputs and buttons; Naive UI for selects, dates and numbers; TinyMCE for rich text.
- [ ] **Read-only:** closed status or `userLevel <= 1`; inputs disabled and save row hidden.
- [ ] **Lifecycle:** `processThemeUpdate` in `beforeMount`; `updateUrl` and `updateUserLevel` in `mounted` (unless `<parent-modules>` does it).
- [ ] **Save:** POST with FormData via `this.axios`, toasts for saving/success/error with `unique_type`, Vuelidate before submitting.
- [ ] **Reuse:** existing modules, wizards, render components and composables before writing new ones.
- [ ] **Styling:** colours only via `--nb-*` tokens defined in both theme files; partial imported in `main.scss`.
- [ ] **Registration:** registered in `components.js` and both lists in `app.js`.
- [ ] **Navigation:** link added to the right navbar dropdown in `partials/header.html`.
- [ ] **Tests:** `tests/unit/<domain>/X.unit.js` added; Django view test added.
- [ ] **Visual check:** checked in both **light and dark** themes, and as a level-1 (read-only) user.
---
## 12. Quirks in the current code: know them, don't copy them
- **`.container-wide`:** used by the wide templates, but it has no rule in `src/sass`, so wide pages get default `main` styling.
- **Missing titles:** some views leave out `nearbeach_title` (e.g. `search_tag`), so the browser tab title is empty. Always set it.
- **Unneeded TinyMCE:** some views set `need_tinymce: True` without using an editor (e.g. `search_organisation`). Set it only when needed.
- **Inconsistent quoting:** string props sometimes use `'{{ x }}'` and sometimes backticks. Use backticks for server-generated strings, and never quote user input this way (§1.3).
- **Spacing between the info card and modules:** sometimes `<br/>`, sometimes `<div class="spacer">`. Prefer `.spacer`.
- **Store setup:** some page components rely on a sibling component to commit `updateUrl`. New components should commit what they need themselves.