]> git.ipfire.org Git - thirdparty/bugzilla.git/commitdiff
Bug 1543700 - Reimplememt Custom Search UI on Advanced Search page
authorKohei Yoshino <kohei.yoshino@gmail.com>
Tue, 18 Jun 2019 17:42:04 +0000 (13:42 -0400)
committerGitHub <noreply@github.com>
Tue, 18 Jun 2019 17:42:04 +0000 (13:42 -0400)
16 files changed:
docs/en/rst/using/finding.rst
js/advanced-search.js [new file with mode: 0644]
js/custom-search.js [deleted file]
js/history.js/license.txt [deleted file]
js/history.js/native.history.js [deleted file]
js/history.js/readme.txt [deleted file]
qa/t/test_search.t
skins/standard/advanced-search.css [new file with mode: 0644]
skins/standard/global.css
template/en/default/search/boolean-charts.html.tmpl [deleted file]
template/en/default/search/custom-search.html.tmpl [new file with mode: 0644]
template/en/default/search/form.html.tmpl
template/en/default/search/search-advanced.html.tmpl
template/en/default/search/search-create-series.html.tmpl
template/en/default/search/search-report-graph.html.tmpl
template/en/default/search/search-report-table.html.tmpl

index 5b3a0f8670c6a182506801ef07b314ffc5dda30e..4f81177c3f4898d2ca728e9128f9e2b4e1af4f7a 100644 (file)
@@ -70,14 +70,12 @@ returned by a query, over and above those defined in the fields at the top
 of the page. It is thereby possible to search for bugs
 based on elaborate combinations of criteria.
 
-The simplest custom searches have only one term. These searches
-permit the selected *field*
-to be compared using a
-selectable *operator* to a
-specified *value.* Much of this could be reproduced using the standard
-fields. However, you can then combine terms using "Match ANY" or "Match ALL",
-using parentheses for combining and priority, in order to construct searches
-of almost arbitrary complexity.
+The simplest custom searches have only one term. These searches permit the
+selected *field* to be compared using a selectable *operator* to a specified
+*value*. Much of this could be reproduced using the standard fields. However,
+you can then combine terms using "Match All" (AND) or "Match Any" (OR), using
+groups for combining and priority, in order to construct searches of almost
+arbitrary complexity.
 
 There are three fields in each row (known as a "term") of a custom search:
 
@@ -105,11 +103,12 @@ operators for :guilabel:`is empty` and :guilabel:`is not empty`, because
 Bugzilla can't tell the difference between a value field left blank on
 purpose and one left blank by accident.
 
-You can have an arbitrary number of rows, and the dropdown box above them
-defines how they relate—:guilabel:`Match ALL of the following separately`,
-:guilabel:`Match ANY of the following separately`, or :guilabel:`Match ALL of
-the following against the same field`. The difference between the first and
-the third can be illustrated with a comment search. If you have a search::
+You can have an arbitrary number of rows and groups, and rearrange them by
+dragging and dropping the handle on each item. You can even duplicate an item by
+holding the Alt key while dragging it. The radio buttons above them define how
+they relate — :guilabel:`Match All`, :guilabel:`Match All (Same Field)` or
+:guilabel:`Match Any`. The difference between the first and second can be
+illustrated with a comment search. If you have a search::
 
     Comment   contains the string   "Fred"
     Comment   contains the string   "Barney"
@@ -121,15 +120,6 @@ would need to occur in exactly the same comment.
 
 .. _advanced-features:
 
-Advanced Features
------------------
-
-If you click :guilabel:`Show Advanced Features`, then more capabilities appear.
-You can negate any row with a checkbox (see below) and also group lines of the
-search with parentheses to determine how different search terms relate. Within
-each bracketed set, you get the choice of combining them using ALL (i.e. AND)
-or ANY (i.e. OR).
-
 Negation
 --------
 
diff --git a/js/advanced-search.js b/js/advanced-search.js
new file mode 100644 (file)
index 0000000..50e6730
--- /dev/null
@@ -0,0 +1,662 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/.
+ *
+ * This Source Code Form is "Incompatible With Secondary Licenses", as
+ * defined by the Mozilla Public License, v. 2.0. */
+
+/**
+ * Reference or define the Bugzilla app namespace.
+ * @namespace
+ */
+var Bugzilla = Bugzilla || {}; // eslint-disable-line no-var
+
+/**
+ * Implement Custom Search features.
+ */
+Bugzilla.CustomSearch = class CustomSearch {
+  /**
+   * Initialize a new CustomSearch instance.
+   */
+  constructor() {
+    this.data = Bugzilla.CustomSearch.data = { group_count: 0, row_count: 0 };
+    this.$container = document.querySelector('#custom-search');
+
+    // Decode and store required data
+    Object.entries(this.$container.dataset).forEach(([key, value]) => this.data[key] = JSON.parse(value));
+
+    // Sort the fields by label instead of name
+    {
+      const { lang } = document.documentElement;
+      const options = { sensitivity: 'base' };
+
+      this.data.fields.sort((a, b) => a.label.localeCompare(b.label, lang, options));
+    }
+
+    this.restore();
+
+    this.$container.addEventListener('change', () => this.save_state());
+    this.$container.addEventListener('CustomSearch:ItemAdded', () => this.update_input_names());
+    this.$container.addEventListener('CustomSearch:ItemRemoved', () => this.remove_empty_group());
+    this.$container.addEventListener('CustomSearch:ItemMoved', () => this.remove_empty_group());
+    this.$container.addEventListener('CustomSearch:DragStarted', event => this.enable_drop_targets(event));
+    this.$container.addEventListener('CustomSearch:DragEnded', () => this.disable_drop_targets());
+  }
+
+  /**
+   * Add rows and groups specified with the URL query or history state.
+   */
+  restore() {
+    const { j_top, conditions } = history.state || this.data.initial;
+    const groups = [];
+    let level = 0;
+
+    groups.push(new Bugzilla.CustomSearch.Group({ j: j_top, is_top: true, add_empty_row: !conditions.length }));
+    groups[0].render(this.$container);
+
+    // Use `let` to work around test failures on Firefox 47 (Bug 1101653)
+    for (let condition of conditions) { // eslint-disable-line prefer-const
+      // Skip empty conditions
+      if (!condition || !condition.f) {
+        continue;
+      }
+
+      // Stop if the condition is invalid (due to any extra CP)
+      if (level < 0) {
+        break;
+      }
+
+      const group = groups[level];
+
+      if (condition.f === 'OP') {
+        // OP = open parentheses = starting a new group
+        groups[++level] = group.add_group(condition);
+      } else if (condition.f === 'CP') {
+        // OP = close parentheses = ending a new group
+        level--;
+      } else {
+        group.add_row(condition);
+      }
+    }
+
+    this.update_input_names();
+  }
+
+  /**
+   * Update the `name` attribute on all the `<input>` elements when a row or group is added, removed or moved.
+   */
+  update_input_names() {
+    let index = 1;
+    let cp_index = 0;
+
+    // Cache radio button states, which can be reset while renaming
+    const radio_states =
+      new Map([...this.$container.querySelectorAll('input[type="radio"]')].map(({ id, checked }) => [id, checked]));
+
+    // Use spread syntax to work around test failures on Firefox 47. `NodeList.forEach` was added to Firefox 50
+    [...this.$container.querySelectorAll('.group.top .condition')].forEach($item => {
+      if ($item.matches('.group')) {
+        // CP needs to be added after all the rows and nested subgroups within the current group.
+        // Example: f1=OP, f2=product, f3=component, f4=OP, f5=reporter, f6=assignee, f7=CP, f8=CP
+        cp_index = index + $item.querySelectorAll('.row').length + ($item.querySelectorAll('.group').length * 2) + 1;
+      }
+
+      [...$item.querySelectorAll('[name]')].filter($input => $input.closest('.condition') === $item).forEach($input => {
+        $input.name = $input.value === 'CP' ? `f${cp_index}` : `${$input.name.charAt(0)}${index}`;
+      });
+
+      index++;
+
+      if (index === cp_index) {
+        index++;
+      }
+    });
+
+    // Restore radio button states
+    radio_states.forEach((checked, id) => document.getElementById(id).checked = checked);
+
+    this.save_state();
+  }
+
+  /**
+   * Save the current search conditions in the browser history, so these rows and groups can be restored after the user
+   * reloads or navigates back to the page, just like native static form widgets.
+   */
+  save_state() {
+    const form_data = new FormData(this.$container.closest('form'));
+    const j_top = form_data.get('j_top');
+    const conditions = [];
+
+    for (let [name, value] of form_data.entries()) { // eslint-disable-line prefer-const
+      const [, key, index] = name.match(/^([njfov])(\d+)$/) || [];
+
+      if (key) {
+        conditions[index] = Object.assign(conditions[index] || {}, { [key]: value });
+      }
+    }
+
+    // The conditions will be the same format as an array of user-defined initial conditions embedded in the page.
+    // Example: [{ f: 'OP', n: 1, j: 'AND' }, { f: 'product', o: 'equals', v: 'Bugzilla' }, { f: 'CP' }]
+    history.replaceState(Object.assign(history.state || {}, { j_top, conditions }), document.title);
+  }
+
+  /**
+   * Remove any empty group when a row or group is moved or removed.
+   */
+  remove_empty_group() {
+    this.$container.querySelectorAll('.group').forEach($group => {
+      if (!$group.querySelector('.condition') && !$group.matches('.top')) {
+        $group.previousElementSibling.remove(); // drop target
+        $group.remove();
+      }
+    });
+
+    this.update_input_names();
+  }
+
+  /**
+   * Enable drop targets between conditions when drag action is started.
+   * @param {DragEvent} event `dragstart` event.
+   */
+  enable_drop_targets(event) {
+    const $source = document.getElementById(event.detail.id);
+
+    this.$container.querySelectorAll('.drop-target').forEach($target => {
+      // The targets above/below the source or within the current group cannot be used for the `move` effect
+      $target.setAttribute('aria-dropeffect', $target === $source.previousElementSibling ||
+        $target === $source.nextElementSibling || $source.contains($target) ? 'copy' : 'copy move');
+    });
+  }
+
+  /**
+   * Disable drop targets between conditions when drag action is ended.
+   */
+  disable_drop_targets() {
+    this.$container.querySelectorAll('[aria-dropeffect]').forEach($target => {
+      $target.setAttribute('aria-dropeffect', 'none');
+    });
+  }
+};
+
+/**
+ * Implement a Custom Search condition features shared by rows and groups.
+ * @abstract
+ */
+Bugzilla.CustomSearch.Condition = class CustomSearchCondition {
+  /**
+   * Add a row or group to the given element.
+   * @param {HTMLElement} $parent Parent node of the new element.
+   * @param {HTMLElement} [$ref] Node before which the new element is inserted.
+   */
+  render($parent, $ref = null) {
+    const { id, type, condition } = this;
+
+    $parent.insertBefore(this.$element, $ref);
+
+    this.$element.dispatchEvent(new CustomEvent('CustomSearch:ItemAdded', {
+      bubbles: true,
+      detail: { id, type, condition },
+    }));
+  }
+
+  /**
+   * Remove a row or group from view.
+   */
+  remove() {
+    const { id, type, condition } = this;
+    const $parent = this.$element.parentElement;
+
+    this.$element.remove();
+
+    $parent.dispatchEvent(new CustomEvent('CustomSearch:ItemRemoved', {
+      bubbles: true,
+      detail: { id, type, condition },
+    }));
+  }
+
+  /**
+   * Enable drag action of a row or group.
+   */
+  enable_drag() {
+    this.$element.draggable = true;
+    this.$element.setAttribute('aria-grabbed', 'true');
+    this.$action_grab.setAttribute('aria-pressed', 'true');
+  }
+
+  /**
+   * Disable drag action of a row or group.
+   */
+  disable_drag() {
+    this.$element.draggable = false;
+    this.$element.setAttribute('aria-grabbed', 'false');
+    this.$action_grab.setAttribute('aria-pressed', 'false');
+  }
+
+  /**
+   * Handle drag events at the source, which is a row or group.
+   * @param {DragEvent} event One of drag-related events.
+   */
+  handle_drag(event) {
+    event.stopPropagation();
+
+    const { id } = this;
+
+    if (event.type === 'dragstart') {
+      event.dataTransfer.setData('application/x-cs-condition', id);
+      event.dataTransfer.effectAllowed = 'copyMove';
+
+      this.$element.dispatchEvent(new CustomEvent('CustomSearch:DragStarted', { bubbles: true, detail: { id } }));
+    }
+
+    if (event.type === 'dragend') {
+      this.disable_drag();
+      this.$element.dispatchEvent(new CustomEvent('CustomSearch:DragEnded', { bubbles: true, detail: { id } }));
+    }
+  }
+};
+
+/**
+ * Implement a Custom Search group.
+ */
+Bugzilla.CustomSearch.Group = class CustomSearchGroup extends Bugzilla.CustomSearch.Condition {
+  /**
+   * Initialize a new CustomSearchGroup instance.
+   * @param {Object} [condition] Search condition.
+   * @param {Boolean} [condition.n] Whether to use NOT.
+   * @param {String} [condition.j] How to join: AND, AND_G or OR.
+   * @param {Boolean} [condition.is_top] Whether this is the topmost group within the custom search container.
+   * @param {Boolean} [condition.add_empty_row] Whether to add an empty new row to the condition area by default.
+   */
+  constructor(condition = {}) {
+    super();
+
+    this.type = 'group';
+    this.condition = condition;
+
+    const $placeholder = document.createElement('div');
+    const { n = false, j = 'AND', is_top = false, add_empty_row = false } = condition;
+    const { data } = Bugzilla.CustomSearch;
+    const { strings: str } = data;
+    const count = ++data.group_count;
+    const index = data.group_count + data.row_count;
+    const id = this.id = `group-${count}`;
+
+    $placeholder.innerHTML = `
+      <section role="group" id="${id}" class="condition group ${is_top ? 'top' : ''}" draggable="false"
+          aria-grabbed="false" aria-label="${str.group_name.replace('{ $count }', count)}">
+        ${is_top ? '' : `<input type="hidden" name="f${index}" value="OP">`}
+        <header role="toolbar">
+          ${is_top ? '' : `
+            <button type="button" class="iconic" aria-label="${str.grab}" data-action="grab">
+              <span class="icon" aria-hidden="true"></span>
+            </button>
+            <label><input type="checkbox" name="n${index}" value="1" ${n ? 'checked' : ''}> ${str.not}</label>
+          `}
+          <div class="match">
+            <div role="radiogroup" class="buttons toggle join" aria-label="${str.join_options}">
+              <div class="item">
+                <input id="${id}-j-r1" class="join" type="radio" name="${is_top ? 'j_top' : `j${index}`}" value="AND"
+                  ${j === 'AND' ? 'checked' : ''} aria-label="${str.match_all}">
+                <label for="${id}-j-r1" title="${str.match_all_hint}">${str.match_all}</label>
+              </div>
+              <div class="item">
+                <input id="${id}-j-r2" class="join" type="radio" name="${is_top ? 'j_top' : `j${index}`}" value="AND_G"
+                  ${j === 'AND_G' ? 'checked' : ''} aria-label="${str.match_all_g}">
+                <label for="${id}-j-r2" title="${str.match_all_g_hint}">${str.match_all_g}</label>
+              </div>
+              <div class="item">
+                <input id="${id}-j-r3" class="join" type="radio" name="${is_top ? 'j_top' : `j${index}`}" value="OR"
+                  ${j === 'OR' ? 'checked' : ''} aria-label="${str.match_any}">
+                <label for="${id}-j-r3" title="${str.match_any_hint}">${str.match_any}</label>
+              </div>
+            </div>
+          </div>
+          ${is_top ? '' : `
+            <button type="button" class="iconic" aria-label="${str.remove}" data-action="remove">
+              <span class="icon" aria-hidden="true"></span>
+            </button>
+          `}
+        </header>
+        <div class="conditions"></div>
+        <footer role="toolbar">
+          <button type="button" class="minor iconic-text" data-action="add-row" aria-label="${str.add_row}">
+            <span class="icon" aria-hidden="true"></span> ${str.row}
+          </button>
+          <button type="button" class="minor iconic-text" data-action="add-group" aria-label="${str.add_group}">
+            <span class="icon" aria-hidden="true"></span> ${str.group}
+          </button>
+        </footer>
+        ${is_top ? '' : `<input type="hidden" name="f${index}" value="CP">`}
+      </section>
+    `;
+
+    this.$element = $placeholder.firstElementChild;
+    this.$join = this.$element.querySelector('.buttons.join');
+    this.$join_and = this.$join.querySelector('[value="AND"]');
+    this.$join_and_g = this.$join.querySelector('[value="AND_G"]');
+    this.$conditions = this.$element.querySelector('.conditions');
+    this.$action_grab = this.$element.querySelector('[data-action="grab"]');
+    this.$action_remove = this.$element.querySelector('[data-action="remove"]');
+    this.$action_add_group = this.$element.querySelector('[data-action="add-group"]');
+    this.$action_add_row = this.$element.querySelector('[data-action="add-row"]');
+
+    this.$element.addEventListener('change', event => this.check_joined_fields(event));
+    this.$element.addEventListener('dragstart', event => this.handle_drag(event));
+    this.$element.addEventListener('dragend', event => this.handle_drag(event));
+    this.$element.addEventListener('CustomSearch:ItemAdded', () => this.update_join_option());
+    this.$element.addEventListener('CustomSearch:ItemRemoved', () => this.update_join_option());
+    this.$element.addEventListener('CustomSearch:ItemMoved', () => this.update_join_option());
+    this.$element.addEventListener('CustomSearch:ItemDuplicating', event => this.duplicate_items(event));
+    this.$action_add_group.addEventListener('click', () => this.add_group({ add_empty_row: true }));
+    this.$action_add_row.addEventListener('click', () => this.add_row());
+
+    if (!is_top) {
+      this.$action_grab.addEventListener('mousedown', () => this.enable_drag());
+      this.$action_grab.addEventListener('mouseup', () => this.disable_drag());
+      this.$action_remove.addEventListener('click', () => this.remove());
+    }
+
+    this.add_drop_target();
+
+    if (add_empty_row) {
+      this.add_row();
+    }
+  }
+
+  /**
+   * Get an array of elements within the condition area but not in the subgroups.
+   * @param {String} selector CSS selector to find elements.
+   * @returns {Array.<HTMLElement>} Elements that match the given selector.
+   */
+  get_elements(selector) {
+    return [...this.$element.querySelectorAll(selector)]
+      .filter($element => $element.closest('.group') === this.$element);
+  }
+
+  /**
+   * Update `<select class="field">` when the join option is changed, or the value on `<select class="field">` is
+   * changed while the "Match Any (Same Field)" join option is enabled.
+   * @param {Event} event `change` event.
+   */
+  check_joined_fields(event) {
+    const $target = event.target;
+    const fields = this.get_elements('.conditions select.field');
+    let field_name;
+
+    if ($target.matches('input.join') && this.get_elements('input.join').includes($target)) {
+      this.condition.j = $target.value;
+
+      if (fields.length) {
+        field_name = fields[0].value;
+      }
+    }
+
+    if (this.condition.j === 'AND_G') {
+      if ($target.matches('select.field') && fields.includes($target)) {
+        field_name = $target.value;
+      }
+
+      if (field_name) {
+        // Copy the field name on the first or updated row to other rows
+        fields.forEach($select => $select.value = field_name);
+      }
+    }
+  }
+
+  /**
+   * Update the join option when a subgroup is added or removed. If there's any subgroup, the "Match Any (Same Field)"
+   * option must be disabled.
+   */
+  update_join_option() {
+    const has_group = !!this.$conditions.querySelector('.group');
+
+    if (has_group && this.$join_and_g.checked) {
+      this.$join_and.checked = true;
+      this.condition.j = 'AND';
+    }
+
+    this.$join_and_g.disabled = has_group;
+  }
+
+  /**
+   * Add a new subgroup to the condition area.
+   * @param {Object} [condition] Search condition.
+   * @param {HTMLElement} [$ref] Node before which the new element is inserted.
+   * @returns {CustomSearchGroup} New group object.
+   */
+  add_group(condition = {}, $ref = null) {
+    const group = new Bugzilla.CustomSearch.Group(condition);
+
+    group.render(this.$conditions, $ref);
+    this.add_drop_target(group.$element.nextElementSibling);
+
+    return group;
+  }
+
+  /**
+   * Add a new child row to the condition area.
+   * @param {Object} [condition] Search condition.
+   * @param {HTMLElement} [$ref] Node before which the new element is inserted.
+   * @returns {CustomSearchRow} New row object.
+   */
+  add_row(condition = {}, $ref = null) {
+    // Copy the field name from the group's last row when a new row is added manually or the group's join option is
+    // "Match Any (Same Field)"
+    if (!condition.f || this.condition.j === 'AND_G') {
+      const last_field = this.get_elements('.conditions select.field').pop();
+
+      if (last_field) {
+        condition.f = last_field.value;
+      }
+    }
+
+    const row = new Bugzilla.CustomSearch.Row(condition);
+
+    row.render(this.$conditions, $ref);
+    this.add_drop_target(row.$element.nextElementSibling);
+
+    return row;
+  }
+
+  /**
+   * Add a new drop target to the condition area.
+   * @param {HTMLElement} [$ref] Node before which the new element is inserted.
+   */
+  add_drop_target($ref = null) {
+    this.$conditions.insertBefore((new Bugzilla.CustomSearch.DropTarget()).$element, $ref);
+  }
+
+  /**
+   * Duplicate one or more drag & dropped items.
+   * @param {CustomEvent} event `CustomSearch:ItemDuplicating` event.
+   * @see CustomSearch.restore
+   */
+  duplicate_items(event) {
+    const { conditions, $target } = event.detail;
+    const groups = [this];
+    let level = 0;
+
+    for (let condition of conditions) { // eslint-disable-line prefer-const
+      const group = groups[level];
+      const $ref = level === 0 ? $target.nextElementSibling : null;
+
+      // Skip empty conditions
+      if (!condition || !condition.f) {
+        continue;
+      }
+
+      if (condition.f === 'OP') {
+        // OP = open parentheses = starting a new group
+        groups[++level] = group.add_group(condition, $ref);
+      } else if (condition.f === 'CP') {
+        // OP = close parentheses = ending a new group
+        level--;
+      } else {
+        group.add_row(condition, $ref);
+      }
+    }
+  }
+};
+
+/**
+ * Implement a Custom Search row.
+ */
+Bugzilla.CustomSearch.Row = class CustomSearchRow extends Bugzilla.CustomSearch.Condition {
+  /**
+   * Initialize a new CustomSearchRow instance.
+   * @param {Object} [condition] Search condition.
+   * @param {Boolean} [condition.n] Whether to use NOT.
+   * @param {String} [condition.f] Field name to be selected in the dropdown list.
+   * @param {String} [condition.o] Operator name to be selected in the dropdown list.
+   * @param {String} [condition.v] Field value.
+   */
+  constructor(condition = {}) {
+    super();
+
+    this.type = 'row';
+    this.condition = condition;
+
+    const { n = false, f = 'noop', o = 'noop', v = '' } = condition;
+    const $placeholder = document.createElement('div');
+    const { data } = Bugzilla.CustomSearch;
+    const { strings: str, fields, types } = data;
+    const count = ++data.row_count;
+    const index = data.group_count + data.row_count;
+    const id = this.id = `row-${count}`;
+
+    $placeholder.innerHTML = `
+      <div role="group" id="${id}" class="condition row" draggable="false" aria-grabbed="false"
+          aria-label="${str.row_name.replace('{ $count }', count)}">
+        <button type="button" class="iconic" aria-label="${str.grab}" aria-pressed="false" data-action="grab">
+          <span class="icon" aria-hidden="true"></span>
+        </button>
+        <label><input type="checkbox" name="n${index}" value="1" ${n ? 'checked' : ''}> ${str.not}</label>
+        <select class="field" name="f${index}" aria-label="${str.field}">
+          ${fields.map(({ value, label }) => `
+            <option value="${value.htmlEncode()}" ${f === value ? 'selected' : ''}>${label.htmlEncode()}</option>
+          `).join('')}
+        </select>
+        <select class="operator" name="o${index}" aria-label="${str.operator}">
+          ${types.map(({ value, label }) => `
+            <option value="${value.htmlEncode()}" ${o === value ? 'selected' : ''}>${label.htmlEncode()}</option>
+          `).join('')}
+        </select>
+        <input class="value" type="text" name="v${index}" value="${v.htmlEncode()}" aria-label="${str.value}">
+        <button type="button" class="iconic" aria-label="${str.remove}" data-action="remove">
+          <span class="icon" aria-hidden="true"></span>
+        </button>
+      </div>
+    `;
+
+    this.$element = $placeholder.firstElementChild;
+    this.$action_grab = this.$element.querySelector('[data-action="grab"]');
+    this.$action_remove = this.$element.querySelector('[data-action="remove"]');
+
+    this.$element.addEventListener('dragstart', event => this.handle_drag(event));
+    this.$element.addEventListener('dragend', event => this.handle_drag(event));
+    this.$action_grab.addEventListener('mousedown', () => this.enable_drag());
+    this.$action_grab.addEventListener('mouseup', () => this.disable_drag());
+    this.$action_remove.addEventListener('click', () => this.remove());
+  }
+};
+
+/**
+ * Implement a Custom Search drop target.
+ */
+Bugzilla.CustomSearch.DropTarget = class CustomSearchDropTarget {
+  /**
+   * Initialize a new CustomSearchDropTarget instance.
+   */
+  constructor() {
+    const $placeholder = document.createElement('div');
+
+    $placeholder.innerHTML = `
+      <div role="separator" class="drop-target" aria-dropeffect="none">
+        <div class="indicator"></div>
+      </div>
+    `;
+
+    this.$element = $placeholder.firstElementChild;
+
+    this.$element.addEventListener('dragenter', event => this.handle_drag(event));
+    this.$element.addEventListener('dragover', event => this.handle_drag(event));
+    this.$element.addEventListener('dragleave', event => this.handle_drag(event));
+    this.$element.addEventListener('drop', event => this.handle_drag(event));
+  }
+
+  /**
+   * Handle drag events at the target.
+   * @param {DragEvent} event One of drag-related events.
+   */
+  handle_drag(event) {
+    const { type, dataTransfer: dt } = event;
+    const effect_allowed = this.$element.getAttribute('aria-dropeffect').split(' ');
+
+    // Chrome and Safari don't set `dropEffect` while Firefox does
+    if (dt.dropEffect === 'none') {
+      if (dt.effectAllowed === 'copy' && effect_allowed.includes('copy')) {
+        dt.dropEffect = 'copy';
+      } else if (dt.effectAllowed === 'copyMove' && effect_allowed.includes('move')) {
+        dt.dropEffect = 'move';
+      }
+    } else {
+      // The `move` effect is not allowed in some cases
+      if (!effect_allowed.includes(dt.dropEffect)) {
+        dt.dropEffect = 'none';
+      }
+    }
+
+    if (type === 'dragenter' && dt.dropEffect !== 'none') {
+      this.$element.classList.add('dragover');
+    }
+
+    if (type === 'dragover') {
+      event.preventDefault();
+    }
+
+    if (type === 'dragleave') {
+      this.$element.classList.remove('dragover');
+    }
+
+    if (type === 'drop') {
+      event.preventDefault();
+
+      const source_id = dt.getData('application/x-cs-condition');
+      const $source = document.getElementById(source_id);
+
+      this.$element.classList.remove('dragover');
+
+      if (dt.dropEffect === 'copy') {
+        const conditions = [];
+
+        // Create an array in the same format as the initial conditions and history-saved state
+        $source.querySelectorAll('[name]').forEach($input => {
+          if (($input.type === 'radio' || $input.type === 'checkbox') && !$input.checked) {
+            return;
+          }
+
+          const [, key, index] = $input.name.match(/^([njfov])(\d+)$/) || [];
+
+          conditions[index] = Object.assign(conditions[index] || {}, { [key]: $input.value });
+        });
+
+        // Let the parent group to duplicate the rows and groups
+        this.$element.closest('.group').dispatchEvent(new CustomEvent('CustomSearch:ItemDuplicating', {
+          detail: { conditions, $target: this.$element },
+        }));
+      }
+
+      if (dt.dropEffect === 'move') {
+        this.$element.insertAdjacentElement('beforebegin', $source.previousElementSibling); // drop target
+        this.$element.insertAdjacentElement('beforebegin', $source);
+
+        $source.parentElement.dispatchEvent(new CustomEvent('CustomSearch:ItemMoved', {
+          bubbles: true,
+          detail: { id: source_id, type: $source.matches('.group') ? 'group' : 'row' },
+        }));
+      }
+    }
+  }
+};
+
+window.addEventListener('DOMContentLoaded', () => new Bugzilla.CustomSearch(), { once: true });
diff --git a/js/custom-search.js b/js/custom-search.js
deleted file mode 100644 (file)
index 21b0660..0000000
+++ /dev/null
@@ -1,356 +0,0 @@
-/* The contents of this file are subject to the Mozilla Public
- * License Version 1.1 (the "License"); you may not use this file
- * except in compliance with the License. You may obtain a copy of
- * the License at http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS
- * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
- * implied. See the License for the specific language governing
- * rights and limitations under the License.
- *
- * The Original Code is the Bugzilla Bug Tracking System.
- *
- * The Initial Developer of the Original Code is BugzillaSource, Inc.
- * Portions created by the Initial Developer are Copyright (C) 2011
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *   Max Kanat-Alexander <mkanat@bugzilla.org>
- */
-
-var PAREN_INDENT_EM = 2;
-var ANY_ALL_SELECT_CLASS = 'any_all_select';
-
-// When somebody chooses to "Hide Advanced Features" for Custom Search,
-// we don't want to hide "Not" checkboxes if they've been checked. We
-// accomplish this by removing the custom_search_advanced class from Not
-// checkboxes when they are checked.
-//
-// We never add the custom_search_advanced class back. If we did, TUI
-// would get confused in this case: Check Not, Hide Advanced Features,
-// Uncheck Not, Show Advanced Features. (It hides "Not" when it shouldn't.)
-function custom_search_not_changed(id) {
-    var container = document.getElementById('custom_search_not_container_' + id);
-    YAHOO.util.Dom.removeClass(container, 'custom_search_advanced');
-
-    fix_query_string(container);
-}
-
-function custom_search_new_row() {
-    var row = document.getElementById('custom_search_last_row');
-    var clone = row.cloneNode(true);
-
-    _cs_fix_row_ids(clone);
-
-    // We only want one copy of the buttons, in the new row. So the old
-    // ones get deleted.
-    var op_button = document.getElementById('op_button');
-    row.removeChild(op_button);
-    var cp_button = document.getElementById('cp_container');
-    row.removeChild(cp_button);
-    var add_button = document.getElementById('add_button');
-    row.removeChild(add_button);
-    _remove_any_all(clone);
-
-    // Always make sure there's only one row with this id.
-    row.id = null;
-    row.parentNode.appendChild(clone);
-    cs_reconfigure(row);
-    fix_query_string(row);
-    return clone;
-}
-
-var _cs_source_any_all;
-function custom_search_open_paren() {
-    var row = document.getElementById('custom_search_last_row');
-
-    // create a copy of j_top and use that as the source, so we can modify
-    // j_top if required
-    if (!_cs_source_any_all) {
-        var j_top = document.getElementById('j_top');
-        _cs_source_any_all = j_top.cloneNode(true);
-    }
-
-    // find the parent any/all select, and remove the grouped option
-    var structure = _cs_build_structure(row);
-    var old_id = _cs_get_row_id(row);
-    var parent_j = document.getElementById(_cs_get_join(structure, 'f' + old_id));
-    _cs_remove_and_g(parent_j);
-
-    // If there's an "Any/All" select in this row, it needs to stay as
-    // part of the parent paren set.
-    var old_any_all = _remove_any_all(row);
-    if (old_any_all) {
-        var any_all_row = row.cloneNode(false);
-        any_all_row.id = null;
-        any_all_row.appendChild(old_any_all);
-        row.parentNode.insertBefore(any_all_row, row);
-    }
-
-    // We also need a "Not" checkbox to stay in the parent paren set.
-    var new_not = YAHOO.util.Dom.getElementsByClassName(
-        'custom_search_not_container', null, row);
-    var not_for_paren = new_not[0].cloneNode(true);
-
-    // Preserve the values when modifying the row.
-    var id = _cs_fix_row_ids(row, true);
-    var prev_id = id - 1;
-
-    var paren_row = row.cloneNode(false);
-    paren_row.id = null;
-    paren_row.innerHTML = '(<input type="hidden" name="f' + prev_id
-                        + '" id="f' + prev_id + '" value="OP">';
-    paren_row.insertBefore(not_for_paren, paren_row.firstChild);
-    row.parentNode.insertBefore(paren_row, row);
-
-    // New paren set needs a new "Any/All" select.
-    var any_all_container = document.createElement('div');
-    YAHOO.util.Dom.addClass(any_all_container, ANY_ALL_SELECT_CLASS);
-    var any_all = _cs_source_any_all.cloneNode(true);
-    any_all.name = 'j' + prev_id;
-    any_all.id = any_all.name;
-    any_all_container.appendChild(any_all);
-    row.insertBefore(any_all_container, row.firstChild);
-
-    var margin = YAHOO.util.Dom.getStyle(row, 'margin-left');
-    var int_match = margin.match(/\d+/);
-    var new_margin = parseInt(int_match[0]) + PAREN_INDENT_EM;
-    YAHOO.util.Dom.setStyle(row, 'margin-left', new_margin + 'em');
-    YAHOO.util.Dom.removeClass('cp_container', 'bz_default_hidden');
-
-    cs_reconfigure(any_all_container);
-    fix_query_string(any_all_container);
-}
-
-function custom_search_close_paren() {
-    var new_row = custom_search_new_row();
-
-    // We need to up the new row's id by one more, because we're going
-    // to insert a "CP" before it.
-    var id = _cs_fix_row_ids(new_row);
-
-    var margin = YAHOO.util.Dom.getStyle(new_row, 'margin-left');
-    var int_match = margin.match(/\d+/);
-    var new_margin = parseInt(int_match[0]) - PAREN_INDENT_EM;
-    YAHOO.util.Dom.setStyle(new_row, 'margin-left', new_margin + 'em');
-
-    var paren_row = new_row.cloneNode(false);
-    paren_row.id = null;
-    paren_row.innerHTML = ')<input type="hidden" name="f' + (id - 1)
-                        + '" id="f' + (id - 1) + '" value="CP">';
-
-    new_row.parentNode.insertBefore(paren_row, new_row);
-
-    if (new_margin == 0) {
-        YAHOO.util.Dom.addClass('cp_container', 'bz_default_hidden');
-    }
-
-    cs_reconfigure(new_row);
-    fix_query_string(new_row);
-}
-
-// When a user goes Back in their browser after searching, some browsers
-// (Chrome, as of September 2011) do not remember the DOM that was created
-// by the Custom Search JS. (In other words, their whole entered Custom
-// Search disappears.) The solution is to update the History object,
-// using the query string, which query.cgi can read to re-create the page
-// exactly as the user had it before.
-function fix_query_string(form_member) {
-    // window.History comes from history.js.
-    // It falls back to the normal window.history object for HTML5 browsers.
-    if (!(window.History && window.History.replaceState))
-        return;
-
-    var form = YAHOO.util.Dom.getAncestorByTagName(form_member, 'form');
-    // Disable the token field so setForm doesn't include it
-    var reenable_token = false;
-    if (form['token'] && !form['token'].disabled) {
-      form['token'].disabled = true;
-      reenable_token = true;
-    }
-    var query = YAHOO.util.Connect.setForm(form);
-    if (reenable_token)
-      form['token'].disabled = false;
-    window.History.replaceState(null, document.title, '?' + query);
-}
-
-// Browsers that do not support HTML5's history.replaceState gain an emulated
-// version via history.js, with the full query_string in the location's hash.
-// We rewrite the URL to include the hash and redirect to the new location,
-// which causes custom search fields to work.
-function redirect_html4_browsers() {
-    var hash = document.location.hash;
-    if (hash == '') return;
-    hash = hash.substring(1);
-    if (hash.substring(0, 10) != 'query.cgi?') return;
-    var url = document.location + "";
-    url = url.substring(0, url.indexOf('query.cgi#')) + hash;
-    document.location = url;
-}
-
-function _cs_fix_row_ids(row, preserve_values) {
-    // Update the label of the checkbox.
-    var label = YAHOO.util.Dom.getElementBy(function() { return true }, 'label', row);
-    var id_match = label.htmlFor.match(/\d+$/);
-    var id = parseInt(id_match[0]) + 1;
-    label.htmlFor = label.htmlFor.replace(/\d+$/, id);
-
-    // Sets all the inputs in the row back to their default
-    // and fixes their id.
-    var fields =
-        YAHOO.util.Dom.getElementsByClassName('custom_search_form_field', null, row);
-    for (var i = 0; i < fields.length; i++) {
-        var field = fields[i];
-
-        if (!preserve_values) {
-            if (field.type == "checkbox") {
-                field.checked = false;
-            }
-            else {
-                field.value = '';
-            }
-        }
-
-        // Update the numeric id for the row.
-        field.name = field.name.replace(/\d+$/, id);
-        field.id = field.name;
-    }
-
-    return id;
-}
-
-function _cs_build_structure(form_member) {
-    // build a map of the structure of the custom fields
-    var form = YAHOO.util.Dom.getAncestorByTagName(form_member, 'form');
-    var last_id = _get_last_cs_row_id(form);
-    var structure = [ 'j_top' ];
-    var nested = [ structure ];
-    for (var id = 1; id <= last_id; id++) {
-        var f = form['f' + id];
-        if (!f || !f.parentNode.parentNode) continue;
-
-        if (f.value == 'OP') {
-            var j = [ 'j' + id ];
-            nested[nested.length - 1].push(j);
-            nested.push(j);
-            continue;
-        } else if (f.value == 'CP') {
-            nested.pop();
-            continue;
-        } else {
-            nested[nested.length - 1].push('f' + id);
-        }
-    }
-    return structure;
-}
-
-function cs_reconfigure(form_member) {
-    var structure = _cs_build_structure(form_member);
-    _cs_add_listeners(structure);
-    _cs_trigger_j_listeners(structure);
-    fix_query_string(form_member);
-
-    var j = _cs_get_join(structure, 'f' + _get_last_cs_row_id());
-    document.getElementById('op_button').disabled = document.getElementById(j).value == 'AND_G';
-}
-
-function _cs_add_listeners(parents) {
-    for (var i = 0, l = parents.length; i < l; i++) {
-        if (typeof(parents[i]) == 'object') {
-            // nested
-            _cs_add_listeners(parents[i]);
-        } else if (i == 0) {
-            // joiner
-            YAHOO.util.Event.removeListener(parents[i], 'change', _cs_j_change);
-            YAHOO.util.Event.addListener(parents[i], 'change', _cs_j_change, parents);
-        } else {
-            // field
-            YAHOO.util.Event.removeListener(parents[i], 'change', _cs_f_change);
-            YAHOO.util.Event.addListener(parents[i], 'change', _cs_f_change, parents);
-        }
-    }
-}
-
-function _cs_trigger_j_listeners(fields) {
-    var has_children = false;
-    for (var i = 0, l = fields.length; i < l; i++) {
-        if (typeof(fields[i]) == 'undefined') {
-            continue;
-        } else if (typeof(fields[i]) == 'object') {
-            // nested
-            _cs_trigger_j_listeners(fields[i]);
-            has_children = true;
-        } else if (i == 0) {
-            _cs_j_change(undefined, fields);
-        }
-    }
-    if (has_children) {
-        _cs_remove_and_g(document.getElementById(fields[0]));
-    }
-}
-
-function _cs_get_join(parents, field) {
-    for (var i = 0, l = parents.length; i < l; i++) {
-        if (typeof(parents[i]) == 'object') {
-            // nested
-            var result = _cs_get_join(parents[i], field);
-            if (result) return result;
-        } else if (parents[i] == field) {
-            return parents[0];
-        }
-    }
-    return false;
-}
-
-function _cs_remove_and_g(join_field) {
-    var index = bz_optionIndex(join_field, 'AND_G');
-    join_field.options[index] = null;
-    join_field.options[bz_optionIndex(join_field, 'AND')].innerHTML = cs_and_label;
-    join_field.options[bz_optionIndex(join_field, 'OR')].innerHTML = cs_or_label;
-}
-
-function _cs_j_change(evt, fields, field) {
-    var j = document.getElementById(fields[0]);
-    if (j && j.value == 'AND_G') {
-        for (var i = 1, l = fields.length; i < l; i++) {
-            if (typeof(fields[i]) == 'object') continue;
-            if (!field) {
-                field = document.getElementById(fields[i]).value;
-            } else {
-                document.getElementById(fields[i]).value = field;
-            }
-        }
-        if (evt) {
-            fix_query_string(j);
-        }
-        if ('f' + _get_last_cs_row_id() == fields[fields.length - 1]) {
-            document.getElementById('op_button').style.display = 'none';
-        }
-    } else {
-        document.getElementById('op_button').style.display = '';
-    }
-}
-
-function _cs_f_change(evt, args) {
-    var field = YAHOO.util.Event.getTarget(evt);
-    _cs_j_change(evt, args, field.value);
-}
-
-function _get_last_cs_row_id() {
-    return _cs_get_row_id('custom_search_last_row');
-}
-
-function _cs_get_row_id(row) {
-    var label = YAHOO.util.Dom.getElementBy(function() { return true }, 'label', row);
-    return parseInt(label.htmlFor.match(/\d+$/)[0]);
-}
-
-function _remove_any_all(parent) {
-    var any_all = YAHOO.util.Dom.getElementsByClassName(
-        ANY_ALL_SELECT_CLASS, null, parent);
-    if (any_all[0]) {
-        parent.removeChild(any_all[0]);
-        return any_all[0];
-    }
-    return null;
-}
diff --git a/js/history.js/license.txt b/js/history.js/license.txt
deleted file mode 100644 (file)
index 719aafc..0000000
+++ /dev/null
@@ -1,10 +0,0 @@
-Copyright (c) 2011, Benjamin Arthur Lupton
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
-
-  • Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
-  • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
-  • Neither the name of Benjamin Arthur Lupton nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/js/history.js/native.history.js b/js/history.js/native.history.js
deleted file mode 100644 (file)
index 3d34166..0000000
+++ /dev/null
@@ -1 +0,0 @@
-window.JSON||(window.JSON={}),function(){function f(a){return a<10?"0"+a:a}function quote(a){return escapable.lastIndex=0,escapable.test(a)?'"'+a.replace(escapable,function(a){var b=meta[a];return typeof b=="string"?b:"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+a+'"'}function str(a,b){var c,d,e,f,g=gap,h,i=b[a];i&&typeof i=="object"&&typeof i.toJSON=="function"&&(i=i.toJSON(a)),typeof rep=="function"&&(i=rep.call(b,a,i));switch(typeof i){case"string":return quote(i);case"number":return isFinite(i)?String(i):"null";case"boolean":case"null":return String(i);case"object":if(!i)return"null";gap+=indent,h=[];if(Object.prototype.toString.apply(i)==="[object Array]"){f=i.length;for(c=0;c<f;c+=1)h[c]=str(c,i)||"null";return e=h.length===0?"[]":gap?"[\n"+gap+h.join(",\n"+gap)+"\n"+g+"]":"["+h.join(",")+"]",gap=g,e}if(rep&&typeof rep=="object"){f=rep.length;for(c=0;c<f;c+=1)d=rep[c],typeof d=="string"&&(e=str(d,i),e&&h.push(quote(d)+(gap?": ":":")+e))}else for(d in i)Object.hasOwnProperty.call(i,d)&&(e=str(d,i),e&&h.push(quote(d)+(gap?": ":":")+e));return e=h.length===0?"{}":gap?"{\n"+gap+h.join(",\n"+gap)+"\n"+g+"}":"{"+h.join(",")+"}",gap=g,e}}"use strict",typeof Date.prototype.toJSON!="function"&&(Date.prototype.toJSON=function(a){return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+f(this.getUTCMonth()+1)+"-"+f(this.getUTCDate())+"T"+f(this.getUTCHours())+":"+f(this.getUTCMinutes())+":"+f(this.getUTCSeconds())+"Z":null},String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(a){return this.valueOf()});var JSON=window.JSON,cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},rep;typeof JSON.stringify!="function"&&(JSON.stringify=function(a,b,c){var d;gap="",indent="";if(typeof c=="number")for(d=0;d<c;d+=1)indent+=" ";else typeof c=="string"&&(indent=c);rep=b;if(!b||typeof b=="function"||typeof b=="object"&&typeof b.length=="number")return str("",{"":a});throw new Error("JSON.stringify")}),typeof JSON.parse!="function"&&(JSON.parse=function(text,reviver){function walk(a,b){var c,d,e=a[b];if(e&&typeof e=="object")for(c in e)Object.hasOwnProperty.call(e,c)&&(d=walk(e,c),d!==undefined?e[c]=d:delete e[c]);return reviver.call(a,b,e)}var j;text=String(text),cx.lastIndex=0,cx.test(text)&&(text=text.replace(cx,function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)}));if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,"")))return j=eval("("+text+")"),typeof reviver=="function"?walk({"":j},""):j;throw new SyntaxError("JSON.parse")})}(),function(a,b){"use strict";var c=a.History=a.History||{};if(typeof c.Adapter!="undefined")throw new Error("History.js Adapter has already been loaded...");c.Adapter={handlers:{},_uid:1,uid:function(a){return a._uid||(a._uid=c.Adapter._uid++)},bind:function(a,b,d){var e=c.Adapter.uid(a);c.Adapter.handlers[e]=c.Adapter.handlers[e]||{},c.Adapter.handlers[e][b]=c.Adapter.handlers[e][b]||[],c.Adapter.handlers[e][b].push(d),a["on"+b]=function(a,b){return function(d){c.Adapter.trigger(a,b,d)}}(a,b)},trigger:function(a,b,d){d=d||{};var e=c.Adapter.uid(a),f,g;c.Adapter.handlers[e]=c.Adapter.handlers[e]||{},c.Adapter.handlers[e][b]=c.Adapter.handlers[e][b]||[];for(f=0,g=c.Adapter.handlers[e][b].length;f<g;++f)c.Adapter.handlers[e][b][f].apply(this,[d])},extractEventData:function(a,c){var d=c&&c[a]||b;return d},onDomLoad:function(b){var c=a.setTimeout(function(){b()},2e3);a.onload=function(){clearTimeout(c),b()}}},typeof c.init!="undefined"&&c.init()}(window),function(a,b){"use strict";var c=a.document,d=a.setTimeout||d,e=a.clearTimeout||e,f=a.setInterval||f,g=a.History=a.History||{};if(typeof g.initHtml4!="undefined")throw new Error("History.js HTML4 Support has already been loaded...");g.initHtml4=function(){if(typeof g.initHtml4.initialized!="undefined")return!1;g.initHtml4.initialized=!0,g.enabled=!0,g.savedHashes=[],g.isLastHash=function(a){var b=g.getHashByIndex(),c;return c=a===b,c},g.saveHash=function(a){return g.isLastHash(a)?!1:(g.savedHashes.push(a),!0)},g.getHashByIndex=function(a){var b=null;return typeof a=="undefined"?b=g.savedHashes[g.savedHashes.length-1]:a<0?b=g.savedHashes[g.savedHashes.length+a]:b=g.savedHashes[a],b},g.discardedHashes={},g.discardedStates={},g.discardState=function(a,b,c){var d=g.getHashByState(a),e;return e={discardedState:a,backState:c,forwardState:b},g.discardedStates[d]=e,!0},g.discardHash=function(a,b,c){var d={discardedHash:a,backState:c,forwardState:b};return g.discardedHashes[a]=d,!0},g.discardedState=function(a){var b=g.getHashByState(a),c;return c=g.discardedStates[b]||!1,c},g.discardedHash=function(a){var b=g.discardedHashes[a]||!1;return b},g.recycleState=function(a){var b=g.getHashByState(a);return g.discardedState(a)&&delete g.discardedStates[b],!0},g.emulated.hashChange&&(g.hashChangeInit=function(){g.checkerFunction=null;var b="",d,e,h,i;return g.isInternetExplorer()?(d="historyjs-iframe",e=c.createElement("iframe"),e.setAttribute("id",d),e.style.display="none",c.body.appendChild(e),e.contentWindow.document.open(),e.contentWindow.document.close(),h="",i=!1,g.checkerFunction=function(){if(i)return!1;i=!0;var c=g.getHash()||"",d=g.unescapeHash(e.contentWindow.document.location.hash)||"";return c!==b?(b=c,d!==c&&(h=d=c,e.contentWindow.document.open(),e.contentWindow.document.close(),e.contentWindow.document.location.hash=g.escapeHash(c)),g.Adapter.trigger(a,"hashchange")):d!==h&&(h=d,g.setHash(d,!1)),i=!1,!0}):g.checkerFunction=function(){var c=g.getHash();return c!==b&&(b=c,g.Adapter.trigger(a,"hashchange")),!0},g.intervalList.push(f(g.checkerFunction,g.options.hashChangeInterval)),!0},g.Adapter.onDomLoad(g.hashChangeInit)),g.emulated.pushState&&(g.onHashChange=function(b){var d=b&&b.newURL||c.location.href,e=g.getHashByUrl(d),f=null,h=null,i=null,j;return g.isLastHash(e)?(g.busy(!1),!1):(g.doubleCheckComplete(),g.saveHash(e),e&&g.isTraditionalAnchor(e)?(g.Adapter.trigger(a,"anchorchange"),g.busy(!1),!1):(f=g.extractState(g.getFullUrl(e||c.location.href,!1),!0),g.isLastSavedState(f)?(g.busy(!1),!1):(h=g.getHashByState(f),j=g.discardedState(f),j?(g.getHashByIndex(-2)===g.getHashByState(j.forwardState)?g.back(!1):g.forward(!1),!1):(g.pushState(f.data,f.title,f.url,!1),!0))))},g.Adapter.bind(a,"hashchange",g.onHashChange),g.pushState=function(b,d,e,f){if(g.getHashByUrl(e))throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors).");if(f!==!1&&g.busy())return g.pushQueue({scope:g,callback:g.pushState,args:arguments,queue:f}),!1;g.busy(!0);var h=g.createStateObject(b,d,e),i=g.getHashByState(h),j=g.getState(!1),k=g.getHashByState(j),l=g.getHash();return g.storeState(h),g.expectedStateId=h.id,g.recycleState(h),g.setTitle(h),i===k?(g.busy(!1),!1):i!==l&&i!==g.getShortUrl(c.location.href)?(g.setHash(i,!1),!1):(g.saveState(h),g.Adapter.trigger(a,"statechange"),g.busy(!1),!0)},g.replaceState=function(a,b,c,d){if(g.getHashByUrl(c))throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors).");if(d!==!1&&g.busy())return g.pushQueue({scope:g,callback:g.replaceState,args:arguments,queue:d}),!1;g.busy(!0);var e=g.createStateObject(a,b,c),f=g.getState(!1),h=g.getStateByIndex(-2);return g.discardState(f,e,h),g.pushState(e.data,e.title,e.url,!1),!0}),g.emulated.pushState&&g.getHash()&&!g.emulated.hashChange&&g.Adapter.onDomLoad(function(){g.Adapter.trigger(a,"hashchange")})},typeof g.init!="undefined"&&g.init()}(window),function(a,b){"use strict";var c=a.console||b,d=a.document,e=a.navigator,f=a.sessionStorage||!1,g=a.setTimeout,h=a.clearTimeout,i=a.setInterval,j=a.clearInterval,k=a.JSON,l=a.alert,m=a.History=a.History||{},n=a.history;k.stringify=k.stringify||k.encode,k.parse=k.parse||k.decode;if(typeof m.init!="undefined")throw new Error("History.js Core has already been loaded...");m.init=function(){return typeof m.Adapter=="undefined"?!1:(typeof m.initCore!="undefined"&&m.initCore(),typeof m.initHtml4!="undefined"&&m.initHtml4(),!0)},m.initCore=function(){if(typeof m.initCore.initialized!="undefined")return!1;m.initCore.initialized=!0,m.options=m.options||{},m.options.hashChangeInterval=m.options.hashChangeInterval||100,m.options.safariPollInterval=m.options.safariPollInterval||500,m.options.doubleCheckInterval=m.options.doubleCheckInterval||500,m.options.storeInterval=m.options.storeInterval||1e3,m.options.busyDelay=m.options.busyDelay||250,m.options.debug=m.options.debug||!1,m.options.initialTitle=m.options.initialTitle||d.title,m.intervalList=[],m.clearAllIntervals=function(){var a,b=m.intervalList;if(typeof b!="undefined"&&b!==null){for(a=0;a<b.length;a++)j(b[a]);m.intervalList=null}},m.debug=function(){(m.options.debug||!1)&&m.log.apply(m,arguments)},m.log=function(){var a=typeof c!="undefined"&&typeof c.log!="undefined"&&typeof c.log.apply!="undefined",b=d.getElementById("log"),e,f,g,h,i;a?(h=Array.prototype.slice.call(arguments),e=h.shift(),typeof c.debug!="undefined"?c.debug.apply(c,[e,h]):c.log.apply(c,[e,h])):e="\n"+arguments[0]+"\n";for(f=1,g=arguments.length;f<g;++f){i=arguments[f];if(typeof i=="object"&&typeof k!="undefined")try{i=k.stringify(i)}catch(j){}e+="\n"+i+"\n"}return b?(b.value+=e+"\n-----\n",b.scrollTop=b.scrollHeight-b.clientHeight):a||l(e),!0},m.getInternetExplorerMajorVersion=function(){var a=m.getInternetExplorerMajorVersion.cached=typeof m.getInternetExplorerMajorVersion.cached!="undefined"?m.getInternetExplorerMajorVersion.cached:function(){var a=3,b=d.createElement("div"),c=b.getElementsByTagName("i");while((b.innerHTML="<!--[if gt IE "+ ++a+"]><i></i><![endif]-->")&&c[0]);return a>4?a:!1}();return a},m.isInternetExplorer=function(){var a=m.isInternetExplorer.cached=typeof m.isInternetExplorer.cached!="undefined"?m.isInternetExplorer.cached:Boolean(m.getInternetExplorerMajorVersion());return a},m.emulated={pushState:!Boolean(a.history&&a.history.pushState&&a.history.replaceState&&!/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i.test(e.userAgent)&&!/AppleWebKit\/5([0-2]|3[0-2])/i.test(e.userAgent)),hashChange:Boolean(!("onhashchange"in a||"onhashchange"in d)||m.isInternetExplorer()&&m.getInternetExplorerMajorVersion()<8)},m.enabled=!m.emulated.pushState,m.bugs={setHash:Boolean(!m.emulated.pushState&&e.vendor==="Apple Computer, Inc."&&/AppleWebKit\/5([0-2]|3[0-3])/.test(e.userAgent)),safariPoll:Boolean(!m.emulated.pushState&&e.vendor==="Apple Computer, Inc."&&/AppleWebKit\/5([0-2]|3[0-3])/.test(e.userAgent)),ieDoubleCheck:Boolean(m.isInternetExplorer()&&m.getInternetExplorerMajorVersion()<8),hashEscape:Boolean(m.isInternetExplorer()&&m.getInternetExplorerMajorVersion()<7)},m.isEmptyObject=function(a){for(var b in a)return!1;return!0},m.cloneObject=function(a){var b,c;return a?(b=k.stringify(a),c=k.parse(b)):c={},c},m.getRootUrl=function(){var a=d.location.protocol+"//"+(d.location.hostname||d.location.host);if(d.location.port||!1)a+=":"+d.location.port;return a+="/",a},m.getBaseHref=function(){var a=d.getElementsByTagName("base"),b=null,c="";return a.length===1&&(b=a[0],c=b.href.replace(/[^\/]+$/,"")),c=c.replace(/\/+$/,""),c&&(c+="/"),c},m.getBaseUrl=function(){var a=m.getBaseHref()||m.getBasePageUrl()||m.getRootUrl();return a},m.getPageUrl=function(){var a=m.getState(!1,!1),b=(a||{}).url||d.location.href,c;return c=b.replace(/\/+$/,"").replace(/[^\/]+$/,function(a,b,c){return/\./.test(a)?a:a+"/"}),c},m.getBasePageUrl=function(){var a=d.location.href.replace(/[#\?].*/,"").replace(/[^\/]+$/,function(a,b,c){return/[^\/]$/.test(a)?"":a}).replace(/\/+$/,"")+"/";return a},m.getFullUrl=function(a,b){var c=a,d=a.substring(0,1);return b=typeof b=="undefined"?!0:b,/[a-z]+\:\/\//.test(a)||(d==="/"?c=m.getRootUrl()+a.replace(/^\/+/,""):d==="#"?c=m.getPageUrl().replace(/#.*/,"")+a:d==="?"?c=m.getPageUrl().replace(/[\?#].*/,"")+a:b?c=m.getBaseUrl()+a.replace(/^(\.\/)+/,""):c=m.getBasePageUrl()+a.replace(/^(\.\/)+/,"")),c.replace(/\#$/,"")},m.getShortUrl=function(a){var b=a,c=m.getBaseUrl(),d=m.getRootUrl();return m.emulated.pushState&&(b=b.replace(c,"")),b=b.replace(d,"/"),m.isTraditionalAnchor(b)&&(b="./"+b),b=b.replace(/^(\.\/)+/g,"./").replace(/\#$/,""),b},m.store={},m.idToState=m.idToState||{},m.stateToId=m.stateToId||{},m.urlToId=m.urlToId||{},m.storedStates=m.storedStates||[],m.savedStates=m.savedStates||[],m.normalizeStore=function(){m.store.idToState=m.store.idToState||{},m.store.urlToId=m.store.urlToId||{},m.store.stateToId=m.store.stateToId||{}},m.getState=function(a,b){typeof a=="undefined"&&(a=!0),typeof b=="undefined"&&(b=!0);var c=m.getLastSavedState();return!c&&b&&(c=m.createStateObject()),a&&(c=m.cloneObject(c),c.url=c.cleanUrl||c.url),c},m.getIdByState=function(a){var b=m.extractId(a.url),c;if(!b){c=m.getStateString(a);if(typeof m.stateToId[c]!="undefined")b=m.stateToId[c];else if(typeof m.store.stateToId[c]!="undefined")b=m.store.stateToId[c];else{for(;;){b=(new Date).getTime()+String(Math.random()).replace(/\D/g,"");if(typeof m.idToState[b]=="undefined"&&typeof m.store.idToState[b]=="undefined")break}m.stateToId[c]=b,m.idToState[b]=a}}return b},m.normalizeState=function(a){var b,c;if(!a||typeof a!="object")a={};if(typeof a.normalized!="undefined")return a;if(!a.data||typeof a.data!="object")a.data={};b={},b.normalized=!0,b.title=a.title||"",b.url=m.getFullUrl(m.unescapeString(a.url||d.location.href)),b.hash=m.getShortUrl(b.url),b.data=m.cloneObject(a.data),b.id=m.getIdByState(b),b.cleanUrl=b.url.replace(/\??\&_suid.*/,""),b.url=b.cleanUrl,c=!m.isEmptyObject(b.data);if(b.title||c)b.hash=m.getShortUrl(b.url).replace(/\??\&_suid.*/,""),/\?/.test(b.hash)||(b.hash+="?"),b.hash+="&_suid="+b.id;return b.hashedUrl=m.getFullUrl(b.hash),(m.emulated.pushState||m.bugs.safariPoll)&&m.hasUrlDuplicate(b)&&(b.url=b.hashedUrl),b},m.createStateObject=function(a,b,c){var d={data:a,title:b,url:c};return d=m.normalizeState(d),d},m.getStateById=function(a){a=String(a);var c=m.idToState[a]||m.store.idToState[a]||b;return c},m.getStateString=function(a){var b,c,d;return b=m.normalizeState(a),c={data:b.data,title:a.title,url:a.url},d=k.stringify(c),d},m.getStateId=function(a){var b,c;return b=m.normalizeState(a),c=b.id,c},m.getHashByState=function(a){var b,c;return b=m.normalizeState(a),c=b.hash,c},m.extractId=function(a){var b,c,d;return c=/(.*)\&_suid=([0-9]+)$/.exec(a),d=c?c[1]||a:a,b=c?String(c[2]||""):"",b||!1},m.isTraditionalAnchor=function(a){var b=!/[\/\?\.]/.test(a);return b},m.extractState=function(a,b){var c=null,d,e;return b=b||!1,d=m.extractId(a),d&&(c=m.getStateById(d)),c||(e=m.getFullUrl(a),d=m.getIdByUrl(e)||!1,d&&(c=m.getStateById(d)),!c&&b&&!m.isTraditionalAnchor(a)&&(c=m.createStateObject(null,null,e))),c},m.getIdByUrl=function(a){var c=m.urlToId[a]||m.store.urlToId[a]||b;return c},m.getLastSavedState=function(){return m.savedStates[m.savedStates.length-1]||b},m.getLastStoredState=function(){return m.storedStates[m.storedStates.length-1]||b},m.hasUrlDuplicate=function(a){var b=!1,c;return c=m.extractState(a.url),b=c&&c.id!==a.id,b},m.storeState=function(a){return m.urlToId[a.url]=a.id,m.storedStates.push(m.cloneObject(a)),a},m.isLastSavedState=function(a){var b=!1,c,d,e;return m.savedStates.length&&(c=a.id,d=m.getLastSavedState(),e=d.id,b=c===e),b},m.saveState=function(a){return m.isLastSavedState(a)?!1:(m.savedStates.push(m.cloneObject(a)),!0)},m.getStateByIndex=function(a){var b=null;return typeof a=="undefined"?b=m.savedStates[m.savedStates.length-1]:a<0?b=m.savedStates[m.savedStates.length+a]:b=m.savedStates[a],b},m.getHash=function(){var a=m.unescapeHash(d.location.hash);return a},m.unescapeString=function(b){var c=b,d;for(;;){d=a.unescape(c);if(d===c)break;c=d}return c},m.unescapeHash=function(a){var b=m.normalizeHash(a);return b=m.unescapeString(b),b},m.normalizeHash=function(a){var b=a.replace(/[^#]*#/,"").replace(/#.*/,"");return b},m.setHash=function(a,b){var c,e,f;return b!==!1&&m.busy()?(m.pushQueue({scope:m,callback:m.setHash,args:arguments,queue:b}),!1):(c=m.escapeHash(a),m.busy(!0),e=m.extractState(a,!0),e&&!m.emulated.pushState?m.pushState(e.data,e.title,e.url,!1):d.location.hash!==c&&(m.bugs.setHash?(f=m.getPageUrl(),m.pushState(null,null,f+"#"+c,!1)):d.location.hash=c),m)},m.escapeHash=function(b){var c=m.normalizeHash(b);return c=a.escape(c),m.bugs.hashEscape||(c=c.replace(/\%21/g,"!").replace(/\%26/g,"&").replace(/\%3D/g,"=").replace(/\%3F/g,"?")),c},m.getHashByUrl=function(a){var b=String(a).replace(/([^#]*)#?([^#]*)#?(.*)/,"$2");return b=m.unescapeHash(b),b},m.setTitle=function(a){var b=a.title,c;b||(c=m.getStateByIndex(0),c&&c.url===a.url&&(b=c.title||m.options.initialTitle));try{d.getElementsByTagName("title")[0].innerHTML=b.replace("<","&lt;").replace(">","&gt;").replace(" & "," &amp; ")}catch(e){}return d.title=b,m},m.queues=[],m.busy=function(a){typeof a!="undefined"?m.busy.flag=a:typeof m.busy.flag=="undefined"&&(m.busy.flag=!1);if(!m.busy.flag){h(m.busy.timeout);var b=function(){var a,c,d;if(m.busy.flag)return;for(a=m.queues.length-1;a>=0;--a){c=m.queues[a];if(c.length===0)continue;d=c.shift(),m.fireQueueItem(d),m.busy.timeout=g(b,m.options.busyDelay)}};m.busy.timeout=g(b,m.options.busyDelay)}return m.busy.flag},m.busy.flag=!1,m.fireQueueItem=function(a){return a.callback.apply(a.scope||m,a.args||[])},m.pushQueue=function(a){return m.queues[a.queue||0]=m.queues[a.queue||0]||[],m.queues[a.queue||0].push(a),m},m.queue=function(a,b){return typeof a=="function"&&(a={callback:a}),typeof b!="undefined"&&(a.queue=b),m.busy()?m.pushQueue(a):m.fireQueueItem(a),m},m.clearQueue=function(){return m.busy.flag=!1,m.queues=[],m},m.stateChanged=!1,m.doubleChecker=!1,m.doubleCheckComplete=function(){return m.stateChanged=!0,m.doubleCheckClear(),m},m.doubleCheckClear=function(){return m.doubleChecker&&(h(m.doubleChecker),m.doubleChecker=!1),m},m.doubleCheck=function(a){return m.stateChanged=!1,m.doubleCheckClear(),m.bugs.ieDoubleCheck&&(m.doubleChecker=g(function(){return m.doubleCheckClear(),m.stateChanged||a(),!0},m.options.doubleCheckInterval)),m},m.safariStatePoll=function(){var b=m.extractState(d.location.href),c;if(!m.isLastSavedState(b))c=b;else return;return c||(c=m.createStateObject()),m.Adapter.trigger(a,"popstate"),m},m.back=function(a){return a!==!1&&m.busy()?(m.pushQueue({scope:m,callback:m.back,args:arguments,queue:a}),!1):(m.busy(!0),m.doubleCheck(function(){m.back(!1)}),n.go(-1),!0)},m.forward=function(a){return a!==!1&&m.busy()?(m.pushQueue({scope:m,callback:m.forward,args:arguments,queue:a}),!1):(m.busy(!0),m.doubleCheck(function(){m.forward(!1)}),n.go(1),!0)},m.go=function(a,b){var c;if(a>0)for(c=1;c<=a;++c)m.forward(b);else{if(!(a<0))throw new Error("History.go: History.go requires a positive or negative integer passed.");for(c=-1;c>=a;--c)m.back(b)}return m};if(m.emulated.pushState){var o=function(){};m.pushState=m.pushState||o,m.replaceState=m.replaceState||o}else m.onPopState=function(b,c){var e=!1,f=!1,g,h;return m.doubleCheckComplete(),g=m.getHash(),g?(h=m.extractState(g||d.location.href,!0),h?m.replaceState(h.data,h.title,h.url,!1):(m.Adapter.trigger(a,"anchorchange"),m.busy(!1)),m.expectedStateId=!1,!1):(e=m.Adapter.extractEventData("state",b,c)||!1,e?f=m.getStateById(e):m.expectedStateId?f=m.getStateById(m.expectedStateId):f=m.extractState(d.location.href),f||(f=m.createStateObject(null,null,d.location.href)),m.expectedStateId=!1,m.isLastSavedState(f)?(m.busy(!1),!1):(m.storeState(f),m.saveState(f),m.setTitle(f),m.Adapter.trigger(a,"statechange"),m.busy(!1),!0))},m.Adapter.bind(a,"popstate",m.onPopState),m.pushState=function(b,c,d,e){if(m.getHashByUrl(d)&&m.emulated.pushState)throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors).");if(e!==!1&&m.busy())return m.pushQueue({scope:m,callback:m.pushState,args:arguments,queue:e}),!1;m.busy(!0);var f=m.createStateObject(b,c,d);return m.isLastSavedState(f)?m.busy(!1):(m.storeState(f),m.expectedStateId=f.id,n.pushState(f.id,f.title,f.url),m.Adapter.trigger(a,"popstate")),!0},m.replaceState=function(b,c,d,e){if(m.getHashByUrl(d)&&m.emulated.pushState)throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors).");if(e!==!1&&m.busy())return m.pushQueue({scope:m,callback:m.replaceState,args:arguments,queue:e}),!1;m.busy(!0);var f=m.createStateObject(b,c,d);return m.isLastSavedState(f)?m.busy(!1):(m.storeState(f),m.expectedStateId=f.id,n.replaceState(f.id,f.title,f.url),m.Adapter.trigger(a,"popstate")),!0};if(f){try{m.store=k.parse(f.getItem("History.store"))||{}}catch(p){m.store={}}m.normalizeStore()}else m.store={},m.normalizeStore();m.Adapter.bind(a,"beforeunload",m.clearAllIntervals),m.Adapter.bind(a,"unload",m.clearAllIntervals),m.saveState(m.storeState(m.extractState(d.location.href,!0))),f&&(m.onUnload=function(){var a,b;try{a=k.parse(f.getItem("History.store"))||{}}catch(c){a={}}a.idToState=a.idToState||{},a.urlToId=a.urlToId||{},a.stateToId=a.stateToId||{};for(b in m.idToState){if(!m.idToState.hasOwnProperty(b))continue;a.idToState[b]=m.idToState[b]}for(b in m.urlToId){if(!m.urlToId.hasOwnProperty(b))continue;a.urlToId[b]=m.urlToId[b]}for(b in m.stateToId){if(!m.stateToId.hasOwnProperty(b))continue;a.stateToId[b]=m.stateToId[b]}m.store=a,m.normalizeStore(),f.setItem("History.store",k.stringify(a))},m.intervalList.push(i(m.onUnload,m.options.storeInterval)),m.Adapter.bind(a,"beforeunload",m.onUnload),m.Adapter.bind(a,"unload",m.onUnload));if(!m.emulated.pushState){m.bugs.safariPoll&&m.intervalList.push(i(m.safariStatePoll,m.options.safariPollInterval));if(e.vendor==="Apple Computer, Inc."||(e.appCodeName||"")==="Mozilla")m.Adapter.bind(a,"hashchange",function(){m.Adapter.trigger(a,"popstate")}),m.getHash()&&m.Adapter.onDomLoad(function(){m.Adapter.trigger(a,"hashchange")})}},m.init()}(window)
\ No newline at end of file
diff --git a/js/history.js/readme.txt b/js/history.js/readme.txt
deleted file mode 100644 (file)
index 1288d07..0000000
+++ /dev/null
@@ -1,2 +0,0 @@
-History.js (v1.7.1 - October 4 2011)
-http://github.com/balupton/history.js
index f03adb8abe5472f615ae0d480a466a29a2acaf33..1b3fcad36cd942ff68152a46a5aa8e3eab3265c1 100644 (file)
@@ -58,9 +58,7 @@ $sel->type_ok("short_desc", "my ID is $bug1_id");
 $sel->select_ok("f1", "label=Commenter");
 $sel->select_ok("o1", "label=is equal to");
 $sel->type_ok("v1", "\%user\%");
-$sel->click_ok("add_button");
-$sel->wait_for_page_to_load_ok(WAIT_TIME);
-$sel->title_is("Search for bugs");
+$sel->click_ok('//button[@data-action="add-row"]');
 $sel->select_ok("f2", "label=Comment");
 $sel->select_ok("o2", "label=contains the string");
 $sel->type_ok("v2", "coming buglist");
diff --git a/skins/standard/advanced-search.css b/skins/standard/advanced-search.css
new file mode 100644 (file)
index 0000000..83ce4ef
--- /dev/null
@@ -0,0 +1,157 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/.
+ *
+ * This Source Code Form is "Incompatible With Secondary Licenses", as
+ * defined by the Mozilla Public License, v. 2.0. */
+
+#custom-search {
+  display: flex;
+}
+
+#custom-search label {
+  -moz-user-select: none;
+  -webkit-user-select: none;
+  user-select: none;
+}
+
+#custom-search button.iconic {
+  display: inline-flex;
+  border-width: 0;
+  border-radius: 0;
+  padding: 0;
+  width: 24px;
+  height: 24px;
+  color: inherit;
+  background: transparent;
+  box-shadow: none;
+  text-shadow: none;
+  transition: none;
+}
+
+#custom-search button.iconic .icon,
+#custom-search button.iconic .icon::before {
+  display: inline-flex;
+  align-items: center;
+  justify-content: center;
+  width: 100%;
+  height: 100%;
+  pointer-events: auto; /* DnD doesn't work on Firefox without this */
+}
+
+#custom-search button.iconic-text {
+  display: inline-flex;
+  align-items: center;
+}
+
+#custom-search .icon::before {
+  display: inline-block;
+  font-size: 16px;
+  font-family: 'Material Icons';
+  vertical-align: top;
+}
+
+#custom-search .conditions {
+  display: flex;
+  flex-direction: column;
+  padding: 4px 0;
+}
+
+#custom-search .condition.group {
+  margin: 4px 0;
+  border: 1px solid var(--control-border-color);
+  border-radius: var(--control-border-radius);
+  padding: 8px;
+}
+
+#custom-search .condition.group [role="toolbar"] {
+  display: flex;
+  align-items: center;
+  margin: 0 -4px;
+}
+
+#custom-search .condition.group footer[role="toolbar"] {
+  justify-content: flex-end;
+}
+
+#custom-search .condition.group [role="toolbar"] > * {
+  margin: 0 4px;
+}
+
+#custom-search .condition.group [role="toolbar"] .match {
+  flex: auto;
+}
+
+#custom-search .condition.row {
+  display: flex;
+  align-items: center;
+  margin: 4px 0;
+  border-radius: 4px;
+  padding: 8px;
+  background-color: var(--secondary-region-background-color);
+}
+
+#custom-search .condition.row > * {
+  margin: 0 4px;
+}
+
+#custom-search .condition.row > input[type="text"] {
+  flex: auto;
+  min-width: 200px;
+}
+
+#custom-search .drop-target {
+  display: flex;
+  align-items: center;
+  z-index: 2;
+  margin: -16px 0;
+  height: 32px;
+}
+
+#custom-search .drop-target[aria-dropeffect="none"] {
+  pointer-events: none;
+}
+
+#custom-search .drop-target .indicator {
+  width: 100%;
+  height: 4px;
+  pointer-events: none;
+}
+
+#custom-search .drop-target.dragover .indicator {
+  background-color: rgb(var(--accent-color-blue-2));
+}
+
+#custom-search [draggable] {
+  transition: all .3s;
+}
+
+#custom-search [draggable="false"] > [data-action="grab"],
+#custom-search [draggable="false"] > [role="toolbar"] > [data-action="grab"] {
+  cursor: grab;
+}
+
+#custom-search [draggable="true"] > [data-action="grab"],
+#custom-search [draggable="true"] > [role="toolbar"] > [data-action="grab"] {
+  cursor: grabbing;
+}
+
+#custom-search [draggable="true"] {
+  color: var(--pressed-button-foreground-color) !important;
+  background-color: var(--pressed-button-background-color) !important;
+}
+
+#custom-search [data-action="grab"] .icon::before {
+  text-indent: -11px;
+  letter-spacing: -11px;
+  content: '\E5D4\E5D4';
+}
+
+#custom-search [data-action="remove"] .icon::before {
+  content: '\E5C9';
+}
+
+#custom-search [data-action^="add-"] .icon::before {
+  margin-right: 2px;
+  content: '\E145';
+}
index c243a4f9c4f78ef8b8a4db1347e164a47cb11b11..d909dd9c1b7f9db3357668831d43f90573194c3f 100644 (file)
@@ -779,6 +779,10 @@ input[type="radio"]:checked {
   background-color: var(--selected-button-background-color);
 }
 
+.buttons.toggle[role="radiogroup"] input[type="radio"]:disabled + label {
+  color: var(--disabled-button-foreground-color);
+}
+
 .buttons.toggle[role="radiogroup"] input[type="radio"]:focus + label {
   z-index: 2;
   border-color: var(--focused-control-border-color);
diff --git a/template/en/default/search/boolean-charts.html.tmpl b/template/en/default/search/boolean-charts.html.tmpl
deleted file mode 100644 (file)
index b386bab..0000000
+++ /dev/null
@@ -1,202 +0,0 @@
-[%# The contents of this file are subject to the Mozilla Public
-  # License Version 1.1 (the "License"); you may not use this file
-  # except in compliance with the License. You may obtain a copy of
-  # the License at http://www.mozilla.org/MPL/
-  #
-  # Software distributed under the License is distributed on an "AS
-  # IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
-  # implied. See the License for the specific language governing
-  # rights and limitations under the License.
-  #
-  # The Original Code is the Bugzilla Bug Tracking System.
-  #
-  # The Initial Developer of the Original Code is Netscape Communications
-  # Corporation. Portions created by Netscape are
-  # Copyright (C) 1998 Netscape Communications Corporation. All
-  # Rights Reserved.
-  #
-  # Contributor(s): Gervase Markham <gerv@gerv.net>
-  #%]
-
-[% PROCESS "global/field-descs.none.tmpl" %]
-
-[% types = [
-  "noop",
-  "equals",
-  "notequals",
-  "anyexact",
-  "substring",
-  "casesubstring",
-  "notsubstring",
-  "anywordssubstr",
-  "allwordssubstr",
-  "nowordssubstr",
-  "regexp",
-  "notregexp",
-  "lessthan",
-  "lessthaneq",
-  "greaterthan",
-  "greaterthaneq",
-  "anywords",
-  "allwords",
-  "nowords",
-  "everchanged",
-  "changedbefore",
-  "changedafter",
-  "changedfrom",
-  "changedto",
-  "changedby",
-  "matches",
-  "notmatches",
-  "isempty",
-  "isnotempty",
-] %]
-
-<div class="bz_section_title" id="custom_search_filter">
-  <div id="custom_search_query_controller" class="arrow">&#9660;</div>
-  <a id="chart" href="javascript:TUI_toggle_class('custom_search_query')">
-    Custom Search</a> <span class="section_help">Didn't find what
-      you're looking for above? This area allows for ANDs, ORs,
-      and other more complex searches.</span>
-</div>
-<div id="custom_search_filter_section"
-     class="bz_search_section custom_search_query">
-  [% SET indent_level = 0 %]
-  [% SET cond_num = 0 %]
-  [% FOREACH condition = default.custom_search %]
-    [% SET cond_num = loop.count - 1 %]
-    [% PROCESS one_condition with_buttons = 0 %]
-  [% END %]
-  [% PROCESS one_condition
-    with_buttons = 1
-    condition = { f => 'noop' }
-    cond_num = cond_num + 1 %]
-  <script [% script_nonce FILTER none %]>
-    TUI_alternates['custom_search_query'] = '&#9658;';
-    TUI_hide_default('custom_search_query');
-    TUI_alternates['custom_search_advanced'] = "Show Advanced Features";
-    TUI_hide_default('custom_search_advanced');
-  </script>
-  <script src="[% 'js/custom-search.js' FILTER version %]"></script>
-  <script src="[% 'js/history.js/native.history.js' FILTER version %]"></script>
-  <script [% script_nonce FILTER none %]>
-    redirect_html4_browsers();
-    [%# These are alternative labels for the AND and OR options in and_all_select %]
-    var cs_and_label = 'Match ALL of the following:';
-    var cs_or_label  = 'Match ANY of the following:';
-    cs_reconfigure('custom_search_last_row');
-  </script>
-</div>
-
-
-[% BLOCK one_condition %]
-  [%# Skip any conditions that don't have a field defined. %]
-  [% RETURN IF !condition.f %]
-
-  [% IF !top_level_any_shown %]
-    [% INCLUDE any_all_select
-      name = "j_top" selected = default.j_top.0
-      with_advanced_link = 1 %]
-    [% top_level_any_shown = 1 %]
-  [% END %]
-
-  [% IF condition.f == "CP" %]
-    [% indent_level = indent_level - 1 %]
-  [% END %]
-
-  <div class="custom_search_condition"
-       [% ' style="margin-left: ' _ (indent_level * 2) _ 'em"' IF indent_level %]
-       [% ' id="custom_search_last_row"' IF with_buttons %]>
-
-    [% IF previous_condition.f == "OP" %]
-      [% INCLUDE any_all_select
-        name = "j" _ (cond_num - 1)
-        selected = previous_condition.j %]
-    [% END %]
-
-    [% IF with_buttons %]
-      <button id="op_button" type="button" class="custom_search_advanced"
-              title="Start a new group of criteria, including this row"
-              onclick="custom_search_open_paren()">(</button>
-    [% END %]
-
-    [% UNLESS condition.f == "CP" %]
-      [%# This only gets hidden via custom_search_advanced if it isn't set. %]
-      <span id="custom_search_not_container_[% cond_num FILTER html %]"
-            class="custom_search_not_container
-                   [%- ' custom_search_advanced' UNLESS condition.n %]"
-            title="Search for the opposite of the criteria here">
-        <input type="checkbox" id="n[% cond_num FILTER html %]"
-               class="custom_search_form_field"
-               name="n[% cond_num FILTER html %]" value="1"
-               onclick="custom_search_not_changed([% cond_num FILTER js %])"
-               [% ' checked="checked"' IF condition.n %]>
-        <label for="n[% cond_num FILTER html %]">Not</label>
-      </span>
-    [% END %]
-
-    [% IF condition.f == "OP" %]
-      <input type="hidden" name="f[% cond_num FILTER html %]"
-             id="f[% cond_num FILTER html %]" value="OP">
-      (
-      [% indent_level = indent_level + 1 %]
-    [% ELSIF condition.f == "CP" %]
-      <input type="hidden" name="f[% cond_num FILTER html %]"
-             id="f[% cond_num FILTER html %]" value="CP">
-      )
-    [% ELSE %]
-      <select name="f[% cond_num FILTER html %]" title="Field"
-              id="f[% cond_num FILTER html %]"
-              onchange="fix_query_string(this)"
-              class="custom_search_form_field">
-        [% FOREACH field = fields %]
-          <option value="[% field.name FILTER html %]"
-                  [%~ ' selected="selected"' IF field.name == condition.f %]>
-            [% field_descs.${field.name} || field.description FILTER html %]
-          </option>
-        [% END %]
-      </select>
-
-      [% INCLUDE "search/type-select.html.tmpl"
-         name = "o${cond_num}", class = "custom_search_form_field"
-         types = types, selected = condition.o %]
-
-      <input name="v[% cond_num FILTER html %]" title="Value"
-             class="custom_search_form_field"
-             onchange="fix_query_string(this)"
-             value="[% condition.v FILTER html %]">
-    [% END %]
-
-    [% IF with_buttons %]
-      <button class="custom_search_add_button" type="button"
-              id="add_button" title="Add a new row"
-              onclick="custom_search_new_row()">+</button>
-      <span id="cp_container" [% ' class="bz_default_hidden"' IF !indent_level %]>
-        <button id="cp_button" type="button"
-                title="End this group of criteria"
-                onclick="custom_search_close_paren()">)</button>
-      </span>
-    [% END %]
-  </div>
-
-  [% previous_condition = condition %]
-[% END %]
-
-[% BLOCK any_all_select %]
-  <div class="any_all_select">
-    <select name="[% name FILTER html %]" id="[% name FILTER html %]"
-            onchange="fix_query_string(this)">
-      <option value="AND">Match ALL of the following separately:</option>
-      <option value="OR" [% ' selected="selected"' IF selected == "OR" %]>
-        Match ANY of the following separately:</option>
-      <option value="AND_G" [% ' selected' IF selected == "AND_G" %]>
-        Match ALL of the following against the same field:</option>
-    </select>
-    [% IF with_advanced_link %]
-      <a id="custom_search_advanced_controller"
-         href="javascript:TUI_toggle_class('custom_search_advanced')">
-        Hide Advanced Features
-      </a>
-    [% END %]
-  </div>
-[% END %]
diff --git a/template/en/default/search/custom-search.html.tmpl b/template/en/default/search/custom-search.html.tmpl
new file mode 100644 (file)
index 0000000..25ba41c
--- /dev/null
@@ -0,0 +1,83 @@
+[%# This Source Code Form is subject to the terms of the Mozilla Public
+  # License, v. 2.0. If a copy of the MPL was not distributed with this
+  # file, You can obtain one at http://mozilla.org/MPL/2.0/.
+  #
+  # This Source Code Form is "Incompatible With Secondary Licenses", as
+  # defined by the Mozilla Public License, v. 2.0.
+  #%]
+
+[%
+
+PROCESS "global/field-descs.none.tmpl";
+
+_initial = {
+  j_top       => initial.j_top.0 || "AND",
+  conditions  => initial.custom_search || [],
+};
+
+_fields = [];
+
+FOREACH field = fields;
+  _fields.push({ value => field.name, label => field_descs.${field.name} || field.description});
+END;
+
+types = [
+  "noop",
+  "equals", "notequals",
+  "anyexact",
+  "substring", "casesubstring", "notsubstring",
+  "anywordssubstr", "allwordssubstr", "nowordssubstr",
+  "regexp", "notregexp",
+  "lessthan", "lessthaneq", "greaterthan", "greaterthaneq",
+  "anywords", "allwords", "nowords",
+  "everchanged", "changedbefore", "changedafter",
+  "changedfrom", "changedto",
+  "changedby",
+  "matches", "notmatches",
+  "isempty", "isnotempty",
+];
+_types = [];
+
+FOREACH type = types;
+  _types.push({ value => type, label => search_descs.$type });
+END;
+
+# Use single quotes because some strigs contain variables to be replaced in the code
+_strings = {
+  add_group         => 'Add New Group',
+  add_row           => 'Add New Row',
+  field             => 'Field',
+  grab              => 'Drag to Move',
+  group             => 'Group',
+  group_name        => 'Group { $count }',
+  join_options      => 'Join Options',
+  match_all         => 'Match All',
+  match_all_hint    => 'Match all of the following separately',
+  match_all_g       => 'Match All (Same Field)',
+  match_all_g_hint  => 'Match all of the following against the same field',
+  match_any         => 'Match Any',
+  match_any_hint    => 'Match any of the following separately',
+  'not'             => 'Not',
+  operator          => 'Operator',
+  remove            => 'Remove',
+  row               => 'Row',
+  row_name          => 'Row { $count }',
+  value             => 'Value',
+};
+
+%]
+
+<div class="bz_section_title" id="custom_search_filter">
+  <div id="custom_search_query_controller" class="arrow">&#9660;</div>
+  <a id="chart" href="javascript:TUI_toggle_class('custom_search_query')">Custom Search</a>
+  <span class="section_help">
+    Didn’t find what you’re looking for above? This area allows for ANDs, ORs, and other more complex searches.
+  </span>
+</div>
+
+<div id="custom-search" class="bz_search_section custom_search_query"
+     data-initial="[% json_encode(_initial) FILTER html %]"
+     data-fields="[% json_encode(_fields) FILTER html %]"
+     data-types="[% json_encode(_types) FILTER html %]"
+     data-strings="[% json_encode(_strings) FILTER html %]">
+</div>
index d330bca7cf2d23ec5e2aeb0a5079357b0cf38531..0bd57d88fdc46c024c2a0767a8a349a96974c117 100644 (file)
@@ -111,10 +111,12 @@ function doOnSelectProduct(selectmode) {
 TUI_alternates['history_query'] = '&#9658;';
 TUI_alternates['people_query'] = '&#9658;';
 TUI_alternates['information_query'] = '&#9658;';
+TUI_alternates['custom_search_query'] = '&#9658;';
 
 TUI_hide_default('history_query');
 TUI_hide_default('people_query');
 TUI_hide_default('information_query');
+TUI_hide_default('custom_search_query');
 </script>
 
 [% query_types = [
index 281e53d4bdf6c3728f09e4be7ff034ed6173aefe..b0dc858000dfc3d70e811f3402f9989d59322ba9 100644 (file)
@@ -21,7 +21,7 @@
 [%# INTERFACE:
   # This template has no interface. However, to use it, you need to fulfill
   # the interfaces of search/form.html.tmpl, search/knob.html.tmpl and
-  # search/boolean-charts.html.tmpl.
+  # search/custom-search.html.tmpl.
   #%]
 
 [% PROCESS global/variables.none.tmpl %]
@@ -45,8 +45,8 @@ function remove_token() {
   generate_api_token = 1
   onload = "doOnSelectProduct(0);"
   javascript = js_data
-  javascript_urls = [ "js/productform.js", "js/TUI.js", "js/field.js"]
-  style_urls = [ "skins/standard/search_form.css" ]
+  javascript_urls = [ "js/productform.js", "js/TUI.js", "js/field.js", "js/advanced-search.js" ]
+  style_urls = [ "skins/standard/search_form.css", "skins/standard/advanced-search.css" ]
   doc_section = "query.html"
   style = "dl.bug_changes dt {
              margin-top: 15px;
@@ -64,7 +64,7 @@ function remove_token() {
 
 [% PROCESS search/form.html.tmpl %]
 
-[% PROCESS "search/boolean-charts.html.tmpl" %]
+[% PROCESS "search/custom-search.html.tmpl" %]
 
 [% PROCESS search/knob.html.tmpl %]
 
index 6dd2211bbe7029bbd164225d9a0cd13340fe3ce8..64be10571ec4a21e5ae9215fae1f9b15eba1a00a 100644 (file)
@@ -21,7 +21,7 @@
 [%# INTERFACE:
   # This template has no interface. However, to use it, you need to fulfill
   # the interfaces of search/form.html.tmpl, reports/series.html.tmpl and
-  # search/boolean-charts.html.tmpl.
+  # search/custom-search.html.tmpl.
   #%]
 
 [% PROCESS global/variables.none.tmpl %]
@@ -35,8 +35,8 @@
   generate_api_token = 1
   onload = "doOnSelectProduct(0);"
   javascript = js_data
-  javascript_urls = [ "js/productform.js", "js/TUI.js", "js/field.js" ]
-  style_urls = [ "skins/standard/search_form.css" ]
+  javascript_urls = [ "js/productform.js", "js/TUI.js", "js/field.js", "js/advanced-search.js" ]
+  style_urls = [ "skins/standard/search_form.css", "skins/standard/advanced-search.css" ]
   doc_section = "reporting.html#charts-new-series"
 %]
 
@@ -64,7 +64,7 @@
 
 <hr>
 
-[% PROCESS "search/boolean-charts.html.tmpl" %]
+[% PROCESS "search/custom-search.html.tmpl" %]
 
 </form>
 
index 89778ed71a04705698b08023abd17162c42ea1ca..ab321f534200099d7cfe14f007bfc4920304491b 100644 (file)
@@ -34,8 +34,8 @@ var queryform = "reportform"
   generate_api_token = 1
   onload = "doOnSelectProduct(0); chartTypeChanged()"
   javascript = js_data
-  javascript_urls = [ "js/productform.js", "js/TUI.js", "js/field.js" ]
-  style_urls = [ "skins/standard/search_form.css" ]
+  javascript_urls = [ "js/productform.js", "js/TUI.js", "js/field.js", "js/advanced-search.js" ]
+  style_urls = [ "skins/standard/search_form.css", "skins/standard/advanced-search.css" ]
   doc_section = "reporting.html#reports"
 %]
 
@@ -130,7 +130,7 @@ var queryform = "reportform"
 
 [% PROCESS search/form.html.tmpl %]
 
-[% PROCESS "search/boolean-charts.html.tmpl" %]
+[% PROCESS "search/custom-search.html.tmpl" %]
 
   <div id="knob">
     <input type="submit" id="[% button_name FILTER css_class_quote %]"
index cd30fbbe5836dc72f42fe307ed0def46ecc11b16..b98b031a33dcc8e0c6c12af066b2b0de3f159d25 100644 (file)
@@ -34,8 +34,8 @@ var queryform = "reportform"
   generate_api_token = 1
   onload = "doOnSelectProduct(0)"
   javascript = js_data
-  javascript_urls = [ "js/productform.js", "js/TUI.js", "js/field.js" ]
-  style_urls = [ "skins/standard/search_form.css" ]
+  javascript_urls = [ "js/productform.js", "js/TUI.js", "js/field.js", "js/advanced-search.js" ]
+  style_urls = [ "skins/standard/search_form.css", "skins/standard/advanced-search.css" ]
   doc_section = "reporting.html#reports"
 %]
 
@@ -82,7 +82,7 @@ var queryform = "reportform"
 
   [% PROCESS search/form.html.tmpl %]
 
-  [% PROCESS "search/boolean-charts.html.tmpl" %]
+  [% PROCESS "search/custom-search.html.tmpl" %]
 
   <div id="knob">
     <input type="submit" id="[% button_name FILTER css_class_quote %]"