patx/gitman

Add contributor chips with autocomplete and enable Save only for changes

Commit 505526d · patx · Nov 4 at 2:51AM

Changeset
505526d957a99825f0b029f845d5cb0e7fb83352
Parents
365e2c733d3d1c6ede3ac2217db3d348007bcec1

View source at this commit

Comments

No comments yet.

Log in to comment

Diff

diff --git a/app.py b/app.py
index 68b08da..5efd739 100644
--- a/app.py
+++ b/app.py
@@ -2562,24 +2562,37 @@ def delete_repository(repo, path):
 
 
 def add_repo_contributor(repo, added_by, username):
-    username = (username or "").strip().lower()
-    contributor = get_user_by_username(username)
-    if not contributor:
-        raise ValueError("User not found.")
-    if contributor["id"] == repo["owner_id"]:
-        raise ValueError("The owner already has access.")
+    return add_repo_contributors(repo, added_by, [username])
+
+
+def add_repo_contributors(repo, added_by, usernames):
+    usernames = list(dict.fromkeys(
+        name.lstrip("@").lower()
+        for value in usernames for name in re.split(r"[\s,]+", value.strip()) if name
+    ))
+    if not usernames:
+        raise ValueError("Choose at least one contributor.")
+    if len(usernames) > 50:
+        raise ValueError("Add up to 50 contributors at a time.")
     now = utcnow()
     with db_connect() as conn:
+        contributors = []
+        for username in usernames:
+            contributor = conn.execute("SELECT id FROM users WHERE username = ?", (username,)).fetchone()
+            if not contributor:
+                raise ValueError(f"User @{username} not found.")
+            if contributor["id"] == repo["owner_id"]:
+                raise ValueError("The owner already has access.")
+            if conn.execute("SELECT 1 FROM repo_contributors WHERE repo_id = ? AND user_id = ?", (repo["id"], contributor["id"])).fetchone():
+                raise ValueError(f"@{username} is already a contributor.")
+            contributors.append((repo["id"], contributor["id"], added_by["id"], now))
         try:
-            conn.execute(
-                """
-                INSERT INTO repo_contributors (repo_id, user_id, added_by_id, created_at)
-                VALUES (?, ?, ?, ?)
-                """,
-                (repo["id"], contributor["id"], added_by["id"], now),
+            conn.executemany(
+                "INSERT INTO repo_contributors (repo_id, user_id, added_by_id, created_at) VALUES (?, ?, ?, ?)",
+                contributors,
             )
         except sqlite3.IntegrityError as exc:
-            raise ValueError("User is already a contributor.") from exc
+            raise ValueError("A selected user is already a contributor.") from exc
     sync_repo_git_config(repo)
 
 
@@ -5484,9 +5497,10 @@ def repo_settings(owner, repo_name):
         redirect(f"/{owner}")
 
     if action == "add_contributor":
-        contributor_username = request.forms.get("username", "").strip()
+        contributor_usernames = request.forms.getall("username")
+        contributor_username = " ".join(contributor_usernames)
         try:
-            add_repo_contributor(repo, user, contributor_username)
+            add_repo_contributors(repo, user, contributor_usernames)
             redirect(f"/{owner}/{repo_name}/settings")
         except ValueError as exc:
             return render_repo_settings_page(repo, path, contributor_username=contributor_username, error=str(exc))
diff --git a/static/contributor-picker.js b/static/contributor-picker.js
new file mode 100644
index 0000000..79791f9
--- /dev/null
+++ b/static/contributor-picker.js
@@ -0,0 +1,99 @@
+(() => {
+  document.querySelectorAll('[data-username-picker]').forEach((picker) => {
+    const input = picker.querySelector('input[data-username-autocomplete]');
+    const form = picker.closest('form');
+    const status = form.querySelector('[data-username-picker-status]');
+    const chips = new Map();
+    const existing = new Set([picker.dataset.owner, ...picker.dataset.existing.split(',')]);
+    let selected = null;
+    const deselect = () => {
+      selected?.classList.remove('chip-selected');
+      selected = null;
+    };
+    const changed = () => input.dispatchEvent(new Event('input', { bubbles: true }));
+    const add = (value) => {
+      const username = value.trim().replace(/^@/, '').toLowerCase();
+      if (!username) return false;
+      if (!/^[a-z0-9][a-z0-9._-]{0,62}$/.test(username)) {
+        status.textContent = 'Enter a username or choose a suggestion.';
+        return false;
+      }
+      if (existing.has(username)) {
+        status.textContent = `@${username} already has access.`;
+        return false;
+      }
+      if (!chips.has(username)) {
+        const chip = document.createElement('span');
+        chip.className = 'username-chip';
+        chip.dataset.username = username;
+        const name = document.createElement('span');
+        name.textContent = `@${username}`;
+        const hidden = document.createElement('input');
+        hidden.type = 'hidden';
+        hidden.name = 'username';
+        hidden.value = username;
+        const remove = document.createElement('button');
+        remove.type = 'button';
+        remove.className = 'username-chip-remove';
+        remove.setAttribute('aria-label', `Remove @${username}`);
+        remove.textContent = '×';
+        remove.addEventListener('click', () => {
+          chip.remove();
+          chips.delete(username);
+          deselect();
+          status.textContent = `Removed @${username} from the selection.`;
+          input.focus();
+        });
+        chip.append(name, hidden, remove);
+        picker.insertBefore(chip, input);
+        chips.set(username, chip);
+      }
+      input.value = '';
+      changed();
+      status.textContent = `${chips.size} ${chips.size === 1 ? 'user' : 'users'} selected. Choose Add contributors to give them access.`;
+      return true;
+    };
+    input.addEventListener('username-selected', (event) => add(event.detail));
+    input.addEventListener('input', deselect);
+    input.addEventListener('blur', deselect);
+    input.addEventListener('keydown', (event) => {
+      if (event.defaultPrevented || event.isComposing) return;
+      if ([' ', 'Enter', ','].includes(event.key)) {
+        event.preventDefault();
+        if (input.value.trim()) add(input.value);
+      } else if (event.key === 'Backspace' && !input.value) {
+        const last = Array.from(chips.values()).pop();
+        if (!last) return;
+        event.preventDefault();
+        if (selected !== last) {
+          deselect();
+          selected = last;
+          last.classList.add('chip-selected');
+          status.textContent = `@${last.dataset.username} selected. Press Backspace again to edit.`;
+        } else {
+          const username = last.dataset.username;
+          last.remove();
+          chips.delete(username);
+          deselect();
+          input.value = username;
+          changed();
+          status.textContent = `Editing @${username}.`;
+        }
+      } else {
+        deselect();
+      }
+    });
+    form.addEventListener('submit', (event) => {
+      if ((input.value.trim() && !add(input.value)) || !chips.size) {
+        event.preventDefault();
+        if (!input.value.trim()) status.textContent = 'Choose at least one contributor.';
+        input.focus();
+      }
+    });
+    const initial = input.value.trim();
+    if (initial) {
+      input.value = '';
+      initial.split(/[\s,]+/).forEach(add);
+    }
+  });
+})();
diff --git a/static/mentions.js b/static/mentions.js
index 0670c0b..61c34aa 100644
--- a/static/mentions.js
+++ b/static/mentions.js
@@ -1,5 +1,6 @@
 (() => {
-  document.querySelectorAll('[data-mentions]').forEach((input, fieldIndex) => {
+  document.querySelectorAll('[data-mentions], [data-username-autocomplete]').forEach((input, fieldIndex) => {
+    const usernameOnly = input.hasAttribute('data-username-autocomplete');
     const menu = document.createElement('div');
     menu.className = 'repo-search-menu mention-menu';
     menu.id = `mention-options-${fieldIndex}`;
@@ -11,6 +12,7 @@
     input.setAttribute('aria-autocomplete', 'list');
     input.setAttribute('aria-controls', menu.id);
     input.setAttribute('aria-expanded', 'false');
+    if (usernameOnly) input.setAttribute('role', 'combobox');
 
     let results = [];
     let activeIndex = -1;
@@ -20,6 +22,10 @@
     let controller;
 
     const currentToken = () => {
+      if (usernameOnly) {
+        const query = input.value.trim().replace(/^@/, '');
+        return query ? { query, start: 0, end: input.value.length } : null;
+      }
       const caret = input.selectionStart;
       if (caret === null || caret !== input.selectionEnd) return null;
       const match = input.value.slice(0, caret).match(/(?:^|[^\w@/\\])@([a-z0-9._-]{0,63})$/i);
@@ -70,6 +76,14 @@
       const current = currentToken();
       const user = results[index];
       if (!user || !current || !token || current.start !== token.start || current.query !== token.query) return;
+      if (usernameOnly) {
+        input.focus();
+        input.value = user.username;
+        input.dispatchEvent(new Event('input', { bubbles: true }));
+        close();
+        input.dispatchEvent(new CustomEvent('username-selected', { detail: user.username }));
+        return;
+      }
       const suffix = input.value.slice(current.end);
       const replacement = `@${user.username}${!suffix || !/^[\s.,;:!?)}\]]/.test(suffix) ? ' ' : ''}`;
       if (input.maxLength > 0 && input.value.length - (current.end - current.start) + replacement.length > input.maxLength) return;
diff --git a/static/save-on-change.js b/static/save-on-change.js
new file mode 100644
index 0000000..b8d1cbb
--- /dev/null
+++ b/static/save-on-change.js
@@ -0,0 +1,24 @@
+(() => {
+  document.querySelectorAll('form[data-save-on-change]').forEach((form) => {
+    const controls = Array.from(form.elements).filter((field) => field.name && !['hidden', 'submit', 'button'].includes(field.type));
+    const buttons = Array.from(form.querySelectorAll('button[type="submit"]'));
+    const value = (field, initial = false) => {
+      if (field.type === 'checkbox' || field.type === 'radio') return initial ? field.defaultChecked : field.checked;
+      if (field.tagName === 'SELECT') {
+        const options = Array.from(field.options).filter((option) => initial ? option.defaultSelected : option.selected);
+        return options.map((option) => option.value);
+      }
+      return initial ? field.defaultValue : field.value;
+    };
+    const initial = JSON.stringify(controls.map((field) => value(field, true)));
+    const sync = () => {
+      const unchanged = JSON.stringify(controls.map((field) => value(field))) === initial;
+      buttons.forEach((button) => { button.disabled = unchanged; });
+    };
+    form.addEventListener('input', sync);
+    form.addEventListener('change', sync);
+    form.addEventListener('reset', () => requestAnimationFrame(sync));
+    window.addEventListener('pageshow', sync);
+    sync();
+  });
+})();
diff --git a/static/styles.css b/static/styles.css
index cc7b12b..c6ab8a5 100644
--- a/static/styles.css
+++ b/static/styles.css
@@ -139,6 +139,7 @@ button:active, .button:active {
 .button.danger { background: #b91c1c; color: #ffffff; }
 .button.danger:hover { background: #991b1b; }
 .button.danger:active { background: #7f1d1d; color: #ffffff; }
+button:disabled, .button:disabled { background: var(--chip); color: var(--muted); opacity: .55; cursor: not-allowed; }
 
 form button[type="submit"] { justify-self: start; }
 
@@ -536,6 +537,14 @@ th { color: var(--ink); font-weight: 700; }
 .settings-card > form { margin-block: 1.25rem; }
 .settings-card > form > div > :last-child { margin-bottom: 0; }
 .contributor-row { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: .75rem 1rem; }
+.username-picker { display: flex; flex-wrap: wrap; align-items: center; gap: .5rem; padding: .75rem; border: 1px solid var(--surface-border); border-radius: 8px; background: var(--surface); }
+.username-picker:focus-within { outline: 2px solid var(--ink); outline-offset: 2px; }
+.username-picker > input { flex: 1 1 12rem; min-width: 0; width: auto; padding: .375rem; border: 0; outline: none; background: transparent; }
+.username-chip { display: inline-flex; align-items: center; gap: .5rem; max-width: 100%; padding: .375rem .625rem; border-radius: 999px; background: var(--chip); color: var(--ink); overflow-wrap: anywhere; }
+.username-chip small { color: var(--muted); }
+.username-chip.chip-selected { outline: 2px solid var(--ink); outline-offset: 1px; }
+.username-chip-remove { flex: 0 0 24px; width: 24px; height: 24px; min-height: 0; padding: 0; background: transparent; color: var(--ink); line-height: 1; }
+[data-username-picker-status]:empty { display: none; }
 .settings-back { display: flex; flex-wrap: wrap; gap: 1rem; justify-content: space-between; margin-top: 1.5rem; }
 
 .mention-menu {
diff --git a/templates/base.tpl b/templates/base.tpl
index 807da50..9c43fe6 100644
--- a/templates/base.tpl
+++ b/templates/base.tpl
@@ -90,7 +90,11 @@
   <footer class="colophon">
     <p>© {{time.strftime("%Y")}} GitMan</p>
   </footer>
-  <script src="/static/mentions.js?v=1" defer></script>
+  <script src="/static/mentions.js?v=2" defer></script>
+  % if user:
+    <script src="/static/contributor-picker.js?v=1" defer></script>
+    <script src="/static/save-on-change.js?v=1" defer></script>
+  % end
   % if user:
     <script src="/static/notifications.js?v=2" defer></script>
     <script src="/static/repo-search.js?v=1" defer></script>
diff --git a/templates/edit_profile.tpl b/templates/edit_profile.tpl
index e81df14..bb460aa 100644
--- a/templates/edit_profile.tpl
+++ b/templates/edit_profile.tpl
@@ -5,7 +5,7 @@
   <div class="settings-cards">
     <section class="settings-card" aria-labelledby="profile-settings-title">
       <h2 id="profile-settings-title">Profile settings</h2>
-      <form method="post" action="/settings">
+      <form method="post" action="/settings" data-save-on-change>
         {{!csrf_field()}}
         <label>
           Display name
diff --git a/templates/repo_settings.tpl b/templates/repo_settings.tpl
index a5cbd6c..5b728e1 100644
--- a/templates/repo_settings.tpl
+++ b/templates/repo_settings.tpl
@@ -15,7 +15,7 @@
   <div class="settings-cards">
 <section class="settings-card" aria-labelledby="repo-description-title">
   <h3 id="repo-description-title">Description</h3>
-  <form method="post">
+  <form method="post" data-save-on-change>
     {{!csrf_field()}}
     <input type="hidden" name="action" value="save">
     <label>
@@ -129,11 +129,14 @@
   <form method="post">
     {{!csrf_field()}}
     <input type="hidden" name="action" value="add_contributor">
-    <label>
-      Username
-      <input name="username" value="{{contributor_username}}" autocomplete="off" placeholder="username">
-    </label>
-    <button class="button" type="submit">Add contributor</button>
+    <label for="contributor-usernames">Add contributors</label>
+    <p id="contributor-picker-help" class="muted">Search for users or enter usernames. Press Space or Enter to add a chip, then choose Add contributors. Press Backspace twice in the empty field to edit the last chip.</p>
+    <div class="username-picker" data-username-picker data-owner="{{repo['owner_username']}}" data-existing="{{','.join(contributor['username'] for contributor in contributors)}}">
+      <span class="username-chip owner-chip"><span>@{{repo['owner_username']}}</span><small>Owner</small></span>
+      <input id="contributor-usernames" name="username" value="{{contributor_username}}" autocomplete="off" placeholder="Search usernames" aria-describedby="contributor-picker-help contributor-picker-status" data-username-autocomplete>
+    </div>
+    <p id="contributor-picker-status" class="muted" data-username-picker-status role="status"></p>
+    <button class="button" type="submit">Add contributors</button>
   </form>
 </section>
 
diff --git a/tests/test_app.py b/tests/test_app.py
index fe880a4..490d59b 100644
--- a/tests/test_app.py
+++ b/tests/test_app.py
@@ -2461,6 +2461,31 @@ def test_bottle_profile_star_fork_and_repo_settings_flows(isolated_app):
     assert "Type &quot;demo&quot; to confirm deletion." in response.text
 
 
+def test_repository_settings_add_multiple_contributors_atomically(isolated_app):
+    owner = create_user('alice')
+    bob = create_user('bob')
+    carol = create_user('carol')
+    isolated_app.create_repository(owner, 'demo', '')
+    repo = isolated_app.get_repo('alice', 'demo')
+    client = WsgiClient(isolated_app.app)
+    login_client(client, 'bob')
+    denied = client.post('/alice/demo/settings', {'action': 'add_contributor', 'username': ['bob', 'carol']})
+    assert denied.status_code == 403
+    assert not isolated_app.user_can_maintain_repo(carol, repo)
+    login_client(client, 'alice')
+    invalid = client.post('/alice/demo/settings', {'action': 'add_contributor', 'username': ['bob', 'missing-user']})
+    assert 'not found' in invalid.text
+    assert not isolated_app.user_can_maintain_repo(bob, repo)
+    owner_selected = client.post('/alice/demo/settings', {'action': 'add_contributor', 'username': ['bob', 'alice']})
+    assert 'owner already has access' in owner_selected.text
+    assert not isolated_app.user_can_maintain_repo(bob, repo)
+    added = client.post('/alice/demo/settings', {'action': 'add_contributor', 'username': ['@Bob', 'carol', 'bob', '']})
+    assert added.status_code == 303
+    assert isolated_app.user_can_maintain_repo(bob, repo)
+    assert isolated_app.user_can_maintain_repo(carol, repo)
+    assert isolated_app.repo_contributor_usernames(repo['id']) == ['bob', 'carol']
+
+
 def test_bottle_issue_routes_create_comment_close_and_reopen(isolated_app):
     owner = create_user("alice")
     create_repo_with_refs(owner)