{"version":3,"file":"sortable.cjs","names":["getSecureRandomIfPossible"],"sources":["../../../src/common/data/sortable.ts"],"sourcesContent":["import { getSecureRandomIfPossible } from './math'\n\n// Get a sort_weight suitable for adding to top of list\n// Original idea https://holtwick.de/en/blog/smart-table-reordering\n\nexport interface SortableItem {\n  sort_weight: number\n}\n\nexport function startSortWeight(items: SortableItem[]): number {\n  return (\n    items.reduce((acc, item) => Math.min(acc, item.sort_weight || 0), 0)\n    - 1\n    - getSecureRandomIfPossible()\n  )\n}\n\n// Get a sort_weight suitable for adding to end of list\nexport function endSortWeight(items: SortableItem[]): number {\n  return (\n    items.reduce((acc, item) => Math.max(acc, item.sort_weight || 0), 0)\n    + 1\n    + getSecureRandomIfPossible()\n  )\n}\n\n// The real magic\nexport function moveSortWeight(\n  newIndex: number,\n  oldIndex: number,\n  items: SortableItem[],\n): number {\n  const count = items.length\n\n  const moveLower = newIndex < oldIndex\n  if (count <= 0 || newIndex >= count - 1)\n    return endSortWeight(items)\n\n  if (newIndex <= 0)\n    return startSortWeight(items)\n\n  // Make sure they are sorted\n  items = sortedItems([...items])\n\n  const step = moveLower ? -1 : 0 // use Math.sign(?) for performance?\n  const lower = items[newIndex + step].sort_weight || 0\n  const upper = items[newIndex + step + 1].sort_weight || 0\n  const distance = upper - lower\n  if (distance === 0) {\n    // Ugly list with no presets, make the best guess\n    if (moveLower)\n      return startSortWeight(items)\n\n    return endSortWeight(items)\n  }\n  const middle = lower + distance / 2\n  const fuzzy = distance * 0.01 * (getSecureRandomIfPossible() - 0.5) // 1% fuzziness to avoid conflicts\n  return middle + fuzzy\n}\n\nexport function sortedItems<T extends SortableItem>(items: T[]): T[] {\n  items.sort((a, b) => (a.sort_weight || 0) - (b.sort_weight || 0))\n  return items\n}\n"],"mappings":";;;;AASA,SAAgB,gBAAgB,OAA+B;AAC7D,QACE,MAAM,QAAQ,KAAK,SAAS,KAAK,IAAI,KAAK,KAAK,eAAe,EAAE,EAAE,EAAE,GAClE,IACAA,oDAA2B;;AAKjC,SAAgB,cAAc,OAA+B;AAC3D,QACE,MAAM,QAAQ,KAAK,SAAS,KAAK,IAAI,KAAK,KAAK,eAAe,EAAE,EAAE,EAAE,GAClE,IACAA,oDAA2B;;AAKjC,SAAgB,eACd,UACA,UACA,OACQ;CACR,MAAM,QAAQ,MAAM;CAEpB,MAAM,YAAY,WAAW;AAC7B,KAAI,SAAS,KAAK,YAAY,QAAQ,EACpC,QAAO,cAAc,MAAM;AAE7B,KAAI,YAAY,EACd,QAAO,gBAAgB,MAAM;AAG/B,SAAQ,YAAY,CAAC,GAAG,MAAM,CAAC;CAE/B,MAAM,OAAO,YAAY,KAAK;CAC9B,MAAM,QAAQ,MAAM,WAAW,MAAM,eAAe;CAEpD,MAAM,YADQ,MAAM,WAAW,OAAO,GAAG,eAAe,KAC/B;AACzB,KAAI,aAAa,GAAG;AAElB,MAAI,UACF,QAAO,gBAAgB,MAAM;AAE/B,SAAO,cAAc,MAAM;;AAI7B,QAFe,QAAQ,WAAW,IACpB,WAAW,OAAQA,oDAA2B,GAAG;;AAIjE,SAAgB,YAAoC,OAAiB;AACnE,OAAM,MAAM,GAAG,OAAO,EAAE,eAAe,MAAM,EAAE,eAAe,GAAG;AACjE,QAAO"}