forkjo/web_src/js/markup/tasklist.js
forgejo-backport-action 118762dd6d [v8.0/forgejo] fix(UI): issue task list numbers, fix #4431 (#4735)
**Backport:** https://codeberg.org/forgejo/forgejo/pulls/4452

## Regexp fixes
This fixes #4431 by adjusting the related regular expressions. Also it allows to have multiple spaces between `-` or `*` and the following brackets.

Related is the following gitea PR: https://github.com/go-gitea/gitea/pull/3296. I wonder a bit why the author stated
> Also fixed the requirement for one character after the blank of - [ ] .

I don't see a reason why
```
- [x]
some task
```
shall not be a valid checkbox without any character after the `]`. E.g., this would render to
- [x]
some task

The third commit fixes this issue.

### Comments
- I wonder a bit why the regexp is written in such complicated way and if
  ```diff
  - (^\s*[-*]\s*\[[\sxX]\])|(
\s*[-*]\s*\[[\sxX]\])
  + (^|
)\s*[-*]\s*\[[\sxX]\]
  ```
  would work the same way. Edit: I tried and indeed the second regex works as expected.
- ~~Why it is actually matching the `\s` and not just the space (` `)? (but OK, no big issue)~~ Edit: `[\t]` is also allowed. Keep it!
- Check boxes in code blocks are counted as well, but I think that this is an edge case which is not a big issue as well.

### Before
![before](https://codeberg.org/attachments/cb4f879d-cdd2-4814-aed2-5de8b5437fb2)
### After
![after](https://codeberg.org/attachments/5d54648f-dd73-4577-9a80-729016219093)

## Javascript fixes
Additionally, while testing I figured out, that currently checkboxes with capital `X` like
```
- [X] another task
```
- [X] another task

cannot be unchecked. Thus, the second commit fixes that issue as well.

## Checklist

The [developer guide](https://forgejo.org/docs/next/developer/) contains information that will be helpful to first time contributors. There also are a few [conditions for merging Pull Requests in Forgejo repositories](https://codeberg.org/forgejo/governance/src/branch/main/PullRequestsAgreement.md). You are also welcome to join the [Forgejo development chatroom](https://matrix.to/#/#forgejo-development:matrix.org).

### Tests

- I added test coverage for Go changes...
  - [ ] in their respective `*_test.go` for unit tests.
  - [x] in the `tests/integration` directory if it involves interactions with a live Forgejo server.
- I added test coverage for JavaScript changes...
  - [ ] in `web_src/js/*.test.js` if it can be unit tested.
  - [ ] in `tests/e2e/*.test.e2e.js` if it requires interactions with a live Forgejo server (see also the [developer guide for JavaScript testing](https://codeberg.org/forgejo/forgejo/src/branch/forgejo/tests/e2e/README.md#end-to-end-tests)).

### Documentation

- [ ] I created a pull request [to the documentation](https://codeberg.org/forgejo/docs) to explain to Forgejo users how to use this change.
- [x] I did not document these changes and I do not expect someone else to do it.

### Release notes

- [ ] I do not want this change to show in the release notes.
- [x] I want the title to show in the release notes with a link to this pull request.
- [ ] I want the content of the `release-notes/<pull request number>.md` to be be used for the release notes instead of the title.

Co-authored-by: Robert Wolff <mahlzahn@posteo.de>
Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/4735
Reviewed-by: Earl Warren <earl-warren@noreply.codeberg.org>
Co-authored-by: forgejo-backport-action <forgejo-backport-action@noreply.codeberg.org>
Co-committed-by: forgejo-backport-action <forgejo-backport-action@noreply.codeberg.org>
2024-07-31 14:16:11 +00:00

90 lines
3.7 KiB
JavaScript

import {POST} from '../modules/fetch.js';
import {showErrorToast} from '../modules/toast.js';
const preventListener = (e) => e.preventDefault();
/**
* Attaches `input` handlers to markdown rendered tasklist checkboxes in comments.
*
* When a checkbox value changes, the corresponding [ ] or [x] in the markdown string
* is set accordingly and sent to the server. On success it updates the raw-content on
* error it resets the checkbox to its original value.
*/
export function initMarkupTasklist() {
for (const el of document.querySelectorAll(`.markup[data-can-edit=true]`) || []) {
const container = el.parentNode;
const checkboxes = el.querySelectorAll(`.task-list-item input[type=checkbox]`);
for (const checkbox of checkboxes) {
if (checkbox.hasAttribute('data-editable')) {
return;
}
checkbox.setAttribute('data-editable', 'true');
checkbox.addEventListener('input', async () => {
const checkboxCharacter = checkbox.checked ? 'x' : ' ';
const position = parseInt(checkbox.getAttribute('data-source-position')) + 1;
const rawContent = container.querySelector('.raw-content');
const oldContent = rawContent.textContent;
const encoder = new TextEncoder();
const buffer = encoder.encode(oldContent);
// Indexes may fall off the ends and return undefined.
if (buffer[position - 1] !== '['.codePointAt(0) ||
buffer[position] !== ' '.codePointAt(0) && buffer[position] !== 'x'.codePointAt(0) && buffer[position] !== 'X'.codePointAt(0) ||
buffer[position + 1] !== ']'.codePointAt(0)) {
// Position is probably wrong. Revert and don't allow change.
checkbox.checked = !checkbox.checked;
throw new Error(`Expected position to be space, x or X and surrounded by brackets, but it's not: position=${position}`);
}
buffer.set(encoder.encode(checkboxCharacter), position);
const newContent = new TextDecoder().decode(buffer);
if (newContent === oldContent) {
return;
}
// Prevent further inputs until the request is done. This does not use the
// `disabled` attribute because it causes the border to flash on click.
for (const checkbox of checkboxes) {
checkbox.addEventListener('click', preventListener);
}
try {
const editContentZone = container.querySelector('.edit-content-zone');
const updateUrl = editContentZone.getAttribute('data-update-url');
const context = editContentZone.getAttribute('data-context');
const contentVersion = editContentZone.getAttribute('data-content-version');
const requestBody = new FormData();
requestBody.append('ignore_attachments', 'true');
requestBody.append('content', newContent);
requestBody.append('context', context);
requestBody.append('content_version', contentVersion);
const response = await POST(updateUrl, {data: requestBody});
const data = await response.json();
if (response.status === 400) {
showErrorToast(data.errorMessage);
return;
}
editContentZone.setAttribute('data-content-version', data.contentVersion);
rawContent.textContent = newContent;
} catch (err) {
checkbox.checked = !checkbox.checked;
console.error(err);
}
// Enable input on checkboxes again
for (const checkbox of checkboxes) {
checkbox.removeEventListener('click', preventListener);
}
});
}
// Enable the checkboxes as they are initially disabled by the markdown renderer
for (const checkbox of checkboxes) {
checkbox.disabled = false;
}
}
}