feat(ui): New sidebar & search UI (#831)

This commit is contained in:
Alex
2026-05-04 09:46:48 +01:00
committed by GitHub
parent c9b2a5734e
commit f3138a88c5
182 changed files with 8318 additions and 4660 deletions
+18 -54
View File
@@ -1,62 +1,26 @@
<svg width="2500" height="350" viewBox="0 0 2500 350" fill="none" xmlns="http://www.w3.org/2000/svg">
<g clip-path="url(#clip0_2_81)">
<g clip-path="url(#sidebar-brand-wordmark-clip)">
<path d="M71.8311 296.149V314.103V332.047V350L89.7839 332.047L107.747 350V332.047V314.103V296.149H71.8311Z" fill="white"/>
<path d="M1748.64 102.654H1701.96C1691.71 102.654 1683.37 110.983 1683.37 121.23V165.376C1683.37 175.622 1691.7 183.952 1701.96 183.952H1748.64C1757.49 183.952 1764.7 176.746 1764.7 167.895V118.721C1764.7 109.869 1757.49 102.664 1748.64 102.664V102.654Z" fill="#ED8A22"/>
<path d="M896.673 102.654H852.504C842.263 102.654 833.919 110.983 833.919 121.23V167.885C833.919 176.736 841.128 183.942 849.984 183.942H899.184C908.039 183.942 915.249 176.736 915.249 167.885V121.23C915.249 110.983 906.915 102.654 896.663 102.654H896.673Z" fill="#ED8A22"/>
<path d="M653.709 183.942H697.878C708.119 183.942 716.463 175.612 716.463 165.366V118.711C716.463 109.859 709.254 102.654 700.398 102.654H651.199C642.343 102.654 635.134 109.859 635.134 118.711V165.366C635.134 175.612 643.467 183.942 653.719 183.942H653.709Z" fill="#ED8A22"/>
<path d="M107.747 80.7661H269.361C274.322 80.7661 278.338 76.7519 278.338 71.7944V8.97179C278.338 4.01422 274.322 0 269.361 0H35.9155C29.369 0 23.2442 1.75622 17.9527 4.81707C12.5007 7.96823 7.96226 12.5043 4.80949 17.9536C1.75712 23.2323 0 29.354 0 35.8972V296.149C0 315.979 16.0751 332.046 35.9155 332.046H58.8786V314.103H35.9155C25.9953 314.103 17.9527 306.064 17.9527 296.149C17.9527 286.234 25.9953 278.196 35.9155 278.196H260.385C270.305 278.196 278.348 270.157 278.348 260.242V116.663C278.348 106.748 270.305 98.7097 260.385 98.7097H107.747C102.786 98.7097 98.7702 102.724 98.7702 107.681V170.504C98.7702 175.462 102.786 179.476 107.747 179.476H188.554C193.514 179.476 197.53 183.49 197.53 188.448C197.53 193.405 193.514 197.419 188.554 197.419H107.747C92.8663 197.419 80.8074 185.367 80.8074 170.494V107.671C80.8074 92.7988 92.8663 80.7461 107.747 80.7461V80.7661Z" fill="url(#paint0_linear_2_81)"/>
<path d="M269.361 314.103H121.231V332.046H269.361C274.322 332.046 278.338 328.032 278.338 323.075C278.338 318.117 274.322 314.103 269.361 314.103Z" fill="url(#paint1_linear_2_81)"/>
<path d="M1620.14 3.3017C1600.16 3.3017 1583.98 19.489 1583.98 39.4498V248.099C1583.98 267.538 1599.74 283.294 1619.19 283.294H1847.17C1856.53 283.294 1864.11 275.717 1864.11 266.364V19.6898C1864.11 10.6377 1856.77 3.3017 1847.72 3.3017H1620.14ZM1782.77 167.885C1782.77 186.701 1767.46 202.006 1748.64 202.006H1701.96C1681.74 202.006 1665.3 185.567 1665.3 165.366V121.219C1665.3 101.018 1681.74 84.5796 1701.96 84.5796H1748.64C1767.46 84.5796 1782.77 99.8839 1782.77 118.701V167.885Z" fill="url(#paint2_linear_2_81)"/>
<path d="M849.994 202.006C831.168 202.006 815.856 186.701 815.856 167.885V121.229C815.856 101.028 832.302 84.5897 852.514 84.5897H896.683C897.527 84.5897 898.37 84.6298 899.204 84.69V84.5897C908.059 84.5897 915.269 77.3842 915.269 68.5328V19.6898C915.269 10.6377 907.929 3.3017 898.872 3.3017H671.31C651.329 3.3017 635.144 19.489 635.144 39.4498V68.5328C635.144 77.3842 642.353 84.5897 651.209 84.5897H700.408C719.234 84.5897 734.546 99.8939 734.546 118.711V165.366C734.546 185.567 718.1 202.006 697.888 202.006H653.719C652.875 202.006 652.032 201.966 651.199 201.905V202.006C642.343 202.006 635.134 209.211 635.134 218.063V248.099C635.134 267.538 650.897 283.294 670.346 283.294H898.33C907.688 283.294 915.269 275.717 915.269 266.364V218.063C915.269 209.211 908.059 202.006 899.204 202.006H849.994Z" fill="url(#paint3_linear_2_81)"/>
<path d="M1215.14 3.3017H987.582C967.601 3.3017 951.415 19.489 951.415 39.4498V248.099C951.415 267.538 967.179 283.294 986.628 283.294H1016.52C1025.37 283.294 1032.58 276.088 1032.58 267.237V93.6217C1032.58 88.634 1036.63 84.5897 1041.62 84.5897C1046.61 84.5897 1050.66 88.634 1050.66 93.6217V267.417C1050.76 276.188 1057.92 283.294 1066.71 283.294H1116.07C1124.93 283.294 1132.14 276.088 1132.14 267.237V93.6217C1132.14 88.634 1136.18 84.5897 1141.17 84.5897C1146.16 84.5897 1150.21 88.634 1150.21 93.6217V267.237C1150.21 276.088 1157.41 283.294 1166.28 283.294H1214.6C1223.96 283.294 1231.54 275.717 1231.54 266.364V19.6898C1231.54 10.6377 1224.2 3.3017 1215.14 3.3017Z" fill="url(#paint4_linear_2_81)"/>
<path d="M1531.43 3.3017H1303.86C1283.88 3.3017 1267.7 19.489 1267.7 39.4498V248.099C1267.7 267.538 1283.46 283.294 1302.91 283.294H1332.8C1341.66 283.294 1348.87 276.088 1348.87 267.237V93.6217C1348.87 88.634 1352.91 84.5897 1357.9 84.5897C1362.89 84.5897 1366.94 88.634 1366.94 93.6217V267.417C1367.04 276.188 1374.2 283.294 1382.99 283.294H1432.35C1441.21 283.294 1448.42 276.088 1448.42 267.237V93.6217C1448.42 88.634 1452.47 84.5897 1457.46 84.5897C1462.45 84.5897 1466.49 88.634 1466.49 93.6217V267.237C1466.49 276.088 1473.69 283.294 1482.56 283.294H1530.88C1540.24 283.294 1547.82 275.717 1547.82 266.364V19.6898C1547.82 10.6377 1540.48 3.3017 1531.43 3.3017Z" fill="url(#paint5_linear_2_81)"/>
<path d="M2090.02 202.006C2085.03 202.006 2080.98 197.961 2080.98 192.974C2080.98 187.986 2085.03 183.942 2090.02 183.942H2164.32C2173.18 183.942 2180.38 176.736 2180.38 167.885V19.6898C2180.38 10.6377 2173.05 3.3017 2163.99 3.3017H1936.43C1916.45 3.3017 1900.26 19.489 1900.26 39.4498V248.099C1900.26 267.538 1916.02 283.294 1935.47 283.294H1965.52C1974.38 283.294 1981.59 276.088 1981.59 267.237V247.216C1981.59 247.216 1981.59 247.186 1981.59 247.166V192.974C1981.59 187.986 1985.64 183.942 1990.63 183.942C1995.62 183.942 1999.66 187.986 1999.66 192.974V247.216C1999.68 267.116 2015.89 283.294 2035.81 283.294H2163.46C2172.81 283.294 2180.4 275.717 2180.4 266.364V218.063C2180.4 209.211 2173.19 202.006 2164.33 202.006H2090.02ZM1990.62 102.684C1985.63 102.684 1981.58 98.6395 1981.58 93.6518C1981.58 88.6641 1985.63 84.6198 1990.62 84.6198H2090.02C2095.01 84.6198 2099.06 88.6641 2099.06 93.6518C2099.06 98.6395 2095.01 102.684 2090.02 102.684H1990.62Z" fill="url(#paint6_linear_2_81)"/>
<path d="M508.611 202.006C503.621 202.006 499.574 197.961 499.574 192.974C499.574 187.986 503.621 183.942 508.611 183.942H582.912C591.768 183.942 598.977 176.736 598.977 167.885V19.6898C598.977 10.6377 591.637 3.3017 582.581 3.3017H355.019C335.038 3.3017 318.852 19.489 318.852 39.4498V248.099C318.852 267.538 334.616 283.294 354.065 283.294H384.116C392.972 283.294 400.182 276.088 400.182 267.237V247.216C400.182 247.216 400.182 247.186 400.182 247.166V192.974C400.182 187.986 404.228 183.942 409.218 183.942C414.208 183.942 418.255 187.986 418.255 192.974V247.216C418.275 267.116 434.481 283.294 454.401 283.294H582.048C591.406 283.294 598.987 275.717 598.987 266.364V218.063C598.987 209.211 591.778 202.006 582.922 202.006H508.611ZM409.208 102.684C404.218 102.684 400.171 98.6395 400.171 93.6518C400.171 88.6641 404.218 84.6198 409.208 84.6198H508.611C513.601 84.6198 517.647 88.6641 517.647 93.6518C517.647 98.6395 513.601 102.684 508.611 102.684H409.208Z" fill="url(#paint7_linear_2_81)"/>
<path d="M2480.27 3.3017H2379.19C2370.33 3.3017 2363.13 10.5072 2363.13 19.3586V93.6217C2363.13 98.6094 2359.08 102.654 2354.09 102.654C2349.1 102.654 2345.05 98.6094 2345.05 93.6217V19.3586C2345.05 10.5072 2337.84 3.3017 2328.99 3.3017H2252.7C2232.72 3.3017 2216.53 19.489 2216.53 39.4498V147.814C2216.53 167.734 2232.75 183.942 2252.68 183.942H2406.3C2411.29 183.942 2415.34 187.986 2415.34 192.974C2415.34 197.961 2411.29 202.006 2406.3 202.006H2232.43C2223.65 202.096 2216.53 209.261 2216.53 218.053V248.089C2216.53 267.528 2232.3 283.284 2251.74 283.284H2479.73C2489.09 283.284 2496.67 275.707 2496.67 266.354V19.6898C2496.67 10.6377 2489.33 3.3017 2480.27 3.3017Z" fill="url(#paint8_linear_2_81)"/>
<path d="M2491.43 314.103H327.818C322.858 314.103 318.842 318.117 318.842 323.075C318.842 328.032 322.858 332.046 327.818 332.046H2491.43C2496.39 332.046 2500.4 328.032 2500.4 323.075C2500.4 318.117 2496.39 314.103 2491.43 314.103Z" fill="url(#paint9_linear_2_81)"/>
<path d="M1748.64 102.654H1701.96C1691.71 102.654 1683.37 110.983 1683.37 121.23V165.376C1683.37 175.622 1691.7 183.952 1701.96 183.952H1748.64C1757.49 183.952 1764.7 176.746 1764.7 167.895V118.721C1764.7 109.869 1757.49 102.664 1748.64 102.664V102.654Z" style="fill: var(--p-primary-400, #ED8A22)"/>
<path d="M896.673 102.654H852.504C842.263 102.654 833.919 110.983 833.919 121.23V167.885C833.919 176.736 841.128 183.942 849.984 183.942H899.184C908.039 183.942 915.249 176.736 915.249 167.885V121.23C915.249 110.983 906.915 102.654 896.663 102.654H896.673Z" style="fill: var(--p-primary-400, #ED8A22)"/>
<path d="M653.709 183.942H697.878C708.119 183.942 716.463 175.612 716.463 165.366V118.711C716.463 109.859 709.254 102.654 700.398 102.654H651.199C642.343 102.654 635.134 109.859 635.134 118.711V165.366C635.134 175.612 643.467 183.942 653.719 183.942H653.709Z" style="fill: var(--p-primary-400, #ED8A22)"/>
<path d="M107.747 80.7661H269.361C274.322 80.7661 278.338 76.7519 278.338 71.7944V8.97179C278.338 4.01422 274.322 0 269.361 0H35.9155C29.369 0 23.2442 1.75622 17.9527 4.81707C12.5007 7.96823 7.96226 12.5043 4.80949 17.9536C1.75712 23.2323 0 29.354 0 35.8972V296.149C0 315.979 16.0751 332.046 35.9155 332.046H58.8786V314.103H35.9155C25.9953 314.103 17.9527 306.064 17.9527 296.149C17.9527 286.234 25.9953 278.196 35.9155 278.196H260.385C270.305 278.196 278.348 270.157 278.348 260.242V116.663C278.348 106.748 270.305 98.7097 260.385 98.7097H107.747C102.786 98.7097 98.7702 102.724 98.7702 107.681V170.504C98.7702 175.462 102.786 179.476 107.747 179.476H188.554C193.514 179.476 197.53 183.49 197.53 188.448C197.53 193.405 193.514 197.419 188.554 197.419H107.747C92.8663 197.419 80.8074 185.367 80.8074 170.494V107.671C80.8074 92.7988 92.8663 80.7461 107.747 80.7461V80.7661Z" fill="url(#sidebar-brand-wordmark-gradient)"/>
<path d="M269.361 314.103H121.231V332.046H269.361C274.322 332.046 278.338 328.032 278.338 323.075C278.338 318.117 274.322 314.103 269.361 314.103Z" fill="url(#sidebar-brand-wordmark-gradient)"/>
<path d="M1620.14 3.3017C1600.16 3.3017 1583.98 19.489 1583.98 39.4498V248.099C1583.98 267.538 1599.74 283.294 1619.19 283.294H1847.17C1856.53 283.294 1864.11 275.717 1864.11 266.364V19.6898C1864.11 10.6377 1856.77 3.3017 1847.72 3.3017H1620.14ZM1782.77 167.885C1782.77 186.701 1767.46 202.006 1748.64 202.006H1701.96C1681.74 202.006 1665.3 185.567 1665.3 165.366V121.219C1665.3 101.018 1681.74 84.5796 1701.96 84.5796H1748.64C1767.46 84.5796 1782.77 99.8839 1782.77 118.701V167.885Z" fill="url(#sidebar-brand-wordmark-gradient)"/>
<path d="M849.994 202.006C831.168 202.006 815.856 186.701 815.856 167.885V121.229C815.856 101.028 832.302 84.5897 852.514 84.5897H896.683C897.527 84.5897 898.37 84.6298 899.204 84.69V84.5897C908.059 84.5897 915.269 77.3842 915.269 68.5328V19.6898C915.269 10.6377 907.929 3.3017 898.872 3.3017H671.31C651.329 3.3017 635.144 19.489 635.144 39.4498V68.5328C635.144 77.3842 642.353 84.5897 651.209 84.5897H700.408C719.234 84.5897 734.546 99.8939 734.546 118.711V165.366C734.546 185.567 718.1 202.006 697.888 202.006H653.719C652.875 202.006 652.032 201.966 651.199 201.905V202.006C642.343 202.006 635.134 209.211 635.134 218.063V248.099C635.134 267.538 650.897 283.294 670.346 283.294H898.33C907.688 283.294 915.269 275.717 915.269 266.364V218.063C915.269 209.211 908.059 202.006 899.204 202.006H849.994Z" fill="url(#sidebar-brand-wordmark-gradient)"/>
<path d="M1215.14 3.3017H987.582C967.601 3.3017 951.415 19.489 951.415 39.4498V248.099C951.415 267.538 967.179 283.294 986.628 283.294H1016.52C1025.37 283.294 1032.58 276.088 1032.58 267.237V93.6217C1032.58 88.634 1036.63 84.5897 1041.62 84.5897C1046.61 84.5897 1050.66 88.634 1050.66 93.6217V267.417C1050.76 276.188 1057.92 283.294 1066.71 283.294H1116.07C1124.93 283.294 1132.14 276.088 1132.14 267.237V93.6217C1132.14 88.634 1136.18 84.5897 1141.17 84.5897C1146.16 84.5897 1150.21 88.634 1150.21 93.6217V267.237C1150.21 276.088 1157.41 283.294 1166.28 283.294H1214.6C1223.96 283.294 1231.54 275.717 1231.54 266.364V19.6898C1231.54 10.6377 1224.2 3.3017 1215.14 3.3017Z" fill="url(#sidebar-brand-wordmark-gradient)"/>
<path d="M1531.43 3.3017H1303.86C1283.88 3.3017 1267.7 19.489 1267.7 39.4498V248.099C1267.7 267.538 1283.46 283.294 1302.91 283.294H1332.8C1341.66 283.294 1348.87 276.088 1348.87 267.237V93.6217C1348.87 88.634 1352.91 84.5897 1357.9 84.5897C1362.89 84.5897 1366.94 88.634 1366.94 93.6217V267.417C1367.04 276.188 1374.2 283.294 1382.99 283.294H1432.35C1441.21 283.294 1448.42 276.088 1448.42 267.237V93.6217C1448.42 88.634 1452.47 84.5897 1457.46 84.5897C1462.45 84.5897 1466.49 88.634 1466.49 93.6217V267.237C1466.49 276.088 1473.69 283.294 1482.56 283.294H1530.88C1540.24 283.294 1547.82 275.717 1547.82 266.364V19.6898C1547.82 10.6377 1540.48 3.3017 1531.43 3.3017Z" fill="url(#sidebar-brand-wordmark-gradient)"/>
<path d="M2090.02 202.006C2085.03 202.006 2080.98 197.961 2080.98 192.974C2080.98 187.986 2085.03 183.942 2090.02 183.942H2164.32C2173.18 183.942 2180.38 176.736 2180.38 167.885V19.6898C2180.38 10.6377 2173.05 3.3017 2163.99 3.3017H1936.43C1916.45 3.3017 1900.26 19.489 1900.26 39.4498V248.099C1900.26 267.538 1916.02 283.294 1935.47 283.294H1965.52C1974.38 283.294 1981.59 276.088 1981.59 267.237V247.216C1981.59 247.216 1981.59 247.186 1981.59 247.166V192.974C1981.59 187.986 1985.64 183.942 1990.63 183.942C1995.62 183.942 1999.66 187.986 1999.66 192.974V247.216C1999.68 267.116 2015.89 283.294 2035.81 283.294H2163.46C2172.81 283.294 2180.4 275.717 2180.4 266.364V218.063C2180.4 209.211 2173.19 202.006 2164.33 202.006H2090.02ZM1990.62 102.684C1985.63 102.684 1981.58 98.6395 1981.58 93.6518C1981.58 88.6641 1985.63 84.6198 1990.62 84.6198H2090.02C2095.01 84.6198 2099.06 88.6641 2099.06 93.6518C2099.06 98.6395 2095.01 102.684 2090.02 102.684H1990.62Z" fill="url(#sidebar-brand-wordmark-gradient)"/>
<path d="M508.611 202.006C503.621 202.006 499.574 197.961 499.574 192.974C499.574 187.986 503.621 183.942 508.611 183.942H582.912C591.768 183.942 598.977 176.736 598.977 167.885V19.6898C598.977 10.6377 591.637 3.3017 582.581 3.3017H355.019C335.038 3.3017 318.852 19.489 318.852 39.4498V248.099C318.852 267.538 334.616 283.294 354.065 283.294H384.116C392.972 283.294 400.182 276.088 400.182 267.237V247.216C400.182 247.216 400.182 247.186 400.182 247.166V192.974C400.182 187.986 404.228 183.942 409.218 183.942C414.208 183.942 418.255 187.986 418.255 192.974V247.216C418.275 267.116 434.481 283.294 454.401 283.294H582.048C591.406 283.294 598.987 275.717 598.987 266.364V218.063C598.987 209.211 591.778 202.006 582.922 202.006H508.611ZM409.208 102.684C404.218 102.684 400.171 98.6395 400.171 93.6518C400.171 88.6641 404.218 84.6198 409.208 84.6198H508.611C513.601 84.6198 517.647 88.6641 517.647 93.6518C517.647 98.6395 513.601 102.684 508.611 102.684H409.208Z" fill="url(#sidebar-brand-wordmark-gradient)"/>
<path d="M2480.27 3.3017H2379.19C2370.33 3.3017 2363.13 10.5072 2363.13 19.3586V93.6217C2363.13 98.6094 2359.08 102.654 2354.09 102.654C2349.1 102.654 2345.05 98.6094 2345.05 93.6217V19.3586C2345.05 10.5072 2337.84 3.3017 2328.99 3.3017H2252.7C2232.72 3.3017 2216.53 19.489 2216.53 39.4498V147.814C2216.53 167.734 2232.75 183.942 2252.68 183.942H2406.3C2411.29 183.942 2415.34 187.986 2415.34 192.974C2415.34 197.961 2411.29 202.006 2406.3 202.006H2232.43C2223.65 202.096 2216.53 209.261 2216.53 218.053V248.089C2216.53 267.528 2232.3 283.284 2251.74 283.284H2479.73C2489.09 283.284 2496.67 275.707 2496.67 266.354V19.6898C2496.67 10.6377 2489.33 3.3017 2480.27 3.3017Z" fill="url(#sidebar-brand-wordmark-gradient)"/>
<path d="M2491.43 314.103H327.818C322.858 314.103 318.842 318.117 318.842 323.075C318.842 328.032 322.858 332.046 327.818 332.046H2491.43C2496.39 332.046 2500.4 328.032 2500.4 323.075C2500.4 318.117 2496.39 314.103 2491.43 314.103Z" fill="url(#sidebar-brand-wordmark-gradient)"/>
</g>
<defs>
<linearGradient id="paint0_linear_2_81" x1="1250.2" y1="0" x2="1250.2" y2="332.046" gradientUnits="userSpaceOnUse">
<stop stop-color="#FBB042"/>
<stop offset="1" stop-color="#F16422"/>
<linearGradient id="sidebar-brand-wordmark-gradient" x1="1250.2" y1="0" x2="1250.2" y2="332.046" gradientUnits="userSpaceOnUse">
<stop offset="0" style="stop-color: var(--p-primary-300, #FBB042)"/>
<stop offset="1" style="stop-color: var(--p-primary-500, #F16422)"/>
</linearGradient>
<linearGradient id="paint1_linear_2_81" x1="1250.2" y1="0" x2="1250.2" y2="332.046" gradientUnits="userSpaceOnUse">
<stop stop-color="#FBB042"/>
<stop offset="1" stop-color="#F16422"/>
</linearGradient>
<linearGradient id="paint2_linear_2_81" x1="1250.2" y1="0" x2="1250.2" y2="332.046" gradientUnits="userSpaceOnUse">
<stop stop-color="#FBB042"/>
<stop offset="1" stop-color="#F16422"/>
</linearGradient>
<linearGradient id="paint3_linear_2_81" x1="1250.2" y1="0" x2="1250.2" y2="332.046" gradientUnits="userSpaceOnUse">
<stop stop-color="#FBB042"/>
<stop offset="1" stop-color="#F16422"/>
</linearGradient>
<linearGradient id="paint4_linear_2_81" x1="1250.2" y1="0" x2="1250.2" y2="332.046" gradientUnits="userSpaceOnUse">
<stop stop-color="#FBB042"/>
<stop offset="1" stop-color="#F16422"/>
</linearGradient>
<linearGradient id="paint5_linear_2_81" x1="1250.2" y1="0" x2="1250.2" y2="332.046" gradientUnits="userSpaceOnUse">
<stop stop-color="#FBB042"/>
<stop offset="1" stop-color="#F16422"/>
</linearGradient>
<linearGradient id="paint6_linear_2_81" x1="1250.2" y1="0" x2="1250.2" y2="332.046" gradientUnits="userSpaceOnUse">
<stop stop-color="#FBB042"/>
<stop offset="1" stop-color="#F16422"/>
</linearGradient>
<linearGradient id="paint7_linear_2_81" x1="1250.2" y1="0" x2="1250.2" y2="332.046" gradientUnits="userSpaceOnUse">
<stop stop-color="#FBB042"/>
<stop offset="1" stop-color="#F16422"/>
</linearGradient>
<linearGradient id="paint8_linear_2_81" x1="1250.2" y1="0" x2="1250.2" y2="332.046" gradientUnits="userSpaceOnUse">
<stop stop-color="#FBB042"/>
<stop offset="1" stop-color="#F16422"/>
</linearGradient>
<linearGradient id="paint9_linear_2_81" x1="1250.2" y1="0" x2="1250.2" y2="332.046" gradientUnits="userSpaceOnUse">
<stop stop-color="#FBB042"/>
<stop offset="1" stop-color="#F16422"/>
</linearGradient>
<clipPath id="clip0_2_81">
<clipPath id="sidebar-brand-wordmark-clip">
<rect width="2500" height="350" fill="white"/>
</clipPath>
</defs>

Before

Width:  |  Height:  |  Size: 9.8 KiB

After

Width:  |  Height:  |  Size: 8.3 KiB

+9 -8
View File
@@ -8,12 +8,12 @@
<path d="M96.7715 113.077H43.5539V119.537H96.7715C98.5535 119.537 99.9964 118.092 99.9964 116.307C99.9964 114.522 98.5535 113.077 96.7715 113.077Z" fill="url(#app-loading-logo-gradient-secondary)"/>
<defs>
<linearGradient id="app-loading-logo-gradient" x1="50" y1="0" x2="50" y2="119.537" gradientUnits="userSpaceOnUse">
<stop offset="0" style="stop-color: var(--p-primary-300)"/>
<stop offset="1" style="stop-color: var(--p-primary-500)"/>
<stop offset="0" style="stop-color: var(--primary-300)"/>
<stop offset="1" style="stop-color: var(--primary-500)"/>
</linearGradient>
<linearGradient id="app-loading-logo-gradient-secondary" x1="50" y1="0" x2="50" y2="119.537" gradientUnits="userSpaceOnUse">
<stop offset="0" style="stop-color: var(--p-primary-300)"/>
<stop offset="1" style="stop-color: var(--p-primary-500)"/>
<stop offset="0" style="stop-color: var(--primary-300)"/>
<stop offset="1" style="stop-color: var(--primary-500)"/>
</linearGradient>
</defs>
</svg>
@@ -37,12 +37,12 @@
<path d="M96.7715 113.077H43.5539V119.537H96.7715C98.5535 119.537 99.9964 118.092 99.9964 116.307C99.9964 114.522 98.5535 113.077 96.7715 113.077Z" fill="url(#app-offline-logo-gradient-secondary)"/>
<defs>
<linearGradient id="app-offline-logo-gradient" x1="50" y1="0" x2="50" y2="119.537" gradientUnits="userSpaceOnUse">
<stop offset="0" style="stop-color: var(--p-primary-300)"/>
<stop offset="1" style="stop-color: var(--p-primary-500)"/>
<stop offset="0" style="stop-color: var(--primary-300)"/>
<stop offset="1" style="stop-color: var(--primary-500)"/>
</linearGradient>
<linearGradient id="app-offline-logo-gradient-secondary" x1="50" y1="0" x2="50" y2="119.537" gradientUnits="userSpaceOnUse">
<stop offset="0" style="stop-color: var(--p-primary-300)"/>
<stop offset="1" style="stop-color: var(--p-primary-500)"/>
<stop offset="0" style="stop-color: var(--primary-300)"/>
<stop offset="1" style="stop-color: var(--primary-500)"/>
</linearGradient>
</defs>
</svg>
@@ -54,6 +54,7 @@
} @else {
<p-confirmDialog />
<p-toast></p-toast>
<app-command-palette />
<router-outlet></router-outlet>
}
</ng-container>
+22
View File
@@ -19,6 +19,7 @@ import { LibraryLoadingService } from "./features/library-creator/library-loadin
import { AuthService } from "./shared/service/auth.service";
import { ConfirmationService } from "primeng/api";
import { MessageService } from "primeng/api";
import { CommandPaletteService } from "./features/command-palette/command-palette.service";
interface StompMessage {
body: string;
@@ -54,6 +55,16 @@ describe("AppComponent", () => {
largeLibraryLoading: ReturnType<typeof signal>;
setLargeLibraryLoading: ReturnType<typeof vi.fn>;
};
let commandPaletteService: {
toggle: ReturnType<typeof vi.fn>;
open: ReturnType<typeof vi.fn>;
hide: ReturnType<typeof vi.fn>;
registerOverlayController: ReturnType<typeof vi.fn>;
isOpen: ReturnType<typeof signal>;
query: ReturnType<typeof signal>;
visibleItems: ReturnType<typeof signal>;
groups: ReturnType<typeof signal>;
};
function createTopicStream(topic: string): Subject<StompMessage> {
const stream = new Subject<StompMessage>();
@@ -92,6 +103,16 @@ describe("AppComponent", () => {
largeLibraryLoading: signal(largeLibraryLoading),
setLargeLibraryLoading: vi.fn(),
};
commandPaletteService = {
toggle: vi.fn(),
open: vi.fn(),
hide: vi.fn(),
registerOverlayController: vi.fn(() => vi.fn()),
isOpen: signal(false),
query: signal(''),
visibleItems: signal([]),
groups: signal([]),
};
TestBed.configureTestingModule({
imports: [TranslocoTestingModule.forRoot({ langs: {} })],
@@ -114,6 +135,7 @@ describe("AppComponent", () => {
{ provide: LibraryHealthService, useValue: libraryHealthService },
{ provide: LibraryLoadingService, useValue: libraryLoadingService },
{ provide: AuthService, useValue: authService },
{ provide: CommandPaletteService, useValue: commandPaletteService },
ConfirmationService,
MessageService],
});
+17 -2
View File
@@ -1,4 +1,4 @@
import {Component, effect, inject, OnDestroy, OnInit, signal} from '@angular/core';
import {Component, DestroyRef, effect, inject, OnDestroy, OnInit, signal} from '@angular/core';
import {RxStompService} from './shared/websocket/rx-stomp.service';
import {BookService} from './features/book/service/book.service';
import {NotificationEventService} from './shared/websocket/notification-event.service';
@@ -19,13 +19,15 @@ import {LibraryHealthService} from './features/book/service/library-health.servi
import {LibraryLoadingService} from './features/library-creator/library-loading.service';
import {scan} from 'rxjs/operators';
import {AuthService} from './shared/service/auth.service';
import {CommandPaletteComponent} from './features/command-palette/command-palette.component';
import {CommandPaletteService} from './features/command-palette/command-palette.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrl: './app.component.scss',
standalone: true,
imports: [ConfirmDialog, Toast, RouterOutlet, TranslocoDirective, TranslocoPipe]
imports: [ConfirmDialog, Toast, RouterOutlet, TranslocoDirective, TranslocoPipe, CommandPaletteComponent]
})
export class AppComponent implements OnInit, OnDestroy {
@@ -46,6 +48,8 @@ export class AppComponent implements OnInit, OnDestroy {
private libraryHealthService = inject(LibraryHealthService);
private libraryLoadingService = inject(LibraryLoadingService);
private authService = inject(AuthService);
private commandPaletteService = inject(CommandPaletteService);
private destroyRef = inject(DestroyRef);
private readonly syncAuthInitializationEffect = effect(() => {
const ready = this.authInit.initialized();
this.loading.set(!ready);
@@ -68,8 +72,19 @@ export class AppComponent implements OnInit, OnDestroy {
ngOnInit(): void {
window.addEventListener('online', this.onOnline);
window.addEventListener('offline', this.onOffline);
document.addEventListener('keydown', this.onGlobalKeydown);
this.destroyRef.onDestroy(() => document.removeEventListener('keydown', this.onGlobalKeydown));
}
private onGlobalKeydown = (event: KeyboardEvent): void => {
if (event.repeat) return;
const combo = (event.metaKey || event.ctrlKey) && !event.shiftKey && !event.altKey;
if (!combo) return;
if (event.key !== 'k' && event.key !== 'K') return;
event.preventDefault();
this.commandPaletteService.toggle();
};
private onOnline = () => {
this.offline.set(false);
};
@@ -1,4 +1,5 @@
<ng-container *transloco="let t; prefix: 'authorBrowser'">
<div class="author-browser-page">
@if (loading()) {
<div class="loading-state">
<p-progressSpinner
@@ -271,4 +272,5 @@
</div>
}
}
</div>
</ng-container>
@@ -1,12 +1,24 @@
.author-browser-page {
--browser-gutter-inline: 2.1rem;
display: flex;
flex-direction: column;
height: 100%;
min-height: 0;
padding: 1.1rem 0 0;
position: relative;
}
.loading-state {
display: flex;
flex: 1 1 auto;
align-items: center;
justify-content: center;
height: calc(100dvh - 6.7rem);
min-height: 0;
}
.browse-header {
padding: 0.75rem 1rem 0;
padding: 0.75rem var(--browser-gutter-inline) 0;
}
.browse-title {
@@ -131,15 +143,15 @@
}
.virtual-scroller {
flex: 1 1 auto;
width: 100%;
height: calc(100dvh - 12.5rem);
padding: 1rem;
min-height: 0;
padding: 1rem var(--browser-gutter-inline);
box-sizing: border-box;
overflow-y: auto;
@media (width <= 768px) {
height: calc(100dvh - 13rem);
padding: 0.5rem;
padding-block: 0.5rem;
}
}
@@ -241,8 +253,14 @@
}
@media (width <= 767px) {
.author-browser-page {
--browser-gutter-inline: 0.5rem;
padding: 1.5rem 0 0;
}
.browse-header {
padding: 0.5rem 0.5rem 0;
padding-top: 0.5rem;
}
.browse-controls {
@@ -205,7 +205,6 @@ export class AuthorBrowserComponent implements OnInit {
minItemWidth: this.minCardWidth,
gap: AuthorBrowserComponent.GRID_GAP,
initialOffset: this.initialScrollOffset,
fillItemWidth: true,
estimateItemHeight: itemWidth => Math.round(itemWidth * this.cardAspectRatio()),
});
@@ -1,19 +1,35 @@
.tabpanels-responsive {
height: calc(100dvh - 9.7rem);
flex: 1 1 auto;
min-height: 0;
overflow: auto;
}
@media (width <= 768px) {
.tabpanels-responsive {
height: calc(100dvh - 8.5rem);
}
.author-wrapper {
display: flex;
flex-direction: column;
height: 100%;
min-height: 0;
position: relative;
}
.author-wrapper {
position: relative;
border-radius: 0.75rem;
overflow: hidden;
border: 1px solid var(--p-content-border-color);
.author-wrapper > p-tabs {
display: flex;
flex-direction: column;
height: 100%;
min-height: 0;
}
::ng-deep .author-wrapper .p-tabs {
display: flex;
flex-direction: column;
height: 100%;
min-height: 0;
}
::ng-deep .author-wrapper .p-tabpanel-active {
display: flex;
flex-direction: column;
min-height: 0;
}
.loading-state {
@@ -147,6 +163,10 @@
}
.books-section {
display: flex;
flex: 1 1 auto;
flex-direction: column;
min-height: 0;
padding: 0 0.5rem;
}
@@ -158,8 +178,9 @@
}
.author-books-scroller {
flex: 1 1 auto;
width: 100%;
height: calc(100dvh - 22rem);
min-height: 0;
box-sizing: border-box;
overflow-y: auto;
}
@@ -2,7 +2,7 @@
display: flex;
flex-direction: column;
flex: 1;
min-height: calc(100dvh - 11rem);
min-height: 0;
}
.editor-container {
@@ -47,7 +47,7 @@
<div class="toolbar-actions">
<div class="toolbar-icons">
@if (isFilterActive()) {
<a class="topbar-items topbar-item" role="button" tabindex="0" (click)="clearFilter()" (keydown.enter)="clearFilter()">
<a class="toolbar-item" role="button" tabindex="0" (click)="clearFilter()" (keydown.enter)="clearFilter()">
<i
class="pi pi-filter-slash filter-clear-icon"
[pTooltip]="t('tooltip.clearFilters')"
@@ -58,7 +58,7 @@
@if (currentViewMode() === 'table') {
<div>
<a class="topbar-items topbar-item" role="button" tabindex="0" (click)="columnPopover.toggle($event)" (keydown.enter)="columnPopover.toggle($event)">
<a class="toolbar-item" role="button" tabindex="0" (click)="columnPopover.toggle($event)" (keydown.enter)="columnPopover.toggle($event)">
<i
class="pi pi-eye"
[pTooltip]="t('tooltip.visibleColumns')"
@@ -90,7 +90,7 @@
</p-popover>
</div>
}
<a class="topbar-items topbar-item" role="button" tabindex="0" (click)="toggleTableGrid()" (keydown.enter)="toggleTableGrid()">
<a class="toolbar-item" role="button" tabindex="0" (click)="toggleTableGrid()" (keydown.enter)="toggleTableGrid()">
<i
[class]="viewIcon()"
[pTooltip]="t('tooltip.toggleView')"
@@ -99,7 +99,7 @@
</a>
<div>
<a
class="topbar-items topbar-item"
class="toolbar-item"
role="button"
tabindex="0"
(click)="seriesCollapseOverlay.toggle($event)"
@@ -164,7 +164,7 @@
</div>
<div class="sort-button-wrapper">
<a class="topbar-items topbar-item" role="button" tabindex="0" (click)="sortPopover.toggle($event)" (keydown.enter)="sortPopover.toggle($event)">
<a class="toolbar-item" role="button" tabindex="0" (click)="sortPopover.toggle($event)" (keydown.enter)="sortPopover.toggle($event)">
<i
class="pi pi-sort"
[pTooltip]="t('tooltip.selectSorting')"
@@ -191,7 +191,7 @@
<div class="mobile-search-wrapper">
<button
type="button"
class="topbar-items topbar-item"
class="toolbar-item"
(click)="searchDropdown.toggle($event)"
[pTooltip]="t('tooltip.search')"
tooltipPosition="top"
@@ -243,7 +243,7 @@
}
</div>
<a class="topbar-items topbar-item" role="button" tabindex="0" (click)="toggleSidebar()" (keydown.enter)="toggleSidebar()">
<a class="toolbar-item" role="button" tabindex="0" (click)="toggleSidebar()" (keydown.enter)="toggleSidebar()">
<i
[ngClass]="showFilter() ? 'pi pi-filter-fill' : 'pi pi-filter'"
[pTooltip]="t('tooltip.toggleSidebar')"
@@ -270,62 +270,63 @@
</p>
</div>
} @else {
@let visibleBooks = books();
@if (visibleBooks.length === 0 && !isBooksLoading()) {
<div class="no-books-container">
<p class="no-books-text">
{{ t('labels.noBooks') }}
</p>
</div>
}
@if (currentViewMode() === 'table' && (visibleBooks.length > 0 || showTableLoadingPlaceholder())) {
<app-book-table
[books]="visibleBooks"
[virtualRowCount]="virtualRowCount()"
[loadedBookCount]="loadedBookCount()"
[isFetchingNextPage]="isFetchingNextBooksPage()"
[bookQueryToken]="bookQueryToken()"
(selectAllRequested)="selectAllBooks()"
(loadNextPage)="loadNextBooksPage()"
[visibleColumns]="visibleColumns()"
[useSquareCovers]="isAudiobookOnlyLibrary()"
></app-book-table>
}
@if (currentViewMode() === 'grid') {
<div #scrollElement class="virtual-scroller">
<div class="virtual-content" [style.height.px]="virtualGrid.virtualizer.getTotalSize()">
@for (virtualItem of virtualGrid.virtualizer.getVirtualItems(); track virtualItem.key) {
@if (visibleBooks[virtualItem.index]; as book) {
<div
class="virtual-cell"
[style.width.px]="virtualGrid.itemWidth()"
[style.height.px]="virtualItem.size"
[style.transform]="virtualGrid.itemTransform(virtualItem)">
<app-book-card
[index]="virtualItem.index"
[book]="book"
[isCheckboxEnabled]="true"
[seriesViewEnabled]="seriesViewEnabled()"
[onBookSelect]="onBookCardSelect"
[isSeriesCollapsed]="seriesCollapseFilter.seriesCollapsed()"
(checkboxClick)="onCheckboxClicked($event)"
[isSelected]="bookSelectionService.isBookSelected(book)"
[useSquareCovers]="isAudiobookOnlyLibrary()"
[overlayPreferenceService]="bookCardOverlayPreferenceService">
</app-book-card>
</div>
} @else {
<div
class="virtual-cell virtual-loader-cell"
[style.width.px]="virtualGrid.itemWidth()"
[style.height.px]="virtualItem.size"
[style.transform]="virtualGrid.itemTransform(virtualItem)"></div>
}
}
<div class="book-browser-content">
@let visibleBooks = books();
@if (visibleBooks.length === 0 && !isBooksLoading()) {
<div class="no-books-container">
<p class="no-books-text">
{{ t('labels.noBooks') }}
</p>
</div>
</div>
}
@if (userService.currentUser(); as currentUser) {
}
@if (currentViewMode() === 'table' && (visibleBooks.length > 0 || showTableLoadingPlaceholder())) {
<app-book-table
[books]="visibleBooks"
[virtualRowCount]="virtualRowCount()"
[loadedBookCount]="loadedBookCount()"
[isFetchingNextPage]="isFetchingNextBooksPage()"
[bookQueryToken]="bookQueryToken()"
(selectAllRequested)="selectAllBooks()"
(loadNextPage)="loadNextBooksPage()"
[visibleColumns]="visibleColumns()"
[useSquareCovers]="isAudiobookOnlyLibrary()"
></app-book-table>
}
@if (currentViewMode() === 'grid') {
<div #scrollElement class="virtual-scroller">
<div class="virtual-content" [style.height.px]="virtualGrid.virtualizer.getTotalSize()">
@for (virtualItem of virtualGrid.virtualizer.getVirtualItems(); track virtualItem.key) {
@if (visibleBooks[virtualItem.index]; as book) {
<div
class="virtual-cell"
[style.width.px]="virtualGrid.itemWidth()"
[style.height.px]="virtualItem.size"
[style.transform]="virtualGrid.itemTransform(virtualItem)">
<app-book-card
[index]="virtualItem.index"
[book]="book"
[isCheckboxEnabled]="true"
[seriesViewEnabled]="seriesViewEnabled()"
[onBookSelect]="onBookCardSelect"
[isSeriesCollapsed]="seriesCollapseFilter.seriesCollapsed()"
(checkboxClick)="onCheckboxClicked($event)"
[isSelected]="bookSelectionService.isBookSelected(book)"
[useSquareCovers]="isAudiobookOnlyLibrary()"
[overlayPreferenceService]="bookCardOverlayPreferenceService">
</app-book-card>
</div>
} @else {
<div
class="virtual-cell virtual-loader-cell"
[style.width.px]="virtualGrid.itemWidth()"
[style.height.px]="virtualItem.size"
[style.transform]="virtualGrid.itemTransform(virtualItem)"></div>
}
}
</div>
</div>
}
@if (userService.currentUser(); as currentUser) {
<div class="book-browser-footer" [class.footer-hidden]="selectedCount() === 0">
<div class="footer-content">
<div class="footer-left">
@@ -448,6 +449,7 @@
</div>
</div>
}
</div>
}
</div>
@@ -5,6 +5,8 @@
flex-direction: row;
min-width: 0;
width: 100%;
height: 100%;
min-height: 0;
}
.book-browser-main {
@@ -13,6 +15,16 @@
flex: 1 1 0;
min-width: 0;
width: auto;
min-height: 0;
}
.book-browser-content {
position: relative;
display: flex;
flex: 1 1 auto;
flex-direction: column;
min-width: 0;
min-height: 0;
}
// Header bar
@@ -22,16 +34,13 @@
justify-content: space-between;
gap: 0.25rem;
padding: 0.35rem;
border-radius: 0.75rem 0.75rem 0 0;
margin-bottom: 0.5rem;
margin-right: 2px;
background-color: var(--card-background);
border: 1px solid var(--p-content-border-color);
border-bottom: 1px solid var(--p-content-border-color);
@media (width >= 768px) {
gap: 1rem;
padding: 0.5rem 1rem;
margin-bottom: 1rem;
}
}
@@ -337,15 +346,10 @@
// Virtual scroller and grid
.virtual-scroller {
width: 100%;
height: calc(100dvh - 10.9rem);
padding: 1rem 0;
height: 100%;
padding: 1rem;
box-sizing: border-box;
overflow-y: auto;
@media (width <= 768px) {
height: calc(100dvh - 9rem);
padding: 0.75rem;
}
}
.virtual-loader-cell {
@@ -385,8 +389,8 @@
border-radius: 0.5rem;
}
// Topbar items (icon buttons)
.topbar-item {
// Toolbar actions (icon buttons)
.toolbar-item {
display: inline-flex;
align-items: center;
justify-content: center;
@@ -33,6 +33,8 @@ import {SortService} from '../../service/sort.service';
import {TranslocoService} from '@jsverse/transloco';
import {AppBooksApiService} from '../../service/app-books-api.service';
import {AppBookFilters, AppBookSort} from '../../model/app-book.model';
import {LayoutService} from '../../../../shared/layout/layout.service';
import {type VirtualGridMetrics} from '../../../../shared/util/virtual-grid.util';
function makeBook(id: number, libraryId: number, title: string, addedOn: string): Book {
return {
@@ -261,6 +263,7 @@ function createHarness(options?: {
},
},
{provide: AppSettingsService, useValue: {appSettings: vi.fn(() => null)}},
{provide: LayoutService, useValue: {sidebarTransitioning: signal(false)}},
{
provide: ActivatedRoute,
useValue: {
@@ -470,6 +473,23 @@ describe('BookBrowserComponent', () => {
expect(component.showTableLoadingPlaceholder()).toBe(false);
});
it('sizes grid loading placeholders to fill the viewport', () => {
const {component} = createHarness({books: [], isBooksLoading: true});
const loadingGrid = component as unknown as {
minimumLoadingGridItemCount(metrics: VirtualGridMetrics): number;
};
component.currentViewMode.set(VIEW_MODES.GRID);
expect(loadingGrid.minimumLoadingGridItemCount({
viewportWidth: 960,
viewportHeight: 900,
columns: 6,
itemHeight: 200,
gap: 20,
})).toBe(36);
});
it('calls SeriesCollapseFilter.collapseBooks when computing books', () => {
createHarness();
const filter = TestBed.inject(SeriesCollapseFilter);
@@ -54,8 +54,9 @@ import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
import {SortService} from '../../service/sort.service';
import {AppBooksApiService} from '../../service/app-books-api.service';
import {AppBookFilters} from '../../model/app-book.model';
import {createVirtualGrid, scaleForGridColumns} from '../../../../shared/util/virtual-grid.util';
import {createVirtualGrid, scaleForGridColumns, type VirtualGridMetrics} from '../../../../shared/util/virtual-grid.util';
import {GridDensityButtonsComponent} from '../../../../shared/components/grid-density-buttons/grid-density-buttons.component';
import {LayoutService} from '../../../../shared/layout/layout.service';
export enum EntityType {
LIBRARY = 'Library',
@@ -111,6 +112,7 @@ export class BookBrowserComponent implements AfterViewInit {
private appBooksApi = inject(AppBooksApiService);
private localStorageService = inject(LocalStorageService);
private scrollService = inject(RouteScrollPositionService);
private layoutService = inject(LayoutService);
private readonly t = inject(TranslocoService);
private readonly destroyRef = inject(DestroyRef);
@@ -322,8 +324,10 @@ export class BookBrowserComponent implements AfterViewInit {
gap: this.virtualGridGap,
columns: this.virtualGridColumns,
count: this.virtualRowCount,
minimumCount: metrics => this.minimumLoadingGridItemCount(metrics),
initialOffset: this.initialScrollOffset,
fillItemWidth: true,
deferViewportUpdates: this.layoutService.sidebarTransitioning,
estimateItemHeight: itemWidth => this.isMobile()
? this.mobileCardSizeForWidth(itemWidth).height
: this.cardSizeForWidth(itemWidth).height,
@@ -515,6 +519,18 @@ export class BookBrowserComponent implements AfterViewInit {
return renderedBookCount + 1;
}
private minimumLoadingGridItemCount({viewportHeight, columns, itemHeight, gap}: VirtualGridMetrics): number {
if (!this.showBooksLoadingPlaceholder() || this.currentViewMode() !== VIEW_MODES.GRID) {
return 0;
}
if (viewportHeight <= 0 || itemHeight <= 0) {
return INITIAL_LOADING_ROW_COUNT;
}
const visibleRows = Math.ceil((viewportHeight + gap) / (itemHeight + gap));
return Math.max(INITIAL_LOADING_ROW_COUNT, (visibleRows + 1) * columns);
}
readonly viewIcon = computed(() =>
this.currentViewMode() === VIEW_MODES.TABLE ? 'pi pi-table' : 'pi pi-objects-column'
);
@@ -1,5 +1,14 @@
:host ::ng-deep p-accordion-header {
:host ::ng-deep p-accordion {
--p-accordion-header-padding: 0.6rem 1rem;
--p-accordion-header-background: var(--card-background);
--p-accordion-header-active-background: var(--card-background);
--p-accordion-header-hover-background: var(--surface-hover);
--p-accordion-header-active-hover-background: var(--surface-hover);
--p-accordion-content-background: var(--card-background);
}
:host ::ng-deep .p-accordionpanel {
background: var(--card-background);
}
:host ::ng-deep .p-togglebutton {
@@ -12,7 +21,7 @@
}
.book-filter-container {
height: calc(100dvh - 6.1rem);
height: 100%;
border-radius: 0.75rem;
overflow: hidden;
background: var(--card-background);
@@ -79,7 +88,6 @@
.filter-row {
cursor: pointer;
transition: colors 200ms ease-in-out;
height: 26px;
display: flex;
flex-direction: row;
@@ -87,6 +95,7 @@
justify-content: space-between;
gap: 0.5rem;
max-width: 97%;
transition: color var(--transition-base);
&.active {
color: var(--primary-color);
@@ -1,5 +1,8 @@
:host {
display: block;
display: flex;
flex-direction: column;
flex: 1 1 auto;
width: 100%;
min-height: 0;
--book-table-border-color: var(--p-datatable-border-color, color-mix(in srgb, var(--p-content-border-color) 82%, black));
@@ -28,14 +31,10 @@
.book-table-scroll {
box-sizing: border-box;
height: calc(100dvh - 150px);
border: 1px solid var(--book-table-border-color);
flex: 1 1 auto;
min-height: 0;
overflow: auto;
background: var(--book-table-row-background);
@media (width <= 768px) {
height: calc(100dvh - 125px);
}
}
.book-table {
@@ -1,92 +0,0 @@
<ng-container *transloco="let t; prefix: 'book.searcher'">
<div class="book-searcher-container">
<p-iconfield class="search-iconfield" [class.focused]="isSearchFocused" [class.has-results]="isDropdownOpen">
<p-inputicon class="pi pi-search"/>
<input
type="text"
pInputText
[(ngModel)]="searchQuery"
(input)="onSearchInputChange()"
(focus)="isSearchFocused = true"
(keydown)="onKeydown($event)"
[placeholder]="t('placeholder')"
class="search-input"
/>
@if (searchQuery) {
<p-button
icon="pi pi-times"
(click)="clearSearch()"
[text]="true"
[rounded]="true"
class="clear-search-btn"
[attr.aria-label]="t('clearSearch')">
</p-button>
}
</p-iconfield>
<p-popover #resultsPopover [appendTo]="'body'" [styleClass]="'search-results-popover'">
<div
class="search-dropdown layout-menu show"
>
@if (isLoading) {
@for (i of [1,2,3]; track i) {
<div class="search-skeleton-item">
<p-skeleton width="50px" height="67px" borderRadius="4px"/>
<div class="search-skeleton-details">
<p-skeleton width="80%" height="1rem"/>
<p-skeleton width="60%" height="0.8rem"/>
</div>
</div>
}
} @else if (books.length > 0) {
@for (book of books; track book; let idx = $index) {
<div
class="search-dropdown-item"
[class.active]="activeIndex === idx"
role="button"
tabindex="0"
(click)="onBookClick(book)"
(keydown.enter)="onBookClick(book)">
<div class="search-item-content">
@if (urlHelper.getThumbnailUrl(book.id, book.metadata?.coverUpdatedOn); as coverUrl) {
<img
[attr.src]="coverUrl"
[alt]="t('bookCoverAlt')"
class="search-book-cover"
/>
} @else {
<app-cover-placeholder class="search-book-cover" [title]="book.metadata?.title ?? ''" [author]="(book.metadata?.authors ?? []).join(', ')" size="sm" />
}
<div class="search-book-details">
<div class="search-book-title-container">
<p class="search-book-name">
{{ book.metadata?.title | slice: 0:70 }}
</p>
</div>
<div class="search-book-meta-line">
@if (book.metadata?.authors?.length ?? 0 > 0) {
<p class="search-book-authors">{{ t('byPrefix') }} {{ getAuthorNames(book.metadata?.authors) }}</p>
}
@if (getPublishedYear(book.metadata?.publishedDate)) {
<span class="metadata-badge year-badge">{{ getPublishedYear(book.metadata?.publishedDate) }}</span>
}
</div>
@if (getSeriesInfo(book.metadata?.seriesName, book.metadata?.seriesNumber)) {
<div class="search-book-series metadata-badge series-badge">
<i class="pi pi-book"></i>
<span>{{ getSeriesInfo(book.metadata?.seriesName, book.metadata?.seriesNumber) }}</span>
</div>
}
</div>
</div>
</div>
}
} @else {
<div class="search-dropdown-item no-results">
<span>{{ t('noResults') }}</span>
</div>
}
</div>
</p-popover>
</div>
</ng-container>
@@ -1,241 +0,0 @@
.book-searcher-container {
margin-left: 0.5rem;
position: relative;
width: 100%;
min-width: 0;
@media (width >= 768px) {
margin-left: 1.25rem;
width: var(--app-search-width-desktop);
max-width: 100%;
transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
}
// Popover styles moved to global src/styles.scss due to appendTo="body"
.search-iconfield {
width: 100%;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
border-radius: 8px;
@media (width >= 640px) {
display: flex;
}
&.focused {
background: color-mix(in srgb, var(--primary-color) 5%, transparent);
box-shadow: 0 0 0 2px color-mix(in srgb, var(--primary-color) 20%, transparent);
.search-input {
border-color: var(--primary-color);
}
}
}
.search-input {
width: 100%;
padding-right: 2.5rem;
height: 2.5rem;
line-height: 2.5rem;
font-size: 1rem;
background: var(--surface-800) !important;
border: 1px solid var(--surface-600);
transition: all 0.2s ease;
&:hover {
border-color: var(--surface-500);
background: var(--surface-700) !important;
}
}
.clear-search-btn {
position: absolute;
right: 0.5rem;
top: 50%;
transform: translateY(-50%);
display: none;
@media (width >= 640px) {
display: inline-flex;
}
}
.search-dropdown {
width: 100%;
background: transparent; // Glassmorphism handled by parent .search-results-popover
border: none;
border-radius: 8px;
max-height: min(70vh, calc(100dvh - 4rem));
overflow-y: auto;
// Desktop width constraints moved to src/styles.scss for body-appended elements
}
// .show class no longer needed as popover handles visibility
.search-dropdown-item {
display: flex;
flex-direction: column;
cursor: pointer;
transition: background-color 0.2s ease;
border-bottom: 1px solid color-mix(in srgb, var(--border-color) 50%, transparent);
&:first-child {
border-radius: 8px 8px 0 0;
}
&:last-child {
border-radius: 0 0 8px 8px;
border-bottom: none;
}
&:hover,
&.active {
background-color: var(--surface-hover);
}
&.no-results {
padding: 2rem 1rem;
text-align: center;
color: var(--text-secondary-color);
font-style: italic;
}
}
.search-item-content {
display: flex;
flex-direction: row;
align-items: flex-start;
gap: 1rem;
width: 100%;
padding: 0.75rem 1rem;
}
.search-book-cover {
width: 50px;
height: 67px;
min-width: 50px;
object-fit: cover;
border-radius: 4px;
box-shadow: 0 2px 4px rgb(0 0 0 / 10%);
background-color: var(--ground-background);
aspect-ratio: 2/3;
}
.search-book-details {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.search-book-title-container {
display: flex;
align-items: flex-start;
}
.search-book-name {
font-weight: 600;
font-size: 0.95rem;
line-height: 1.4;
display: -webkit-box;
-webkit-line-clamp: 2;
line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
text-overflow: ellipsis;
overflow-wrap: anywhere;
margin: 0;
}
.search-book-meta-line {
display: flex;
align-items: center;
gap: 0.5rem;
flex-wrap: wrap;
}
.search-book-authors {
font-size: 0.9rem;
font-style: italic;
color: var(--text-secondary-color);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
margin: 0;
flex: 1;
min-width: 0;
}
.search-book-year {
font-size: 0.8rem;
color: var(--text-secondary-color);
background-color: var(--ground-background);
padding: 0.125rem 0.5rem;
border-radius: 4px;
white-space: nowrap;
font-weight: 500;
}
.search-book-series {
display: flex;
align-items: center;
gap: 0.375rem;
font-size: 0.8rem;
color: var(--primary-color);
padding: 0.075rem 0.125rem;
border-radius: 4px;
width: fit-content;
i {
font-size: 0.75rem;
}
span {
font-weight: 500;
}
}
.search-book-metadata {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
align-items: center;
}
.metadata-badge {
display: inline-flex;
align-items: center;
gap: 0.25rem;
font-size: 0.8rem;
padding: 0.1rem 0.25rem;
border-radius: 4px;
background-color: var(--surface-hover);
color: var(--text-secondary-color);
white-space: nowrap;
i {
font-size: 0.7rem;
}
&.series-badge {
background-color: color-mix(in srgb, var(--p-primary-color) 10%, transparent);
color: var(--p-primary-color);
}
}
.search-skeleton-item {
display: flex;
flex-direction: row;
gap: 1rem;
padding: 0.75rem 1rem;
}
.search-skeleton-details {
display: flex;
flex-direction: column;
gap: 0.5rem;
flex: 1;
}
@@ -1,14 +0,0 @@
import {describe, it} from 'vitest';
// NOTE(frontend-seam): Real coverage here needs seams around debounced signal-to-observable
// search state, global document click listeners, and router navigation so search dropdown behavior
// can be tested without a browser-event harness.
describe.skip('BookSearcherComponent', () => {
it('needs debounce seams to verify filtered-book output, loading state, and active-index reset behavior', () => {
// TODO(seam): Cover the debounced search signal and filteredBooks computed state once timing concerns are extracted for direct control.
});
it('needs event seams to verify keyboard navigation, outside-click clearing, and routed book selection', () => {
// TODO(seam): Cover onKeydown and onDocumentClick after isolating host listeners and router side effects behind adapters.
});
});
@@ -1,162 +0,0 @@
import {Component, ElementRef, HostListener, computed, inject, signal, ViewChild} from '@angular/core';
import {toObservable, toSignal} from '@angular/core/rxjs-interop';
import {debounceTime, distinctUntilChanged} from 'rxjs/operators';
import {Book} from '../../model/book.model';
import {FormsModule} from '@angular/forms';
import {InputText} from 'primeng/inputtext';
import {BookService} from '../../service/book.service';
import {Button} from 'primeng/button';
import {SlicePipe} from '@angular/common';
import {Skeleton} from 'primeng/skeleton';
import {UrlHelperService} from '../../../../shared/service/url-helper.service';
import {CoverPlaceholderComponent} from '../../../../shared/components/cover-generator/cover-generator.component';
import {Router} from '@angular/router';
import {IconField} from 'primeng/iconfield';
import {InputIcon} from 'primeng/inputicon';
import {filterBooksBySearchTerm} from '../book-browser/filters/HeaderFilter';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
import {Popover} from 'primeng/popover';
@Component({
selector: 'app-book-searcher',
templateUrl: './book-searcher.component.html',
imports: [
FormsModule,
InputText,
Button,
SlicePipe,
Skeleton,
IconField,
InputIcon,
TranslocoDirective,
CoverPlaceholderComponent,
Popover,
],
styleUrls: ['./book-searcher.component.scss'],
standalone: true
})
export class BookSearcherComponent {
searchQuery = '';
activeIndex = -1;
isSearchFocused = false;
private readonly searchTerm = signal('');
private readonly debouncedSearchTerm = toSignal(
toObservable(this.searchTerm).pipe(
debounceTime(200),
distinctUntilChanged()
),
{initialValue: ''}
);
private readonly filteredBooks = computed(() => {
const term = this.debouncedSearchTerm().trim();
if (term.length < 2) {
return [];
}
return filterBooksBySearchTerm(this.bookService.books(), term).slice(0, 50);
});
private bookService = inject(BookService);
private router = inject(Router);
protected urlHelper = inject(UrlHelperService);
private readonly t = inject(TranslocoService);
private elRef = inject(ElementRef);
@ViewChild('resultsPopover') resultsPopover?: Popover;
get books(): Book[] {
return this.filteredBooks();
}
get isLoading(): boolean {
const rawTerm = this.searchTerm().trim();
return rawTerm.length >= 2 && rawTerm !== this.debouncedSearchTerm().trim();
}
getAuthorNames(authors: string[] | undefined): string {
return authors?.join(', ') || this.t.translate('book.searcher.unknownAuthor');
}
getPublishedYear(publishedDate: string | undefined): string | null {
if (!publishedDate) return null;
const year = publishedDate.split('-')[0];
return year && year.length === 4 ? year : null;
}
getSeriesInfo(seriesName: string | undefined, seriesNumber: number | null | undefined): string | null {
if (!seriesName) return null;
if (seriesNumber) {
return `${seriesName} #${seriesNumber}`;
}
return seriesName;
}
onSearchInputChange(): void {
this.searchTerm.set(this.searchQuery.trim());
this.activeIndex = -1;
if (this.isDropdownOpen) {
setTimeout(() => this.showPopover());
} else {
this.resultsPopover?.hide();
}
}
private showPopover(): void {
if (this.resultsPopover) {
const inputElement = this.elRef.nativeElement.querySelector('.search-input');
this.resultsPopover.show(null, inputElement);
}
}
onBookClick(book: Book): void {
this.clearSearch();
this.router.navigate(['/book', book.id], {
queryParams: {tab: 'view'}
});
}
clearSearch(): void {
this.searchQuery = '';
this.searchTerm.set('');
this.activeIndex = -1;
this.resultsPopover?.hide();
}
get isDropdownOpen(): boolean {
return this.books.length > 0 || this.isLoading;
}
@HostListener('document:click', ['$event'])
onDocumentClick(event: Event): void {
if (!this.elRef.nativeElement.contains(event.target)) {
this.clearSearch();
this.isSearchFocused = false;
}
}
onKeydown(event: KeyboardEvent): void {
if (!this.isDropdownOpen) return;
switch (event.key) {
case 'ArrowDown':
this.activeIndex = Math.min(this.activeIndex + 1, this.books.length - 1);
event.preventDefault();
break;
case 'ArrowUp':
this.activeIndex = Math.max(this.activeIndex - 1, 0);
event.preventDefault();
break;
case 'Enter':
if (this.activeIndex >= 0 && this.activeIndex < this.books.length) {
this.onBookClick(this.books[this.activeIndex]);
}
break;
case 'Escape':
this.clearSearch();
(event.target as HTMLElement).blur();
break;
}
}
}
@@ -1,19 +1,22 @@
.tabpanels-responsive {
height: calc(100dvh - 9.7rem);
flex: 1 1 auto;
min-height: 0;
overflow: auto;
}
@media (width <= 768px) {
.tabpanels-responsive {
height: calc(100dvh - 8.5rem);
}
.series-wrapper {
display: flex;
flex-direction: column;
height: 100%;
min-height: 0;
position: relative;
}
.series-wrapper {
position: relative;
border-radius: 0.75rem;
overflow: hidden;
border: 1px solid var(--p-content-border-color);
.series-wrapper > p-tabs {
display: flex;
flex-direction: column;
height: 100%;
min-height: 0;
}
.series-main {
@@ -1,5 +1,7 @@
import {SortOption} from './sort.model';
export type ShelfSystemKey = 'kobo';
export interface Shelf {
id?: number;
name: string;
@@ -9,4 +11,5 @@ export interface Shelf {
publicShelf?: boolean;
userId?: number;
bookCount?: number;
systemKey?: ShelfSystemKey | null;
}
@@ -136,6 +136,15 @@ export class AppBooksApiService {
}
}
searchBooks(query: string, size = 20): Observable<AppPageResponse<AppBookSummary>> {
const params = new HttpParams()
.set('q', query.trim())
.set('page', '0')
.set('size', Math.max(1, size).toString());
return this.http.get<AppPageResponse<AppBookSummary>>(`${this.booksUrl}/search`, {params});
}
fetchNextPage(): void {
this.booksQuery.fetchNextPage();
}
@@ -1,14 +1,243 @@
import {describe, it} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {Router} from '@angular/router';
import {of} from 'rxjs';
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import type {MenuItem, MenuItemCommandEvent} from 'primeng/api';
import {ConfirmationService, MessageService} from 'primeng/api';
import {TranslocoService} from '@jsverse/transloco';
// NOTE(frontend-seam): Real coverage here needs a seam around nested Prime confirmation payloads,
// router/navigation side effects, clipboard writes, and multiple dialog/task services so menu-item
// command wiring can be asserted without turning the spec into a brittle integration harness.
describe.skip('LibraryShelfMenuService', () => {
it('needs a menu-command seam to verify library, shelf, and magic-shelf action wiring deterministically', () => {
// TODO(seam): Cover confirmation payloads, delete/refresh commands, and dialog launches after introducing a thin menu-action adapter.
import {LibraryShelfMenuService} from './library-shelf-menu.service';
import {LibraryService} from './library.service';
import {ShelfService} from './shelf.service';
import {TaskHelperService} from '../../settings/task-management/task-helper.service';
import {UserService} from '../../settings/user-management/user.service';
import {LoadingService} from '../../../core/services/loading.service';
import {DialogLauncherService} from '../../../shared/services/dialog-launcher.service';
import {BookDialogHelperService} from '../components/book-browser/book-dialog-helper.service';
import {MagicShelfService} from '../../magic-shelf/service/magic-shelf.service';
import {MetadataRefreshType} from '../../metadata/model/request/metadata-refresh-type.enum';
import type {Library} from '../model/library.model';
import type {Shelf} from '../model/shelf.model';
import type {MagicShelf} from '../../magic-shelf/service/magic-shelf.service';
function buildLibrary(overrides: Partial<Library> = {}): Library {
return {
id: 7,
name: 'Main Library',
watch: true,
paths: [],
...overrides,
};
}
function buildShelf(overrides: Partial<Shelf> = {}): Shelf {
return {
id: 11,
name: 'Favorites',
userId: 3,
publicShelf: false,
...overrides,
};
}
function buildMagicShelf(overrides: Partial<MagicShelf> = {}): MagicShelf {
return {
id: 13,
name: 'Magic Shelf',
filterJson: '{}',
isPublic: false,
...overrides,
};
}
function findMenuItem(items: MenuItem[], label: string): MenuItem {
const item = items
.flatMap(candidate => candidate.items ?? [candidate])
.find(candidate => candidate.label === label);
expect(item).toBeDefined();
return item!;
}
function runCommand(item: MenuItem): void {
item.command?.({ item } as MenuItemCommandEvent);
}
describe('LibraryShelfMenuService', () => {
let service: LibraryShelfMenuService;
const confirmationService = {
confirm: vi.fn(),
};
const messageService = {
add: vi.fn(),
};
const libraryService = {
refreshLibrary: vi.fn(() => of(undefined)),
deleteLibrary: vi.fn(() => of(undefined)),
};
const shelfService = {
deleteShelf: vi.fn(() => of(undefined)),
};
const taskHelperService = {
refreshMetadataTask: vi.fn(() => of(undefined)),
};
const userService = {
getCurrentUser: vi.fn(() => ({id: 3, permissions: {admin: false}})),
};
const router = {
navigate: vi.fn(),
};
const dialogLauncherService = {
openLibraryEditDialog: vi.fn(),
openLibraryMetadataFetchDialog: vi.fn(),
openShelfEditDialog: vi.fn(),
openMagicShelfEditDialog: vi.fn(),
};
const magicShelfService = {
deleteShelf: vi.fn(() => of(undefined)),
};
const loadingService = {
show: vi.fn(() => 'loader-token'),
hide: vi.fn(),
};
const bookDialogHelperService = {
openAddPhysicalBookDialog: vi.fn(),
openBulkIsbnImportDialog: vi.fn(),
openDuplicateMergerDialog: vi.fn(),
};
const translocoService = {
translate: vi.fn((key: string) => key),
};
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
LibraryShelfMenuService,
{provide: ConfirmationService, useValue: confirmationService},
{provide: MessageService, useValue: messageService},
{provide: LibraryService, useValue: libraryService},
{provide: ShelfService, useValue: shelfService},
{provide: TaskHelperService, useValue: taskHelperService},
{provide: UserService, useValue: userService},
{provide: Router, useValue: router},
{provide: DialogLauncherService, useValue: dialogLauncherService},
{provide: MagicShelfService, useValue: magicShelfService},
{provide: LoadingService, useValue: loadingService},
{provide: BookDialogHelperService, useValue: bookDialogHelperService},
{provide: TranslocoService, useValue: translocoService},
],
});
service = TestBed.inject(LibraryShelfMenuService);
});
it('needs a browser-side seam to verify clipboard and navigation behavior without relying on global runtime objects', () => {
// TODO(seam): Cover magic-shelf export and post-delete navigation once clipboard/router effects are injectable.
afterEach(() => {
TestBed.resetTestingModule();
vi.restoreAllMocks();
confirmationService.confirm.mockClear();
messageService.add.mockClear();
libraryService.refreshLibrary.mockClear();
libraryService.deleteLibrary.mockClear();
shelfService.deleteShelf.mockClear();
taskHelperService.refreshMetadataTask.mockClear();
userService.getCurrentUser.mockClear();
router.navigate.mockClear();
dialogLauncherService.openLibraryEditDialog.mockClear();
dialogLauncherService.openLibraryMetadataFetchDialog.mockClear();
dialogLauncherService.openShelfEditDialog.mockClear();
dialogLauncherService.openMagicShelfEditDialog.mockClear();
magicShelfService.deleteShelf.mockClear();
loadingService.show.mockClear();
loadingService.hide.mockClear();
bookDialogHelperService.openAddPhysicalBookDialog.mockClear();
bookDialogHelperService.openBulkIsbnImportDialog.mockClear();
bookDialogHelperService.openDuplicateMergerDialog.mockClear();
translocoService.translate.mockClear();
});
it('disables and guards library actions when the library id is missing', () => {
const items = service.initializeLibraryMenuItems(buildLibrary({id: undefined}));
const actionLabels = [
'book.shelfMenuService.library.addPhysicalBook',
'book.shelfMenuService.library.bulkIsbnImport',
'book.shelfMenuService.library.editLibrary',
'book.shelfMenuService.library.rescanLibrary',
'book.shelfMenuService.library.customFetchMetadata',
'book.shelfMenuService.library.autoFetchMetadata',
'book.shelfMenuService.library.findDuplicates',
'book.shelfMenuService.library.deleteLibrary',
];
for (const label of actionLabels) {
const item = findMenuItem(items, label);
expect(item.disabled).toBe(true);
runCommand(item);
}
expect(bookDialogHelperService.openAddPhysicalBookDialog).not.toHaveBeenCalled();
expect(bookDialogHelperService.openBulkIsbnImportDialog).not.toHaveBeenCalled();
expect(bookDialogHelperService.openDuplicateMergerDialog).not.toHaveBeenCalled();
expect(dialogLauncherService.openLibraryEditDialog).not.toHaveBeenCalled();
expect(dialogLauncherService.openLibraryMetadataFetchDialog).not.toHaveBeenCalled();
expect(taskHelperService.refreshMetadataTask).not.toHaveBeenCalled();
expect(confirmationService.confirm).not.toHaveBeenCalled();
});
it('passes the concrete library id into library actions when available', () => {
const items = service.initializeLibraryMenuItems(buildLibrary({id: 42}));
runCommand(findMenuItem(items, 'book.shelfMenuService.library.addPhysicalBook'));
runCommand(findMenuItem(items, 'book.shelfMenuService.library.bulkIsbnImport'));
runCommand(findMenuItem(items, 'book.shelfMenuService.library.editLibrary'));
runCommand(findMenuItem(items, 'book.shelfMenuService.library.customFetchMetadata'));
runCommand(findMenuItem(items, 'book.shelfMenuService.library.autoFetchMetadata'));
runCommand(findMenuItem(items, 'book.shelfMenuService.library.findDuplicates'));
runCommand(findMenuItem(items, 'book.shelfMenuService.library.rescanLibrary'));
runCommand(findMenuItem(items, 'book.shelfMenuService.library.deleteLibrary'));
expect(bookDialogHelperService.openAddPhysicalBookDialog).toHaveBeenCalledWith(42);
expect(bookDialogHelperService.openBulkIsbnImportDialog).toHaveBeenCalledWith(42);
expect(dialogLauncherService.openLibraryEditDialog).toHaveBeenCalledWith(42);
expect(dialogLauncherService.openLibraryMetadataFetchDialog).toHaveBeenCalledWith(42);
expect(taskHelperService.refreshMetadataTask).toHaveBeenCalledWith({
refreshType: MetadataRefreshType.LIBRARY,
libraryId: 42,
});
expect(bookDialogHelperService.openDuplicateMergerDialog).toHaveBeenCalledWith(42);
expect(confirmationService.confirm).toHaveBeenCalledTimes(2);
});
it('guards shelf actions when the shelf id is missing even for the owner', () => {
userService.getCurrentUser.mockReturnValue({id: 3, permissions: {admin: false}});
const items = service.initializeShelfMenuItems(buildShelf({id: undefined, userId: 3}));
const editItem = findMenuItem(items, 'book.shelfMenuService.shelf.editShelf');
const deleteItem = findMenuItem(items, 'book.shelfMenuService.shelf.deleteShelf');
expect(editItem.disabled).toBe(true);
expect(deleteItem.disabled).toBe(true);
runCommand(editItem);
runCommand(deleteItem);
expect(dialogLauncherService.openShelfEditDialog).not.toHaveBeenCalled();
expect(confirmationService.confirm).not.toHaveBeenCalled();
});
it('guards magic shelf actions when the shelf id is missing', () => {
const items = service.initializeMagicShelfMenuItems(buildMagicShelf({id: null}));
const editItem = findMenuItem(items, 'book.shelfMenuService.magicShelf.editMagicShelf');
const deleteItem = findMenuItem(items, 'book.shelfMenuService.magicShelf.deleteMagicShelf');
expect(editItem.disabled).toBe(true);
expect(deleteItem.disabled).toBe(true);
runCommand(editItem);
runCommand(deleteItem);
expect(dialogLauncherService.openMagicShelfEditDialog).not.toHaveBeenCalled();
expect(confirmationService.confirm).not.toHaveBeenCalled();
});
});
@@ -35,295 +35,331 @@ export class LibraryShelfMenuService {
private readonly t = inject(TranslocoService);
initializeLibraryMenuItems(entity: Library | null): MenuItem[] {
const libraryId = entity?.id;
const disableLibraryActions = libraryId == null;
return [
{
label: this.t.translate('book.shelfMenuService.library.optionsLabel'),
items: [
{
label: this.t.translate('book.shelfMenuService.library.addPhysicalBook'),
icon: 'pi pi-book',
command: () => {
this.bookDialogHelperService.openAddPhysicalBookDialog(entity?.id as number);
}
},
{
label: this.t.translate('book.shelfMenuService.library.bulkIsbnImport'),
icon: 'pi pi-barcode',
command: () => {
this.bookDialogHelperService.openBulkIsbnImportDialog(entity?.id as number);
}
},
{
separator: true
},
{
label: this.t.translate('book.shelfMenuService.library.editLibrary'),
icon: 'pi pi-pen-to-square',
command: () => {
this.dialogLauncherService.openLibraryEditDialog((entity?.id as number));
}
},
{
label: this.t.translate('book.shelfMenuService.library.rescanLibrary'),
icon: 'pi pi-refresh',
command: () => {
this.confirmationService.confirm({
message: this.t.translate('book.shelfMenuService.confirm.rescanLibraryMessage', {name: entity?.name}),
header: this.t.translate('book.shelfMenuService.confirm.header'),
icon: undefined,
acceptLabel: this.t.translate('book.shelfMenuService.confirm.rescanLabel'),
rejectLabel: this.t.translate('common.cancel'),
acceptIcon: undefined,
rejectIcon: undefined,
acceptButtonStyleClass: undefined,
rejectButtonStyleClass: undefined,
rejectButtonProps: {
label: this.t.translate('common.cancel'),
severity: 'secondary',
},
acceptButtonProps: {
label: this.t.translate('book.shelfMenuService.confirm.rescanLabel'),
severity: 'success',
},
accept: () => {
const libraryId = entity?.id;
if (libraryId == null) {
return;
}
label: this.t.translate('book.shelfMenuService.library.addPhysicalBook'),
icon: 'pi pi-book',
disabled: disableLibraryActions,
command: () => {
if (libraryId == null) {
return;
}
this.libraryService.refreshLibrary(libraryId).subscribe({
complete: () => {
this.messageService.add({severity: 'info', summary: this.t.translate('common.success'), detail: this.t.translate('book.shelfMenuService.toast.libraryRefreshSuccessDetail')});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: this.t.translate('book.shelfMenuService.toast.failedSummary'),
detail: this.t.translate('book.shelfMenuService.toast.libraryRefreshFailedDetail'),
});
}
this.bookDialogHelperService.openAddPhysicalBookDialog(libraryId);
}
},
{
label: this.t.translate('book.shelfMenuService.library.bulkIsbnImport'),
icon: 'pi pi-barcode',
disabled: disableLibraryActions,
command: () => {
if (libraryId == null) {
return;
}
this.bookDialogHelperService.openBulkIsbnImportDialog(libraryId);
}
},
{
separator: true
},
{
label: this.t.translate('book.shelfMenuService.library.editLibrary'),
icon: 'pi pi-pen-to-square',
disabled: disableLibraryActions,
command: () => {
if (libraryId == null) {
return;
}
this.dialogLauncherService.openLibraryEditDialog(libraryId);
}
},
{
label: this.t.translate('book.shelfMenuService.library.rescanLibrary'),
icon: 'pi pi-refresh',
disabled: disableLibraryActions,
command: () => {
if (libraryId == null) {
return;
}
this.confirmationService.confirm({
message: this.t.translate('book.shelfMenuService.confirm.rescanLibraryMessage', {name: entity?.name}),
header: this.t.translate('book.shelfMenuService.confirm.header'),
icon: undefined,
acceptLabel: this.t.translate('book.shelfMenuService.confirm.rescanLabel'),
rejectLabel: this.t.translate('common.cancel'),
acceptIcon: undefined,
rejectIcon: undefined,
acceptButtonStyleClass: undefined,
rejectButtonStyleClass: undefined,
rejectButtonProps: {
label: this.t.translate('common.cancel'),
severity: 'secondary',
},
acceptButtonProps: {
label: this.t.translate('book.shelfMenuService.confirm.rescanLabel'),
severity: 'success',
},
accept: () => {
this.libraryService.refreshLibrary(libraryId).subscribe({
complete: () => {
this.messageService.add({severity: 'info', summary: this.t.translate('common.success'), detail: this.t.translate('book.shelfMenuService.toast.libraryRefreshSuccessDetail')});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: this.t.translate('book.shelfMenuService.toast.failedSummary'),
detail: this.t.translate('book.shelfMenuService.toast.libraryRefreshFailedDetail'),
});
}
});
}
},
{
label: this.t.translate('book.shelfMenuService.library.customFetchMetadata'),
icon: 'pi pi-sync',
command: () => {
this.dialogLauncherService.openLibraryMetadataFetchDialog((entity?.id as number));
}
},
{
label: this.t.translate('book.shelfMenuService.library.autoFetchMetadata'),
icon: 'pi pi-bolt',
command: () => {
this.taskHelperService.refreshMetadataTask({
refreshType: MetadataRefreshType.LIBRARY,
libraryId: entity?.id ?? undefined
}).subscribe();
}
},
{
label: this.t.translate('book.shelfMenuService.library.findDuplicates'),
icon: 'pi pi-copy',
command: () => {
this.bookDialogHelperService.openDuplicateMergerDialog(entity?.id as number);
}
},
{
separator: true
},
{
label: this.t.translate('book.shelfMenuService.library.deleteLibrary'),
icon: 'pi pi-trash',
command: () => {
this.confirmationService.confirm({
message: this.t.translate('book.shelfMenuService.confirm.deleteLibraryMessage', {name: entity?.name}),
header: this.t.translate('book.shelfMenuService.confirm.header'),
acceptLabel: this.t.translate('common.yes'),
rejectLabel: this.t.translate('common.cancel'),
rejectButtonProps: {
label: this.t.translate('common.cancel'),
severity: 'secondary',
},
acceptButtonProps: {
label: this.t.translate('common.yes'),
severity: 'danger',
},
accept: () => {
const loader = this.loadingService.show(this.t.translate('book.shelfMenuService.loading.deletingLibrary', {name: entity?.name}));
const libraryId = entity?.id;
if (libraryId == null) {
this.loadingService.hide(loader);
return;
}
this.libraryService.deleteLibrary(libraryId)
.pipe(finalize(() => this.loadingService.hide(loader)))
.subscribe({
complete: () => {
this.router.navigate(['/']);
this.messageService.add({severity: 'info', summary: this.t.translate('common.success'), detail: this.t.translate('book.shelfMenuService.toast.libraryDeletedDetail')});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: this.t.translate('book.shelfMenuService.toast.failedSummary'),
detail: this.t.translate('book.shelfMenuService.toast.libraryDeleteFailedDetail'),
});
}
});
}
});
}
});
}
},
{
label: this.t.translate('book.shelfMenuService.library.customFetchMetadata'),
icon: 'pi pi-sync',
disabled: disableLibraryActions,
command: () => {
if (libraryId == null) {
return;
}
]
this.dialogLauncherService.openLibraryMetadataFetchDialog(libraryId);
}
},
{
label: this.t.translate('book.shelfMenuService.library.autoFetchMetadata'),
icon: 'pi pi-bolt',
disabled: disableLibraryActions,
command: () => {
if (libraryId == null) {
return;
}
this.taskHelperService.refreshMetadataTask({
refreshType: MetadataRefreshType.LIBRARY,
libraryId
}).subscribe();
}
},
{
label: this.t.translate('book.shelfMenuService.library.findDuplicates'),
icon: 'pi pi-copy',
disabled: disableLibraryActions,
command: () => {
if (libraryId == null) {
return;
}
this.bookDialogHelperService.openDuplicateMergerDialog(libraryId);
}
},
{
separator: true
},
{
label: this.t.translate('book.shelfMenuService.library.deleteLibrary'),
icon: 'pi pi-trash',
disabled: disableLibraryActions,
command: () => {
if (libraryId == null) {
return;
}
this.confirmationService.confirm({
message: this.t.translate('book.shelfMenuService.confirm.deleteLibraryMessage', {name: entity?.name}),
header: this.t.translate('book.shelfMenuService.confirm.header'),
acceptLabel: this.t.translate('common.yes'),
rejectLabel: this.t.translate('common.cancel'),
rejectButtonProps: {
label: this.t.translate('common.cancel'),
severity: 'secondary',
},
acceptButtonProps: {
label: this.t.translate('common.yes'),
severity: 'danger',
},
accept: () => {
const loader = this.loadingService.show(this.t.translate('book.shelfMenuService.loading.deletingLibrary', {name: entity?.name}));
this.libraryService.deleteLibrary(libraryId)
.pipe(finalize(() => this.loadingService.hide(loader)))
.subscribe({
complete: () => {
this.router.navigate(['/']);
this.messageService.add({severity: 'info', summary: this.t.translate('common.success'), detail: this.t.translate('book.shelfMenuService.toast.libraryDeletedDetail')});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: this.t.translate('book.shelfMenuService.toast.failedSummary'),
detail: this.t.translate('book.shelfMenuService.toast.libraryDeleteFailedDetail'),
});
}
});
}
});
}
}
];
}
initializeShelfMenuItems(entity: Shelf | null): MenuItem[] {
const user = this.userService.getCurrentUser();
const shelfId = entity?.id;
const isOwner = entity?.userId === user?.id;
const isPublicShelf = entity?.publicShelf ?? false;
const disableOptions = !isOwner;
const disableOptions = !isOwner || shelfId == null;
return [
const items: MenuItem[] = [
{
label: (isPublicShelf ? this.t.translate('book.shelfMenuService.shelf.publicShelfPrefix') : '') + (disableOptions ? this.t.translate('book.shelfMenuService.shelf.readOnly') : this.t.translate('book.shelfMenuService.shelf.optionsLabel')),
items: [
{
label: this.t.translate('book.shelfMenuService.shelf.editShelf'),
icon: 'pi pi-pen-to-square',
disabled: disableOptions,
command: () => {
this.dialogLauncherService.openShelfEditDialog((entity?.id as number));
}
},
{
separator: true
},
{
label: this.t.translate('book.shelfMenuService.shelf.deleteShelf'),
icon: 'pi pi-trash',
disabled: disableOptions,
command: () => {
this.confirmationService.confirm({
message: this.t.translate('book.shelfMenuService.confirm.deleteShelfMessage', {name: entity?.name}),
header: this.t.translate('book.shelfMenuService.confirm.header'),
acceptLabel: this.t.translate('common.yes'),
rejectLabel: this.t.translate('common.cancel'),
acceptButtonProps: {
label: this.t.translate('common.yes'),
severity: 'danger'
},
rejectButtonProps: {
label: this.t.translate('common.cancel'),
severity: 'secondary'
},
accept: () => {
const shelfId = entity?.id;
if (shelfId == null) {
return;
}
label: this.t.translate('book.shelfMenuService.shelf.editShelf'),
icon: 'pi pi-pen-to-square',
disabled: disableOptions,
command: () => {
if (shelfId == null) {
return;
}
this.shelfService.deleteShelf(shelfId).subscribe({
complete: () => {
this.router.navigate(['/']);
this.messageService.add({severity: 'info', summary: this.t.translate('common.success'), detail: this.t.translate('book.shelfMenuService.toast.shelfDeletedDetail')});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: this.t.translate('book.shelfMenuService.toast.failedSummary'),
detail: this.t.translate('book.shelfMenuService.toast.shelfDeleteFailedDetail'),
});
}
this.dialogLauncherService.openShelfEditDialog(shelfId);
}
},
{
separator: true
},
{
label: this.t.translate('book.shelfMenuService.shelf.deleteShelf'),
icon: 'pi pi-trash',
disabled: disableOptions,
command: () => {
if (shelfId == null) {
return;
}
this.confirmationService.confirm({
message: this.t.translate('book.shelfMenuService.confirm.deleteShelfMessage', {name: entity?.name}),
header: this.t.translate('book.shelfMenuService.confirm.header'),
acceptLabel: this.t.translate('common.yes'),
rejectLabel: this.t.translate('common.cancel'),
acceptButtonProps: {
label: this.t.translate('common.yes'),
severity: 'danger'
},
rejectButtonProps: {
label: this.t.translate('common.cancel'),
severity: 'secondary'
},
accept: () => {
this.shelfService.deleteShelf(shelfId).subscribe({
complete: () => {
this.router.navigate(['/']);
this.messageService.add({severity: 'info', summary: this.t.translate('common.success'), detail: this.t.translate('book.shelfMenuService.toast.shelfDeletedDetail')});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: this.t.translate('book.shelfMenuService.toast.failedSummary'),
detail: this.t.translate('book.shelfMenuService.toast.shelfDeleteFailedDetail'),
});
}
});
}
}
]
});
}
}
];
/* Keep the grouped label only when it conveys state (public/read-only). */
if (isPublicShelf || disableOptions) {
const prefix = isPublicShelf ? this.t.translate('book.shelfMenuService.shelf.publicShelfPrefix') : '';
const suffix = disableOptions
? this.t.translate('book.shelfMenuService.shelf.readOnly')
: this.t.translate('book.shelfMenuService.shelf.optionsLabel');
return [{ label: prefix + suffix, items }];
}
return items;
}
initializeMagicShelfMenuItems(entity: MagicShelf | null): MenuItem[] {
const isAdmin = this.userService.getCurrentUser()?.permissions.admin ?? false;
const magicShelfId = entity?.id;
const isPublicShelf = entity?.isPublic ?? false;
const disableOptions = isPublicShelf && !isAdmin;
const disableOptions = magicShelfId == null || (isPublicShelf && !isAdmin);
return [
{
label: this.t.translate('book.shelfMenuService.magicShelf.optionsLabel'),
items: [
{
label: this.t.translate('book.shelfMenuService.magicShelf.editMagicShelf'),
icon: 'pi pi-pen-to-square',
disabled: disableOptions,
command: () => {
this.dialogLauncherService.openMagicShelfEditDialog((entity?.id as number));
}
},
{
label: this.t.translate('book.shelfMenuService.magicShelf.exportJson'),
icon: 'pi pi-copy',
command: () => {
if (entity?.filterJson) {
navigator.clipboard.writeText(entity.filterJson).then(() => {
this.messageService.add({severity: 'success', summary: this.t.translate('common.success'), detail: this.t.translate('book.shelfMenuService.toast.magicShelfJsonCopiedDetail')});
});
}
}
},
{
separator: true
},
{
label: this.t.translate('book.shelfMenuService.magicShelf.deleteMagicShelf'),
icon: 'pi pi-trash',
disabled: disableOptions,
command: () => {
this.confirmationService.confirm({
message: this.t.translate('book.shelfMenuService.confirm.deleteMagicShelfMessage', {name: entity?.name}),
header: this.t.translate('book.shelfMenuService.confirm.header'),
acceptLabel: this.t.translate('common.yes'),
rejectLabel: this.t.translate('common.cancel'),
acceptButtonProps: {
label: this.t.translate('common.yes'),
severity: 'danger'
},
rejectButtonProps: {
label: this.t.translate('common.cancel'),
severity: 'secondary'
},
accept: () => {
const shelfId = entity?.id;
if (shelfId == null) {
return;
}
label: this.t.translate('book.shelfMenuService.magicShelf.editMagicShelf'),
icon: 'pi pi-pen-to-square',
disabled: disableOptions,
command: () => {
if (magicShelfId == null) {
return;
}
this.magicShelfService.deleteShelf(shelfId).subscribe({
complete: () => {
this.router.navigate(['/']);
this.messageService.add({severity: 'info', summary: this.t.translate('common.success'), detail: this.t.translate('book.shelfMenuService.toast.magicShelfDeletedDetail')});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: this.t.translate('book.shelfMenuService.toast.failedSummary'),
detail: this.t.translate('book.shelfMenuService.toast.magicShelfDeleteFailedDetail'),
});
}
this.dialogLauncherService.openMagicShelfEditDialog(magicShelfId);
}
},
{
label: this.t.translate('book.shelfMenuService.magicShelf.exportJson'),
icon: 'pi pi-copy',
command: () => {
if (entity?.filterJson) {
navigator.clipboard.writeText(entity.filterJson).then(() => {
this.messageService.add({severity: 'success', summary: this.t.translate('common.success'), detail: this.t.translate('book.shelfMenuService.toast.magicShelfJsonCopiedDetail')});
});
}
}
},
{
separator: true
},
{
label: this.t.translate('book.shelfMenuService.magicShelf.deleteMagicShelf'),
icon: 'pi pi-trash',
disabled: disableOptions,
command: () => {
if (magicShelfId == null) {
return;
}
this.confirmationService.confirm({
message: this.t.translate('book.shelfMenuService.confirm.deleteMagicShelfMessage', {name: entity?.name}),
header: this.t.translate('book.shelfMenuService.confirm.header'),
acceptLabel: this.t.translate('common.yes'),
rejectLabel: this.t.translate('common.cancel'),
acceptButtonProps: {
label: this.t.translate('common.yes'),
severity: 'danger'
},
rejectButtonProps: {
label: this.t.translate('common.cancel'),
severity: 'secondary'
},
accept: () => {
this.magicShelfService.deleteShelf(magicShelfId).subscribe({
complete: () => {
this.router.navigate(['/']);
this.messageService.add({severity: 'info', summary: this.t.translate('common.success'), detail: this.t.translate('book.shelfMenuService.toast.magicShelfDeletedDetail')});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: this.t.translate('book.shelfMenuService.toast.failedSummary'),
detail: this.t.translate('book.shelfMenuService.toast.magicShelfDeleteFailedDetail'),
});
}
});
}
}
]
});
}
}
];
}
@@ -130,6 +130,16 @@ export class LibraryService {
return this.bookService.books().filter(book => book.libraryId === libraryId).length;
}
readonly bookCountByLibraryId = computed(() => {
const counts = new Map<number, number>();
for (const book of this.bookService.books()) {
if (book.libraryId != null) {
counts.set(book.libraryId, (counts.get(book.libraryId) ?? 0) + 1);
}
}
return counts;
});
setLargeLibraryLoading(isLoading: boolean, expectedCount: number): void {
this.largeLibraryLoading.set({ isLoading, expectedCount });
}
@@ -1,8 +1,9 @@
import {HttpTestingController} from '@angular/common/http/testing';
import {signal} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {createAuthServiceStub, createQueryClientHarness, flushSignalAndQueryEffects} from '../../../core/testing/query-testing';
import {createAuthServiceStub, createQueryClientHarness, flushQueryAsync, flushSignalAndQueryEffects} from '../../../core/testing/query-testing';
import type {Book} from '../model/book.model';
import type {Shelf} from '../model/shelf.model';
import {AuthService} from '../../../shared/service/auth.service';
@@ -41,6 +42,7 @@ describe('ShelfService', () => {
let userService: {
getCurrentUser: ReturnType<typeof vi.fn>;
};
let currentUser: ReturnType<typeof signal<{id: number} | null>>;
beforeEach(() => {
authService = createAuthServiceStub();
@@ -49,8 +51,9 @@ describe('ShelfService', () => {
books: vi.fn(() => []),
removeBooksFromShelf: vi.fn(),
};
currentUser = signal<{id: number} | null>(null);
userService = {
getCurrentUser: vi.fn(() => null),
getCurrentUser: vi.fn(() => currentUser()),
};
vi.spyOn(queryClientHarness.queryClient, 'invalidateQueries').mockResolvedValue(undefined);
@@ -79,8 +82,7 @@ describe('ShelfService', () => {
});
async function flushShelvesQueryResult(): Promise<void> {
await Promise.resolve();
flushSignalAndQueryEffects();
await flushQueryAsync();
}
it('eagerly fetches shelves and hydrates the computed shelves signal', async () => {
@@ -94,10 +96,26 @@ describe('ShelfService', () => {
request.flush(response);
await flushShelvesQueryResult();
expect(service.shelves()).toEqual(response);
expect(service.shelves()).toEqual([
expect.objectContaining({id: 1, name: 'Reading', systemKey: null}),
expect.objectContaining({id: 2, name: 'Archive', systemKey: null}),
]);
expect(service.shelvesError()).toBeNull();
});
it('marks the Kobo system shelf when the backend returns the known Kobo shelf shape', async () => {
httpTestingController.expectOne(req => req.url.endsWith('/api/v1/shelves')).flush([
buildShelf({id: 1, name: 'Kobo', icon: 'pi pi-tablet'}),
buildShelf({id: 2, name: 'Archive', icon: 'pi pi-folder'}),
]);
await flushShelvesQueryResult();
expect(service.shelves()).toEqual([
expect.objectContaining({id: 1, name: 'Kobo', systemKey: 'kobo'}),
expect.objectContaining({id: 2, name: 'Archive', systemKey: null}),
]);
});
it('removes shelf queries when the auth token is cleared', () => {
const removeQueriesSpy = vi.spyOn(queryClientHarness.queryClient, 'removeQueries').mockImplementation(() => undefined);
@@ -149,14 +167,36 @@ describe('ShelfService', () => {
buildBook(3, {shelves: [buildShelf({id: 2, name: 'Archive'})]}),
]);
userService.getCurrentUser.mockReturnValue({id: 7});
currentUser.set({id: 7});
expect(service.getBookCountValue(1)).toBe(2);
userService.getCurrentUser.mockReturnValue({id: 42});
currentUser.set({id: 42});
expect(service.getBookCountValue(2)).toBe(6);
expect(service.getBookCountValue(999)).toBe(0);
});
it('builds shelf count maps with local counts for the owner and persisted counts for shared shelves', async () => {
httpTestingController.expectOne(req => req.url.endsWith('/api/v1/shelves')).flush([
buildShelf({id: 1, userId: 7, bookCount: 99}),
buildShelf({id: 2, userId: 10, bookCount: 6}),
]);
await flushShelvesQueryResult();
bookService.books.mockReturnValue([
buildBook(1, {shelves: [buildShelf({id: 1, name: 'Reading'})]}),
buildBook(2, {shelves: [buildShelf({id: 1, name: 'Reading'})]}),
buildBook(3, {shelves: [buildShelf({id: 2, name: 'Archive'})]}),
]);
currentUser.set({id: 7});
flushSignalAndQueryEffects();
const counts = service.bookCountByShelfId();
expect(counts.get(1)).toBe(2);
expect(counts.get(2)).toBe(6);
});
it('counts unshelved books from the current book cache snapshot', () => {
httpTestingController.expectOne(req => req.url.endsWith('/api/v1/shelves')).flush([]);
@@ -12,6 +12,8 @@ import {UserService} from '../../settings/user-management/user.service';
import {AuthService} from '../../../shared/service/auth.service';
const SHELVES_QUERY_KEY = ['shelves'] as const;
const KOBO_SHELF_NAME = 'Kobo';
const KOBO_SHELF_ICON = 'pi pi-tablet';
@Injectable({providedIn: 'root'})
export class ShelfService {
@@ -53,7 +55,7 @@ export class ShelfService {
private getShelvesQueryOptions() {
return queryOptions({
queryKey: SHELVES_QUERY_KEY,
queryFn: () => lastValueFrom(this.http.get<Shelf[]>(this.url))
queryFn: async () => this.decorateShelves(await lastValueFrom(this.http.get<Shelf[]>(this.url)))
});
}
@@ -110,4 +112,40 @@ export class ShelfService {
return this.bookService.books().filter(book => !book.shelves || book.shelves.length === 0).length;
}
readonly bookCountByShelfId = computed(() => {
const currentUserId = this.userService.getCurrentUser()?.id;
const counts = new Map<number, number>();
for (const book of this.bookService.books()) {
for (const shelf of book.shelves ?? []) {
if (shelf.id != null) {
counts.set(shelf.id, (counts.get(shelf.id) ?? 0) + 1);
}
}
}
for (const shelf of this.shelves()) {
if (shelf.userId !== currentUserId && shelf.id != null) {
counts.set(shelf.id, shelf.bookCount ?? 0);
}
}
return counts;
});
readonly unshelvedBookCount = computed(() =>
this.bookService.books().filter(book => !book.shelves || book.shelves.length === 0).length
);
private decorateShelves(shelves: Shelf[]): Shelf[] {
return shelves.map((shelf) => ({
...shelf,
systemKey: this.getSystemKey(shelf),
}));
}
private getSystemKey(shelf: Shelf): Shelf['systemKey'] {
return shelf.name === KOBO_SHELF_NAME && shelf.icon === KOBO_SHELF_ICON ? 'kobo' : null;
}
}
@@ -1,17 +1,9 @@
.main-card {
display: flex;
flex-direction: column;
height: calc(100dvh - 6.1rem);
border-radius: 0.75rem;
height: 100%;
overflow: hidden;
background: var(--card-background);
border: 1px solid var(--p-content-border-color);
@media (width <= 768px) {
height: calc(100dvh - 4.4rem);
border-radius: 0;
border-width: 1px 0 0;
}
background: var(--page-background);
}
.header {
@@ -22,7 +14,7 @@
justify-content: space-between;
border-bottom: 1px solid var(--p-content-border-color);
gap: 1rem;
@media (width <= 768px) {
padding: 1rem;
}
@@ -41,7 +33,7 @@
p {
font-size: 0.875rem;
color: rgb(156 163 175);
strong {
color: var(--primary-color);
}
@@ -82,7 +74,6 @@
align-items: center;
justify-content: center;
z-index: 50;
border-radius: 0.75rem;
}
.loading-content {
@@ -119,7 +110,6 @@
align-items: center;
justify-content: center;
z-index: 50;
border-radius: 0.75rem;
> * + * {
margin-top: 0.75rem;
@@ -217,7 +207,7 @@ p-inputgroup.disabled {
display: flex;
gap: 1rem;
align-items: center;
@media (width <= 640px) {
flex-wrap: wrap;
width: 100%;
@@ -0,0 +1,112 @@
<ng-template #paletteTpl>
<ng-container *transloco="let t; prefix: 'layout.commandPalette'">
<div class="command-palette-shell" cdkTrapFocus [cdkTrapFocusAutoCapture]="true" [attr.aria-label]="t('ariaLabel')">
<div class="command-palette" [style.max-height.px]="availableHeightPx()">
<!-- iOS needs both type="search" and a form with an action attribute. -->
<form ngNoForm action="." class="command-palette-form" (submit)="$event.preventDefault()">
<div class="command-palette-input-row">
<i class="pi pi-search" aria-hidden="true"></i>
<input
#paletteInput
type="search"
name="q"
class="command-palette-input"
autocomplete="off"
spellcheck="false"
autocapitalize="none"
enterkeyhint="search"
[placeholder]="t('placeholder')"
[attr.aria-label]="t('ariaLabel')"
[ngModel]="svc.query()"
(ngModelChange)="onQueryChange($event)"
(keydown)="onKeydown($event)"
/>
</div>
</form>
@let groups = svc.groups();
@let hasQuery = svc.query().trim().length > 0;
@let isSearching = svc.isSearching();
@if (hasQuery) {
<div class="command-palette-results" role="listbox">
@if (!isSearching && groups.length === 0) {
<div class="command-palette-empty">{{ t('empty') }}</div>
}
@for (group of groups; track group.kind) {
<div class="command-palette-group" role="group" [attr.aria-label]="t(groupLabelKey(group.kind))">
<div class="command-palette-group-label" aria-hidden="true">{{ t(groupLabelKey(group.kind)) }}</div>
@for (item of group.items; track item.id) {
<button
type="button"
class="command-palette-item"
[class.active]="activeItem()?.id === item.id"
[class.book-item]="item.kind === 'book' && !!item.bookMeta"
[id]="itemDomId(item)"
role="option"
[attr.aria-selected]="activeItem()?.id === item.id"
(mouseenter)="onItemHover(item)"
(click)="svc.select(item)"
>
@if (item.kind === 'book' && item.bookMeta; as bookMeta) {
<ng-container *transloco="let tb; prefix: 'book.searcher'">
<div class="command-palette-book-cover">
@if (bookMeta.thumbnailUrl) {
<img [src]="bookMeta.thumbnailUrl" alt="" />
} @else {
<app-cover-placeholder
[title]="item.title"
[author]="bookMeta.authors.join(', ')"
size="sm"
></app-cover-placeholder>
}
</div>
<div class="command-palette-book-details">
<div class="command-palette-book-title">{{ item.title }}</div>
<div class="command-palette-book-meta">
@if (bookMeta.authors.length) {
<span>{{ tb('byPrefix') }} {{ bookMeta.authors.join(', ') }}</span>
}
@if (bookMeta.seriesName) {
<span>{{ bookMeta.seriesName }}@if (bookMeta.seriesNumber) { #{{ bookMeta.seriesNumber }} }</span>
}
@if (bookMeta.year) {
<span>{{ bookMeta.year }}</span>
}
</div>
</div>
</ng-container>
} @else {
@if (item.icon) {
<app-icon-display
class="command-palette-item-icon"
[icon]="item.icon"
size="18px"
[displayEmpty]="true"
></app-icon-display>
}
<span class="command-palette-item-title">{{ item.title }}</span>
@if (item.subtitle) {
<span class="command-palette-item-subtitle">{{ item.subtitle }}</span>
}
}
</button>
}
</div>
}
</div>
<div class="command-palette-hint" aria-hidden="true">
<span class="command-palette-hint-item">
<kbd>↑↓</kbd> {{ t('hintNavigate') }}
</span>
<span class="command-palette-hint-item">
<kbd>↵</kbd> {{ t('hintSelect') }}
</span>
</div>
}
</div>
</div>
</ng-container>
</ng-template>
@@ -0,0 +1,244 @@
:host {
display: contents;
}
.command-palette-shell {
position: relative;
width: min(640px, calc(100vw - 2rem));
}
.command-palette {
display: flex;
flex-direction: column;
width: 100%;
max-height: min(70vh, calc(100dvh - 4rem));
background: var(--surface-overlay);
color: var(--text-color);
border: 1px solid var(--border-color);
border-radius: var(--radius-md);
box-shadow: var(--shadow-overlay);
overflow: hidden;
}
.command-palette-form {
&:has(+ .command-palette-results) .command-palette-input-row {
border-bottom: 1px solid var(--border-color);
}
}
.command-palette-input-row {
display: flex;
align-items: center;
gap: var(--space-3);
padding: var(--space-4) var(--space-5);
i {
color: var(--text-secondary-color);
font-size: var(--text-lg);
}
}
.command-palette-input {
flex: 1;
min-width: 0;
padding: 0;
background: transparent;
border: none;
outline: none;
color: inherit;
font-size: var(--text-lg);
line-height: 1.4;
appearance: none;
&::placeholder {
color: var(--text-secondary-color);
}
&::-webkit-search-cancel-button,
&::-webkit-search-decoration {
appearance: none;
display: none;
}
}
.command-palette-results {
flex: 1;
overflow-y: auto;
padding: var(--space-1) var(--space-3);
}
.command-palette-empty {
padding: var(--space-6) var(--space-4);
color: var(--text-secondary-color);
text-align: center;
font-size: var(--text-sm);
}
.command-palette-group {
padding: var(--space-2) 0;
& + .command-palette-group {
border-top: 1px solid var(--border-color);
}
}
.command-palette-group-label {
padding: var(--space-2) var(--space-2) var(--space-1);
font-size: var(--text-xs);
font-weight: 500;
color: var(--text-secondary-color);
}
.command-palette-item {
display: flex;
align-items: center;
gap: var(--space-2);
width: 100%;
padding: var(--space-2);
background: transparent;
border: none;
border-radius: var(--radius-md);
color: inherit;
text-align: left;
font: inherit;
cursor: pointer;
scroll-margin: var(--space-2) 0;
.command-palette-item-icon {
color: var(--text-secondary-color);
flex-shrink: 0;
}
&.active {
background: color-mix(in srgb, var(--primary-color) 8%, transparent);
color: var(--primary-color);
.command-palette-item-icon {
color: inherit;
}
}
&.book-item {
align-items: center;
gap: var(--space-3);
padding: var(--space-2);
}
}
.command-palette-book-cover {
flex-shrink: 0;
width: 32px;
height: 48px;
border-radius: var(--radius-sm);
overflow: hidden;
background: var(--surface-800);
box-shadow: var(--shadow-sm);
img {
width: 100%;
height: 100%;
object-fit: cover;
display: block;
}
}
.command-palette-book-details {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: var(--space-1);
}
.command-palette-book-title {
font-size: var(--text-base);
font-weight: 600;
line-height: 1.3;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.command-palette-book-meta {
display: flex;
flex-wrap: wrap;
align-items: center;
min-width: 0;
font-size: var(--text-sm);
color: var(--text-secondary-color);
> * + *::before {
content: '·';
margin: 0 var(--space-2);
}
}
.command-palette-item-title {
flex: 0 1 auto;
min-width: 0;
font-size: var(--text-base);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.command-palette-item-subtitle {
flex: 1 1 auto;
min-width: 0;
margin-left: var(--space-2);
color: var(--text-secondary-color);
font-size: var(--text-sm);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
text-align: right;
}
.command-palette-hint {
display: flex;
justify-content: flex-end;
gap: var(--space-3);
padding: var(--space-2) var(--space-4);
border-top: 1px solid var(--border-color);
color: var(--text-secondary-color);
font-size: var(--text-xs);
}
.command-palette-hint-item {
display: inline-flex;
align-items: center;
gap: var(--space-2);
}
.command-palette-hint kbd {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 1.25rem;
padding: 0 var(--space-1);
border-radius: var(--radius-sm);
background: var(--surface-hover);
font-family: inherit;
font-size: var(--text-xs);
line-height: 1.5;
color: var(--text-color);
}
@media (width <= 991px) {
.command-palette-shell {
width: 100vw;
}
.command-palette {
max-height: calc(100dvh - 3.5rem);
border-top: none;
border-left: none;
border-right: none;
border-radius: 0;
box-shadow: 0 12px 24px rgb(0 0 0 / 18%);
}
.command-palette-hint {
display: none;
}
}
@@ -0,0 +1,227 @@
import { computed, signal } from '@angular/core';
import { OverlayContainer } from '@angular/cdk/overlay';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { NavigationStart, Router } from '@angular/router';
import { Subject } from 'rxjs';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { getTranslocoModule } from '../../core/testing/transloco-testing';
import type { PaletteGroup, PaletteItem } from './command-palette.model';
import { CommandPaletteComponent } from './command-palette.component';
import { CommandPaletteService } from './command-palette.service';
function createItem(id: string, title: string): PaletteItem {
return {
id,
kind: 'page',
title,
searchText: title.toLowerCase(),
};
}
class MockCommandPaletteService {
private readonly _isOpen = signal(false);
private overlayController?: { open(): void; close(): void; focusInput(): void };
readonly isOpen = this._isOpen.asReadonly();
readonly query = signal('');
readonly isSearching = signal(false);
readonly items = signal<PaletteItem[]>([]);
readonly groups = computed<PaletteGroup[]>(() =>
this.query().trim()
? [{ kind: 'page', items: this.items() }]
: []
);
readonly visibleItems = computed<PaletteItem[]>(() =>
this.groups().flatMap((group) => group.items)
);
readonly select = vi.fn();
readonly hide = vi.fn(() => {
this.overlayController?.close();
this._isOpen.set(false);
this.query.set('');
});
registerOverlayController(controller: { open(): void; close(): void; focusInput(): void }): () => void {
this.overlayController = controller;
return () => {
if (this.overlayController === controller) {
this.overlayController = undefined;
}
};
}
open(): void {
this.overlayController?.open();
this._isOpen.set(true);
}
}
describe('CommandPaletteComponent', () => {
let fixture: ComponentFixture<CommandPaletteComponent>;
let overlayContainer: OverlayContainer;
let overlayRoot: HTMLElement;
let service: MockCommandPaletteService;
let routerEvents: Subject<unknown>;
let originalScrollIntoView: PropertyDescriptor | undefined;
let originalMatchMedia: PropertyDescriptor | undefined;
beforeEach(() => {
originalScrollIntoView = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'scrollIntoView');
originalMatchMedia = Object.getOwnPropertyDescriptor(window, 'matchMedia');
Object.defineProperty(HTMLElement.prototype, 'scrollIntoView', {
configurable: true,
writable: true,
value: vi.fn(),
});
Object.defineProperty(window, 'matchMedia', {
configurable: true,
writable: true,
value: vi.fn().mockImplementation((query: string) => ({
matches: false,
media: query,
onchange: null,
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
addListener: vi.fn(),
removeListener: vi.fn(),
dispatchEvent: vi.fn(),
})),
});
routerEvents = new Subject<unknown>();
TestBed.configureTestingModule({
imports: [CommandPaletteComponent, getTranslocoModule()],
providers: [
{ provide: CommandPaletteService, useClass: MockCommandPaletteService },
{ provide: Router, useValue: { events: routerEvents.asObservable() } },
],
});
fixture = TestBed.createComponent(CommandPaletteComponent);
overlayContainer = TestBed.inject(OverlayContainer);
overlayRoot = overlayContainer.getContainerElement();
service = TestBed.inject(CommandPaletteService) as unknown as MockCommandPaletteService;
fixture.detectChanges();
});
afterEach(() => {
fixture?.destroy();
overlayRoot?.replaceChildren();
document.querySelectorAll('.cdk-overlay-container').forEach((el) => el.remove());
if (originalScrollIntoView) {
Object.defineProperty(HTMLElement.prototype, 'scrollIntoView', originalScrollIntoView);
} else {
delete (HTMLElement.prototype as { scrollIntoView?: unknown }).scrollIntoView;
}
if (originalMatchMedia) {
Object.defineProperty(window, 'matchMedia', originalMatchMedia);
} else {
delete (window as { matchMedia?: unknown }).matchMedia;
}
TestBed.resetTestingModule();
vi.restoreAllMocks();
});
it('opens the overlay when the service opens and focuses the search input', async () => {
service.query.set('dash');
service.items.set([createItem('page:dashboard', 'Dashboard')]);
service.open();
await flushPalette(fixture);
const input = overlayRoot.querySelector('.command-palette-input') as HTMLInputElement | null;
expect(input).not.toBeNull();
expect(document.activeElement).toBe(input);
});
it('closes the overlay on Escape', async () => {
service.query.set('dash');
service.items.set([createItem('page:dashboard', 'Dashboard')]);
service.open();
await flushPalette(fixture);
const input = overlayRoot.querySelector('.command-palette-input') as HTMLInputElement;
input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
await flushPalette(fixture);
expect(service.hide).toHaveBeenCalled();
expect(overlayRoot.querySelector('.command-palette-input')).toBeNull();
});
it('wraps keyboard navigation through the result list', async () => {
service.query.set('a');
service.items.set([
createItem('page:dashboard', 'Dashboard'),
createItem('page:authors', 'Authors'),
]);
service.open();
await flushPalette(fixture);
const input = overlayRoot.querySelector('.command-palette-input') as HTMLInputElement;
input.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowUp', bubbles: true }));
await flushPalette(fixture);
const items = Array.from(overlayRoot.querySelectorAll('.command-palette-item'));
expect(items[1].classList.contains('active')).toBe(true);
});
it('selects the highlighted item on Enter', async () => {
const items = [
createItem('page:dashboard', 'Dashboard'),
createItem('page:authors', 'Authors'),
];
service.query.set('a');
service.items.set(items);
service.open();
await flushPalette(fixture);
const input = overlayRoot.querySelector('.command-palette-input') as HTMLInputElement;
input.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowDown', bubbles: true }));
await flushPalette(fixture);
input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }));
expect(service.select).toHaveBeenCalledWith(items[1]);
});
it('disposes the overlay when the component is destroyed while open', async () => {
service.query.set('dash');
service.items.set([createItem('page:dashboard', 'Dashboard')]);
service.open();
await flushPalette(fixture);
expect(overlayRoot.querySelector('.command-palette-input')).not.toBeNull();
fixture.destroy();
expect(overlayRoot.querySelector('.command-palette-input')).toBeNull();
fixture = null as unknown as ComponentFixture<CommandPaletteComponent>;
});
it('closes through the service when navigation starts', async () => {
service.query.set('dash');
service.items.set([createItem('page:dashboard', 'Dashboard')]);
service.open();
await flushPalette(fixture);
routerEvents.next(new NavigationStart(1, '/dashboard'));
await flushPalette(fixture);
expect(service.hide).toHaveBeenCalled();
expect(service.isOpen()).toBe(false);
expect(service.query()).toBe('');
expect(overlayRoot.querySelector('.command-palette-input')).toBeNull();
});
});
async function flushPalette(fixture: ComponentFixture<CommandPaletteComponent>): Promise<void> {
fixture.detectChanges();
TestBed.flushEffects();
await Promise.resolve();
await Promise.resolve();
fixture.detectChanges();
}
@@ -0,0 +1,296 @@
import { A11yModule } from '@angular/cdk/a11y';
import { Overlay, OverlayModule, OverlayRef } from '@angular/cdk/overlay';
import { TemplatePortal } from '@angular/cdk/portal';
import { Component, computed, DestroyRef, effect, ElementRef, inject, signal, TemplateRef, untracked, ViewContainerRef, viewChild } from '@angular/core';
import { NavigationStart, Router } from '@angular/router';
import { filter, take } from 'rxjs/operators';
import { FormsModule } from '@angular/forms';
import { TranslocoDirective } from '@jsverse/transloco';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { CoverPlaceholderComponent } from '../../shared/components/cover-generator/cover-generator.component';
import { IconDisplayComponent } from '../../shared/components/icon-display/icon-display.component';
import { PaletteItem } from './command-palette.model';
import { CommandPaletteService } from './command-palette.service';
const MOBILE_MEDIA_QUERY = '(max-width: 991px)';
const MOBILE_TOPBAR_HEIGHT = '3.5rem';
@Component({
selector: 'app-command-palette',
standalone: true,
imports: [A11yModule, OverlayModule, FormsModule, TranslocoDirective, IconDisplayComponent, CoverPlaceholderComponent],
templateUrl: './command-palette.component.html',
styleUrl: './command-palette.component.scss',
})
export class CommandPaletteComponent {
protected readonly svc = inject(CommandPaletteService);
private readonly overlay = inject(Overlay);
private readonly router = inject(Router);
private readonly destroyRef = inject(DestroyRef);
private readonly vcRef = inject(ViewContainerRef);
protected readonly paletteTpl = viewChild.required<TemplateRef<unknown>>('paletteTpl');
protected readonly inputEl = viewChild<ElementRef<HTMLInputElement>>('paletteInput');
protected readonly activeIndex = signal(0);
protected readonly availableHeightPx = signal<number | null>(null);
protected readonly activeItem = computed<PaletteItem | null>(() => {
const items = this.svc.visibleItems();
if (items.length === 0) return null;
const idx = Math.min(this.activeIndex(), items.length - 1);
return items[Math.max(0, idx)];
});
private overlayRef: OverlayRef | undefined;
private focusAnimationFrameId: number | undefined;
private focusTimeoutId: number | undefined;
private mobileMedia: MediaQueryList | undefined;
private readonly mobileMediaListener = () => {
this.applyPositionStrategy();
this.refreshAvailableHeight();
};
private readonly visualViewportListener = () => this.refreshAvailableHeight();
constructor() {
const unregisterOverlayController = this.svc.registerOverlayController({
open: () => this.openOverlay(),
close: () => this.closeOverlay(),
focusInput: () => this.focusInputNow(),
});
this.destroyRef.onDestroy(() => {
unregisterOverlayController();
this.clearPendingFocus();
this.closeOverlay();
});
this.router.events
.pipe(
filter((event): event is NavigationStart => event instanceof NavigationStart),
takeUntilDestroyed(this.destroyRef),
)
.subscribe(() => this.svc.hide());
effect(() => {
this.svc.visibleItems();
untracked(() => this.activeIndex.set(0));
});
effect(() => {
const item = this.activeItem();
if (!item) return;
queueMicrotask(() => {
const el = document.getElementById(this.itemDomId(item));
el?.scrollIntoView({ block: 'nearest' });
});
});
}
protected itemDomId(item: PaletteItem): string {
return `cp-${item.id.replace(/[^a-zA-Z0-9_-]/g, '_')}`;
}
protected onQueryChange(value: string): void {
this.svc.query.set(value);
}
protected onKeydown(event: KeyboardEvent): void {
const items = this.svc.visibleItems();
switch (event.key) {
case 'ArrowDown':
if (items.length > 0) {
event.preventDefault();
this.activeIndex.update((i) => (i + 1) % items.length);
}
break;
case 'ArrowUp':
if (items.length > 0) {
event.preventDefault();
this.activeIndex.update((i) => (i - 1 + items.length) % items.length);
}
break;
case 'Home':
if (items.length > 0) {
event.preventDefault();
this.activeIndex.set(0);
}
break;
case 'End':
if (items.length > 0) {
event.preventDefault();
this.activeIndex.set(items.length - 1);
}
break;
case 'Enter': {
if (this.isMobileViewport()) {
event.preventDefault();
(event.target as HTMLElement | null)?.blur?.();
break;
}
const active = this.activeItem();
if (active) {
event.preventDefault();
this.svc.select(active);
}
break;
}
case 'Escape':
event.preventDefault();
this.svc.hide();
break;
}
}
protected onItemHover(item: PaletteItem): void {
const items = this.svc.visibleItems();
const idx = items.findIndex((candidate) => candidate.id === item.id);
if (idx >= 0) {
this.activeIndex.set(idx);
}
}
protected groupLabelKey(kind: string): string {
return `groups.${kind}`;
}
private openOverlay(): void {
if (this.overlayRef) {
this.focusInputNow();
this.scheduleInputFocus();
return;
}
this.bindMobileMediaListener();
this.bindVisualViewportListener();
this.refreshAvailableHeight();
this.overlayRef = this.overlay.create({
positionStrategy: this.buildPositionStrategy(),
scrollStrategy: this.overlay.scrollStrategies.block(),
hasBackdrop: true,
backdropClass: 'command-palette-backdrop',
panelClass: 'command-palette-panel',
});
this.overlayRef.attach(new TemplatePortal(this.paletteTpl(), this.vcRef));
this.overlayRef.backdropClick().pipe(take(1)).subscribe(() => this.svc.hide());
this.focusInputNow();
this.scheduleInputFocus();
}
private closeOverlay(): void {
this.clearPendingFocus();
this.unbindMobileMediaListener();
this.unbindVisualViewportListener();
this.availableHeightPx.set(null);
this.overlayRef?.dispose();
this.overlayRef = undefined;
}
private buildPositionStrategy() {
const position = this.overlay.position().global();
if (this.isMobileViewport()) {
return position.left('0').top(MOBILE_TOPBAR_HEIGHT);
}
return position.centerHorizontally().top('15vh');
}
private applyPositionStrategy(): void {
if (!this.overlayRef) return;
this.overlayRef.updatePositionStrategy(this.buildPositionStrategy());
}
private isMobileViewport(): boolean {
return this.mobileMedia?.matches ?? false;
}
private bindMobileMediaListener(): void {
if (typeof window === 'undefined' || this.mobileMedia) return;
this.mobileMedia = window.matchMedia(MOBILE_MEDIA_QUERY);
this.mobileMedia.addEventListener('change', this.mobileMediaListener);
}
private unbindMobileMediaListener(): void {
this.mobileMedia?.removeEventListener('change', this.mobileMediaListener);
this.mobileMedia = undefined;
}
private bindVisualViewportListener(): void {
const vv = typeof window !== 'undefined' ? window.visualViewport : null;
if (!vv) return;
vv.addEventListener('resize', this.visualViewportListener);
vv.addEventListener('scroll', this.visualViewportListener);
}
private unbindVisualViewportListener(): void {
const vv = typeof window !== 'undefined' ? window.visualViewport : null;
if (!vv) return;
vv.removeEventListener('resize', this.visualViewportListener);
vv.removeEventListener('scroll', this.visualViewportListener);
}
private refreshAvailableHeight(): void {
// dvh doesn't shrink when the iOS virtual keyboard opens; visualViewport does.
if (!this.isMobileViewport()) {
this.availableHeightPx.set(null);
return;
}
const vv = typeof window !== 'undefined' ? window.visualViewport : null;
if (!vv) {
this.availableHeightPx.set(null);
return;
}
const topbarPx = this.readTopbarHeightPx();
this.availableHeightPx.set(Math.max(0, Math.round(vv.height - topbarPx)));
}
private readTopbarHeightPx(): number {
const fontSize = typeof window !== 'undefined'
? parseFloat(window.getComputedStyle(document.documentElement).fontSize)
: 16;
return (isNaN(fontSize) ? 16 : fontSize) * 3.5;
}
private scheduleInputFocus(): void {
this.clearPendingFocus();
if (typeof window === 'undefined') return;
// iOS Safari only raises the virtual keyboard when focus() lands after layout.
const focusInput = () => this.focusInputNow();
this.focusAnimationFrameId = window.requestAnimationFrame(focusInput);
this.focusTimeoutId = window.setTimeout(focusInput, 60);
}
private focusInputNow(): void {
const input = this.resolveInputElement();
if (!input) return;
try {
input.focus({ preventScroll: true });
} catch {
input.focus();
}
const cursorPosition = input.value.length;
input.setSelectionRange(cursorPosition, cursorPosition);
}
private resolveInputElement(): HTMLInputElement | null {
const viewInput = this.inputEl()?.nativeElement;
if (viewInput) return viewInput;
const overlayInput = this.overlayRef?.overlayElement.querySelector('.command-palette-input');
return overlayInput instanceof HTMLInputElement ? overlayInput : null;
}
private clearPendingFocus(): void {
if (typeof window !== 'undefined' && this.focusAnimationFrameId !== undefined) {
window.cancelAnimationFrame(this.focusAnimationFrameId);
}
if (typeof window !== 'undefined' && this.focusTimeoutId !== undefined) {
window.clearTimeout(this.focusTimeoutId);
}
this.focusAnimationFrameId = undefined;
this.focusTimeoutId = undefined;
}
}
@@ -0,0 +1,37 @@
import { IconSelection } from '../../shared/service/icon-picker.service';
export type PaletteItemKind =
| 'action'
| 'page'
| 'book'
| 'author'
| 'series'
| 'shelf'
| 'magicShelf'
| 'library';
export interface PaletteBookMeta {
thumbnailUrl: string | null;
authors: string[];
seriesName: string | null;
seriesNumber: number | null;
year: string | null;
}
export interface PaletteItem {
id: string;
kind: PaletteItemKind;
title: string;
subtitle?: string;
icon?: IconSelection;
searchText: string;
route?: unknown[];
queryParams?: Record<string, string>;
command?: () => void;
bookMeta?: PaletteBookMeta;
}
export interface PaletteGroup {
kind: PaletteItemKind;
items: PaletteItem[];
}
@@ -0,0 +1,118 @@
import { signal } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { Router } from '@angular/router';
import { of } from 'rxjs';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { getTranslocoModule } from '../../core/testing/transloco-testing';
import { BookDialogHelperService } from '../book/components/book-browser/book-dialog-helper.service';
import { Book } from '../book/model/book.model';
import { BookService } from '../book/service/book.service';
import { LibraryService } from '../book/service/library.service';
import { ShelfService } from '../book/service/shelf.service';
import { MagicShelfService } from '../magic-shelf/service/magic-shelf.service';
import { UrlHelperService } from '../../shared/service/url-helper.service';
import { UserService } from '../settings/user-management/user.service';
import { IconService } from '../../shared/services/icon.service';
import { DialogLauncherService } from '../../shared/services/dialog-launcher.service';
import { CommandPaletteService } from './command-palette.service';
function makeBook(id: number, title: string, authors: string[] = []): Book {
return {
id,
libraryId: 1,
libraryName: 'Library',
metadata: {
bookId: id,
title,
authors,
},
} as Book;
}
describe('CommandPaletteService', () => {
let service: CommandPaletteService;
let books = signal<Book[]>([]);
beforeEach(() => {
vi.useFakeTimers();
});
beforeEach(() => {
books = signal([
makeBook(1, 'The Hobbit', ['J.R.R. Tolkien']),
makeBook(2, 'The Fellowship of the Ring', ['J.R.R. Tolkien']),
makeBook(3, 'Dune', ['Frank Herbert']),
]);
TestBed.configureTestingModule({
imports: [getTranslocoModule()],
providers: [
{ provide: Router, useValue: { navigate: vi.fn(() => Promise.resolve(true)) } },
{ provide: BookService, useValue: { books: books.asReadonly() } },
{ provide: ShelfService, useValue: { shelves: signal([]) } },
{ provide: MagicShelfService, useValue: { shelves: signal([]) } },
{ provide: LibraryService, useValue: { libraries: signal([]) } },
{ provide: UserService, useValue: { currentUser: signal({ permissions: {} }) } },
{ provide: UrlHelperService, useValue: { getThumbnailUrl: vi.fn(() => null) } },
{ provide: IconService, useValue: { getSvgIconContent: vi.fn(() => of('')) } },
{
provide: DialogLauncherService,
useValue: {
openLibraryCreateDialog: vi.fn(),
openMagicShelfCreateDialog: vi.fn(),
openFileUploadDialog: vi.fn(),
},
},
{
provide: BookDialogHelperService,
useValue: {
openShelfCreatorDialog: vi.fn(),
},
},
],
});
service = TestBed.inject(CommandPaletteService);
TestBed.flushEffects();
});
afterEach(() => {
TestBed.resetTestingModule();
vi.runOnlyPendingTimers();
vi.useRealTimers();
vi.restoreAllMocks();
});
it('queries matching book groups locally after the debounce window', async () => {
service.query.set('tolkien');
TestBed.flushEffects();
await vi.advanceTimersByTimeAsync(200);
TestBed.flushEffects();
const bookGroup = service.groups().find((group) => group.kind === 'book');
expect(bookGroup).toBeDefined();
expect(bookGroup?.items.map((item) => item.title)).toEqual([
'The Hobbit',
'The Fellowship of the Ring',
]);
});
it('does not show book groups for one-character searches', async () => {
service.query.set('d');
TestBed.flushEffects();
await vi.advanceTimersByTimeAsync(200);
TestBed.flushEffects();
expect(service.groups().find((group) => group.kind === 'book')).toBeUndefined();
});
it('returns no groups when the query is empty', () => {
service.query.set('');
expect(service.groups()).toEqual([]);
expect(service.visibleItems()).toEqual([]);
});
});
@@ -0,0 +1,320 @@
import { computed, inject, Injectable, signal } from '@angular/core';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { Router } from '@angular/router';
import { TranslocoService } from '@jsverse/transloco';
import { debounceTime, distinctUntilChanged } from 'rxjs';
import { BookDialogHelperService } from '../book/components/book-browser/book-dialog-helper.service';
import { filterBooksBySearchTerm, normalizeSearchTerm } from '../book/components/book-browser/filters/HeaderFilter';
import { Book } from '../book/model/book.model';
import { BookService } from '../book/service/book.service';
import { LibraryService } from '../book/service/library.service';
import { ShelfService } from '../book/service/shelf.service';
import { MagicShelfService } from '../magic-shelf/service/magic-shelf.service';
import { UserService } from '../settings/user-management/user.service';
import { NavItem } from '../../shared/layout/navigation/nav-item.model';
import { buildAllNavPages, buildQuickActionNavItems } from '../../shared/layout/navigation/nav-catalog';
import { IconSelection } from '../../shared/service/icon-picker.service';
import { UrlHelperService } from '../../shared/service/url-helper.service';
import { DialogLauncherService } from '../../shared/services/dialog-launcher.service';
import { IconService } from '../../shared/services/icon.service';
import { PaletteGroup, PaletteItem, PaletteItemKind } from './command-palette.model';
interface GroupDef {
kind: PaletteItemKind;
source: PaletteItem[];
cap: number;
}
interface CommandPaletteOverlayController {
open(): void;
close(): void;
focusInput(): void;
}
const BOOK_RESULT_LIMIT = 50;
const MIN_BOOK_SEARCH_LENGTH = 2;
const BOOK_SEARCH_DEBOUNCE_MS = 200;
@Injectable({ providedIn: 'root' })
export class CommandPaletteService {
private readonly router = inject(Router);
private readonly t = inject(TranslocoService);
private readonly userService = inject(UserService);
private readonly bookService = inject(BookService);
private readonly shelfService = inject(ShelfService);
private readonly magicShelfService = inject(MagicShelfService);
private readonly libraryService = inject(LibraryService);
private readonly dialogLauncherService = inject(DialogLauncherService);
private readonly bookDialogHelperService = inject(BookDialogHelperService);
private readonly iconService = inject(IconService);
private readonly urlHelper = inject(UrlHelperService);
private readonly _isOpen = signal(false);
readonly isOpen = this._isOpen.asReadonly();
readonly query = signal('');
private overlayController?: CommandPaletteOverlayController;
private readonly activeLang = toSignal(this.t.langChanges$, { initialValue: this.t.getActiveLang() });
private readonly translate = (key: string): string => this.t.translate(key);
private readonly trimmedQuery = computed(() => this.query().trim());
private readonly debouncedBookQuery = toSignal(
toObservable(this.trimmedQuery).pipe(
debounceTime(BOOK_SEARCH_DEBOUNCE_MS),
distinctUntilChanged(),
),
{ initialValue: this.trimmedQuery() },
);
private readonly localBookItems = computed<PaletteItem[]>(() => {
const query = this.debouncedBookQuery();
if (query.length < MIN_BOOK_SEARCH_LENGTH) {
return [];
}
return filterBooksBySearchTerm(this.bookService.books(), query)
.slice(0, BOOK_RESULT_LIMIT)
.map((book) => this.toPaletteBookItem(book));
});
registerOverlayController(controller: CommandPaletteOverlayController): () => void {
this.overlayController = controller;
return () => {
if (this.overlayController === controller) {
this.overlayController = undefined;
}
};
}
open(): void {
if (!this._isOpen()) {
this.overlayController?.open();
this._isOpen.set(true);
} else {
this.overlayController?.focusInput();
}
this.prefetchCustomIcons();
}
private prefetchCustomIcons(): void {
const seen = new Set<string>();
const collect = (items: PaletteItem[]) => {
for (const item of items) {
if (item.icon?.type === 'CUSTOM_SVG' && !seen.has(item.icon.value)) {
seen.add(item.icon.value);
this.iconService.getSvgIconContent(item.icon.value).subscribe({ error: () => undefined });
}
}
};
collect(this.indexedLibraries());
collect(this.indexedShelves());
collect(this.indexedMagicShelves());
}
hide(): void {
this.overlayController?.close();
this._isOpen.set(false);
this.query.set('');
}
toggle(): void {
if (this._isOpen()) {
this.hide();
} else {
this.open();
}
}
select(item: PaletteItem): void {
this.hide();
queueMicrotask(() => {
if (item.command) {
item.command();
return;
}
if (item.route) {
void this.router.navigate(item.route, item.queryParams ? { queryParams: item.queryParams } : {});
}
});
}
readonly groups = computed<PaletteGroup[]>(() => {
const raw = this.trimmedQuery();
const normalized = normalizeSearchTerm(raw);
const tokens = normalized ? normalized.split(/\s+/).filter(Boolean) : [];
if (tokens.length === 0) {
return [];
}
const groups: PaletteGroup[] = [];
const bookItems = this.visibleBookItems();
if (bookItems.length > 0) {
groups.push({ kind: 'book', items: bookItems });
}
const defs: GroupDef[] = [
{ kind: 'shelf', source: this.indexedShelves(), cap: 10 },
{ kind: 'magicShelf', source: this.indexedMagicShelves(), cap: 10 },
{ kind: 'library', source: this.indexedLibraries(), cap: 10 },
{ kind: 'page', source: this.indexedPages(), cap: 10 },
{ kind: 'action', source: this.indexedActions(), cap: 10 },
];
groups.push(
...defs
.map((def) => ({
kind: def.kind,
items: this.filterItems(def.source, tokens, def.cap),
}))
.filter((group) => group.items.length > 0)
);
return groups;
});
readonly visibleItems = computed<PaletteItem[]>(() =>
this.groups().flatMap((group) => group.items)
);
readonly isSearching = computed(() => {
const raw = this.trimmedQuery();
if (raw.length < MIN_BOOK_SEARCH_LENGTH) {
return false;
}
return raw !== this.debouncedBookQuery();
});
private filterItems(source: PaletteItem[], tokens: string[], cap: number): PaletteItem[] {
const matched: PaletteItem[] = [];
for (const item of source) {
if (matched.length >= cap) break;
let hit = true;
for (const tok of tokens) {
if (!item.searchText.includes(tok)) {
hit = false;
break;
}
}
if (hit) {
matched.push(item);
}
}
return matched;
}
private readonly indexedActions = computed<PaletteItem[]>(() => {
this.activeLang();
const user = this.userService.currentUser();
if (!user) return [];
return buildQuickActionNavItems(this.translate, user.permissions, {
createLibrary: () => this.dialogLauncherService.openLibraryCreateDialog(),
createShelf: () => this.bookDialogHelperService.openShelfCreatorDialog(),
createMagicShelf: () => this.dialogLauncherService.openMagicShelfCreateDialog(),
uploadBook: () => this.dialogLauncherService.openFileUploadDialog(),
}).map((item) => this.toPaletteNavItem(item, 'action'));
});
private readonly indexedPages = computed<PaletteItem[]>(() => {
this.activeLang();
const user = this.userService.currentUser();
if (!user) return [];
return buildAllNavPages(this.translate, user.permissions)
.map((item) => this.toPaletteNavItem(item, 'page'));
});
private readonly indexedShelves = computed<PaletteItem[]>(() =>
this.shelfService.shelves()
.filter((shelf) => shelf.id != null)
.map((shelf) => ({
id: `shelf:${shelf.id}`,
kind: 'shelf' as const,
title: shelf.name,
icon: this.iconSelectionFor(shelf.icon, shelf.iconType, 'pi-bookmark'),
searchText: normalizeSearchTerm(shelf.name),
route: [`/shelf/${shelf.id}/books`],
}))
);
private readonly indexedMagicShelves = computed<PaletteItem[]>(() =>
this.magicShelfService.shelves()
.filter((shelf) => shelf.id != null)
.map((shelf) => ({
id: `magic-shelf:${shelf.id}`,
kind: 'magicShelf' as const,
title: shelf.name,
icon: this.iconSelectionFor(shelf.icon, shelf.iconType, 'pi-sparkles'),
searchText: normalizeSearchTerm(shelf.name),
route: [`/magic-shelf/${shelf.id}/books`],
}))
);
private readonly indexedLibraries = computed<PaletteItem[]>(() =>
this.libraryService.libraries()
.filter((library) => library.id != null)
.map((library) => ({
id: `library:${library.id}`,
kind: 'library' as const,
title: library.name,
icon: this.iconSelectionFor(library.icon, library.iconType, 'pi-folder'),
searchText: normalizeSearchTerm(library.name),
route: [`/library/${library.id}/books`],
}))
);
private readonly visibleBookItems = computed<PaletteItem[]>(() =>
this.trimmedQuery().length >= MIN_BOOK_SEARCH_LENGTH ? this.localBookItems() : []
);
private iconSelectionFor(
value: string | null | undefined,
iconType: string | null | undefined,
fallback: string,
): IconSelection {
if (!value) return { type: 'PRIME_NG', value: fallback };
if (iconType === 'CUSTOM_SVG') return { type: 'CUSTOM_SVG', value };
return { type: 'PRIME_NG', value };
}
private toPaletteBookItem(book: Book): PaletteItem {
const metadata = book.metadata;
const title = metadata?.title ?? book.primaryFile?.fileName ?? book.fileName ?? '';
const authors = metadata?.authors ?? [];
const publishedDate = metadata?.publishedDate ?? '';
const year = publishedDate && /^\d{4}/.test(publishedDate) ? publishedDate.slice(0, 4) : null;
const haystack = [title, metadata?.seriesName ?? '', ...authors].filter(Boolean).join(' ');
return {
id: `book:${book.id}`,
kind: 'book',
title,
icon: { type: 'PRIME_NG', value: 'pi-book' },
searchText: normalizeSearchTerm(haystack),
route: ['/book', book.id],
queryParams: { tab: 'view' },
bookMeta: {
thumbnailUrl: this.urlHelper.getThumbnailUrl(book.id, metadata?.coverUpdatedOn),
authors,
seriesName: metadata?.seriesName ?? null,
seriesNumber: metadata?.seriesNumber ?? null,
year,
},
};
}
private toPaletteNavItem(item: NavItem, kind: Extract<PaletteItemKind, 'action' | 'page'>): PaletteItem {
return {
id: `${kind}:${item.id}`,
kind,
title: item.label,
icon: item.icon ? { type: 'PRIME_NG', value: item.icon } : undefined,
searchText: normalizeSearchTerm(item.label),
route: item.routerLink,
command: item.action,
};
}
}
@@ -4,8 +4,8 @@
margin-bottom: 2rem;
position: relative;
overflow: hidden;
background: rgb(30 30 45 / 40%);
border: color-mix(in srgb, var(--p-surface-500), transparent 50%) 1px solid;
background: transparent;
border: 1px solid var(--border-subtle);
}
.dashboard-scroller-title {
@@ -14,7 +14,7 @@
font-weight: 800;
margin-bottom: 1rem;
padding: 0;
background: linear-gradient(135deg, #fff, #e2e8f0, #3b82f6);
background: linear-gradient(135deg, var(--text-color), var(--text-color-secondary), var(--primary-color));
background-clip: text;
-webkit-text-fill-color: transparent;
position: relative;
@@ -1,24 +1,28 @@
.dashboard-container {
height: calc(100dvh - 6.7rem);
box-sizing: border-box;
height: 100%;
overflow-y: auto;
position: relative;
}
@media (width <= 768px) {
.dashboard-container {
height: calc(100dvh - 5rem);
}
}
.dashboard {
box-sizing: border-box;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 100%;
padding: 1.1rem 1.1rem 0;
text-align: center;
position: relative;
z-index: 1;
}
@media (width <= 768px) {
.dashboard {
padding: 0.5rem 0.5rem 0;
}
}
.loading-state {
display: flex;
align-items: center;
@@ -42,7 +46,7 @@
font-size: 1.75rem;
font-weight: 700;
margin-bottom: 2rem;
background: linear-gradient(135deg, #fff, #e2e8f0, var(--p-primary-500));
background: linear-gradient(135deg, var(--text-color), var(--text-color-secondary), var(--primary-color));
background-clip: text;
-webkit-text-fill-color: transparent;
text-shadow: 0 2px 4px rgb(0 0 0 / 30%);
@@ -51,9 +55,9 @@
.dashboard-no-library {
padding: 3rem;
background: var(--p-surface-900);
background: transparent;
border-radius: 24px;
border: 1px solid var(--p-content-border-color);
border: 1px solid var(--border-subtle);
position: relative;
overflow: hidden;
}
@@ -74,11 +78,11 @@
::ng-deep .p-button {
box-shadow: 0 4px 12px rgb(0 0 0 / 30%);
background: rgb(var(--p-surface-900-rgb), 80%);
border: 1px solid var(--p-content-border-color);
background: transparent;
border: 1px solid var(--border-subtle);
&:hover {
background: rgb(var(--p-surface-800-rgb), 90%);
background: var(--surface-toolbar);
transform: scale(1.05);
transition: all 0.2s ease;
}
@@ -116,6 +116,16 @@ export class MagicShelfService {
).length;
}
readonly bookCountByMagicShelfId = computed(() => {
const counts = new Map<number, number>();
for (const shelf of this.shelves()) {
if (shelf.id != null) {
counts.set(shelf.id, this.getBookCountValue(shelf.id));
}
}
return counts;
});
deleteShelf(id: number): Observable<void> {
return this.http.delete<void>(`${this.url}/${id}`).pipe(
tap(() => {
@@ -13,42 +13,45 @@
}
.tabs-wrapper {
border-radius: 0.75rem;
flex: 1 1 auto;
min-height: 0;
overflow: hidden;
border: 1px solid var(--p-content-border-color);
}
.tabs-wrapper > p-tabs {
display: flex;
flex-direction: column;
height: 100%;
min-height: 0;
}
.tabs-wrapper > p-tabs > p-tablist {
flex: 0 0 auto;
}
.dialog-mode {
border: 1px solid var(--p-content-border-color);
border-radius: 0 0 0.75rem 0.75rem !important;
border-width: 1px 0 0 !important;
}
.tabpanels-responsive {
flex: 1 1 auto;
min-height: 0;
overflow: auto;
}
::ng-deep .layout-main .tabpanels-responsive {
height: calc(100dvh - 9.7rem);
}
@media (width <= 768px) {
::ng-deep .layout-main .tabpanels-responsive {
height: calc(100dvh - 8.5rem);
}
}
::ng-deep .book-details-dialog .p-dialog-content,
::ng-deep .book-details-dialog app-book-metadata-center,
::ng-deep .book-details-dialog app-book-metadata-center > div,
::ng-deep .book-details-dialog app-book-metadata-center p-tabs {
:host-context(.book-details-dialog) {
display: flex;
width: 100%;
}
::ng-deep .book-details-dialog p-tablist {
flex-shrink: 0;
:host-context(.book-details-dialog) .book-metadata-center-container,
:host-context(.book-details-dialog) p-tabs {
display: flex;
width: 100%;
}
::ng-deep .book-details-dialog .p-dialog-content {
padding: 0;
:host-context(.book-details-dialog) p-tablist {
flex-shrink: 0;
}
@@ -114,26 +114,25 @@
.main-container {
width: 100%;
padding: 1rem;
height: calc(100dvh - 10.5rem);
border-width: 1px;
border-radius: 0.5rem;
box-sizing: border-box;
padding: 1rem 0;
height: 100%;
min-height: 0;
display: flex;
flex-direction: column;
@media (width >= 768px) {
height: calc(100dvh - 6.125rem);
}
}
.enclosing-container {
border-color: var(--p-content-border-color);
background: var(--p-content-background);
}
.settings-header {
margin-top: 0.75rem;
flex-shrink: 0;
@media (width >= 768px) {
padding: 0 1rem;
}
}
.settings-title {
@@ -257,7 +256,6 @@
border: 1px solid rgb(128 128 128 / 20%);
border-radius: 8px;
overflow: hidden;
background: var(--ground-background);
display: flex;
flex-direction: column;
flex: 1;
@@ -4,11 +4,32 @@
.main-container {
@include settings.settings-page-container;
gap: 0;
overflow-y: hidden;
height: calc(100dvh - 5rem);
padding: 0;
}
@media (width >= 768px) {
height: calc(100dvh - 5.6rem);
.main-container > .settings-header,
.main-container > .settings-card {
margin-inline: 1.1rem;
}
.main-container > .settings-header {
margin-top: 1.1rem;
}
.main-container > .settings-card {
margin-top: 1.5rem;
}
@media (width <= 768px) {
.main-container > .settings-header,
.main-container > .settings-card {
margin-inline: 0.5rem;
}
.main-container > .settings-header {
margin-top: 0.5rem;
}
}
@@ -20,6 +41,11 @@
display: flex;
flex-direction: column;
gap: 1.5rem;
padding: 1.5rem 1.1rem 0;
@media (width <= 768px) {
padding: 1.5rem 0.5rem 0;
}
}
@include settings.settings-page-header;
@@ -274,9 +274,6 @@
object-fit: contain;
box-shadow: 0 8px 32px rgb(0 0 0 / 60%);
border-radius: 4px;
&.previous-image {
}
}
&.fit-width {
@@ -294,12 +294,10 @@ $transition-fast: 150ms ease;
inset: 0;
width: 100%;
height: 100%;
overflow-x: hidden;
overflow-y: auto;
overflow: hidden auto;
&.horizontal-scroll {
overflow-x: auto;
overflow-y: hidden;
overflow: auto hidden;
}
embedpdf-container {
@@ -1,4 +1,5 @@
<ng-container *transloco="let t; prefix: 'seriesBrowser'">
<div class="series-browser-page">
@if (isBooksLoading()) {
<div class="loading-state">
<p-progressSpinner
@@ -93,4 +94,5 @@
}
}
}
</div>
</ng-container>
@@ -1,13 +1,24 @@
.series-browser-page {
--browser-gutter-inline: 2.1rem;
display: flex;
flex-direction: column;
height: 100%;
min-height: 0;
padding: 1.1rem 0 0;
}
.loading-state {
display: flex;
flex: 1 1 auto;
align-items: center;
justify-content: center;
height: calc(100dvh - 6.7rem);
min-height: 0;
}
// Browse Header
.browse-header {
padding: 0.75rem 1rem 0;
padding: 0.75rem var(--browser-gutter-inline) 0;
}
.browse-title {
@@ -98,19 +109,25 @@
// Virtual scroller and grid
.virtual-scroller {
flex: 1 1 auto;
width: 100%;
height: calc(100dvh - 12.5rem);
padding: 1rem;
min-height: 0;
padding: 1rem var(--browser-gutter-inline);
box-sizing: border-box;
overflow: hidden auto;
scrollbar-gutter: stable;
@media (width <= 768px) {
height: calc(100dvh - 13rem);
padding: 0.5rem;
padding-block: 0.5rem;
}
}
.virtual-scroller-item {
position: relative;
overflow: visible;
transition: width 0.2s ease, height 0.2s ease;
}
// Empty state
.empty-state {
display: flex;
@@ -134,8 +151,14 @@
}
@media (width <= 767px) {
.series-browser-page {
--browser-gutter-inline: 0.5rem;
padding: 1.5rem 0 0;
}
.browse-header {
padding: 0.5rem 0.5rem 0;
padding-top: 0.5rem;
}
.browse-controls {
@@ -120,7 +120,6 @@ export class SeriesBrowserComponent implements OnInit {
minItemWidth: this.minCardWidth,
gap: SeriesBrowserComponent.GRID_GAP,
initialOffset: this.initialScrollOffset,
fillItemWidth: true,
estimateItemHeight: itemWidth => Math.round(itemWidth * this.cardAspectRatio()),
});
readonly currentCardScale = computed(() => this.virtualGrid.itemWidth() / this.baseCardWidth());
@@ -3,12 +3,9 @@
.main-container {
width: 100%;
padding: 1rem;
height: calc(100dvh - 10.5rem);
height: 100%;
min-height: 0;
overflow-y: auto;
@media (width >= 768px) {
height: calc(100dvh - 11.65rem);
}
}
@include settings.settings-page-header;
@@ -1,5 +1,48 @@
:host {
display: block;
height: 100%;
min-height: 0;
}
.settings-container {
border-radius: 0.75rem;
display: flex;
flex-direction: column;
height: 100%;
min-height: 0;
}
.settings-container > p-tabs,
.settings-container p-tabs.p-tabs {
display: flex;
flex-direction: column;
height: 100%;
min-height: 0;
}
.settings-container p-tablist {
flex: 0 0 auto;
}
.settings-container p-tabpanels {
display: flex;
flex: 1 1 auto;
flex-direction: column;
min-height: 0;
overflow: hidden;
border: 1px solid var(--p-content-border-color);
padding: 0;
background: transparent;
}
.settings-container p-tabpanel.p-tabpanel-active {
display: flex;
flex: 1 1 auto;
flex-direction: column;
min-height: 0;
}
.settings-container p-tabpanel.p-tabpanel-active > * {
display: block;
flex: 1 1 auto;
min-height: 0;
height: 100%;
}
@@ -0,0 +1,32 @@
<ng-container *transloco="let t; prefix: 'settingsView.language'">
<div class="settings-card">
<div class="section-header">
<h3 class="section-title">
<i class="pi pi-language"></i>
{{ t('sectionTitle') }}
</h3>
<p class="section-description">{{ t('sectionDesc') }}</p>
</div>
<div class="section-body">
<div class="setting-item">
<div class="setting-header-standalone">
<span class="setting-label">{{ t('label') }}</span>
</div>
<div class="setting-options">
<div class="select-group">
<p-select
size="small"
[options]="languageOptions"
[ngModel]="activeLang()"
(ngModelChange)="onLanguageChange($event)"
optionLabel="label"
optionValue="value"
appendTo="body">
</p-select>
</div>
</div>
</div>
</div>
</div>
</ng-container>
@@ -0,0 +1,41 @@
@use '../../../../shared/styles/settings-shared' as settings;
.settings-card {
@include settings.settings-card;
}
.section-header {
@include settings.settings-section-header;
}
.section-title {
@include settings.settings-section-title;
}
.section-description {
@include settings.settings-section-description;
}
.section-body {
@include settings.settings-section-body;
}
.setting-item {
@include settings.settings-item;
}
.setting-header-standalone {
@include settings.settings-item-header-standalone;
}
.setting-label {
@include settings.settings-label;
}
.setting-options {
@include settings.settings-options;
}
.select-group {
@include settings.settings-select-group;
}
@@ -0,0 +1,35 @@
import {Component, DestroyRef, inject} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {takeUntilDestroyed, toSignal} from '@angular/core/rxjs-interop';
import {Select} from 'primeng/select';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
import {AVAILABLE_LANGS, LANG_LABELS} from '../../../../core/config/transloco-loader';
import {LANG_STORAGE_KEY} from '../../../../core/config/language-initializer';
@Component({
selector: 'app-language-preferences',
standalone: true,
imports: [FormsModule, Select, TranslocoDirective],
templateUrl: './language-preferences.component.html',
styleUrl: './language-preferences.component.scss',
})
export class LanguagePreferencesComponent {
readonly languageOptions = AVAILABLE_LANGS.map(value => ({
value,
label: LANG_LABELS[value] ?? value,
}));
private readonly t = inject(TranslocoService);
private readonly destroyRef = inject(DestroyRef);
readonly activeLang = toSignal(this.t.langChanges$, {initialValue: this.t.getActiveLang()});
onLanguageChange(lang: string): void {
if (lang === this.activeLang()) return;
this.t.load(lang).pipe(takeUntilDestroyed(this.destroyRef)).subscribe({
next: () => {
this.t.setActiveLang(lang);
localStorage.setItem(LANG_STORAGE_KEY, lang);
},
});
}
}
@@ -19,9 +19,9 @@
<div class="setting-options">
<p-select
size="small"
[options]="sortingOptions"
[(ngModel)]="selectedLibrarySorting"
(ngModelChange)="onLibrarySortingChange()"
[options]="sortingOptions()"
[ngModel]="selectedLibrarySorting()"
(ngModelChange)="onLibrarySortingChange($event)"
appendTo="body"
optionLabel="label"
optionValue="value"
@@ -38,9 +38,9 @@
<div class="setting-options">
<p-select
size="small"
[options]="sortingOptions"
[(ngModel)]="selectedShelfSorting"
(ngModelChange)="onShelfSortingChange()"
[options]="sortingOptions()"
[ngModel]="selectedShelfSorting()"
(ngModelChange)="onShelfSortingChange($event)"
appendTo="body"
optionLabel="label"
optionValue="value"
@@ -57,9 +57,9 @@
<div class="setting-options">
<p-select
size="small"
[options]="sortingOptions"
[(ngModel)]="selectedMagicShelfSorting"
(ngModelChange)="onMagicShelfSortingChange()"
[options]="sortingOptions()"
[ngModel]="selectedMagicShelfSorting()"
(ngModelChange)="onMagicShelfSortingChange($event)"
appendTo="body"
optionLabel="label"
optionValue="value"
@@ -1,85 +1,43 @@
import {signal} from '@angular/core';
import {signal, WritableSignal} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {MessageService} from 'primeng/api';
import {getTranslocoModule} from '../../../../core/testing/transloco-testing';
import {User, UserService, UserSettings} from '../../user-management/user.service';
import {LayoutService} from '../../../../shared/layout/layout.service';
import {SortPref} from '../../../../shared/layout/sidebar-sort-preferences';
import {SidebarSortingPreferencesComponent} from './sidebar-sorting-preferences.component';
function createUserSettings(): UserSettings {
return {
perBookSetting: {pdf: 'Global', epub: 'Individual', cbx: 'Global'},
pdfReaderSetting: {pageSpread: 'off', pageZoom: '100%', showSidebar: true},
epubReaderSetting: {theme: 'light', font: 'serif', fontSize: 16, flow: 'paginated', spread: 'auto', lineHeight: 1.5, margin: 1, letterSpacing: 0},
ebookReaderSetting: {lineHeight: 1.5, justify: true, hyphenate: true, maxColumnCount: 1, gap: 1, fontSize: 16, theme: 'light', maxInlineSize: 100, maxBlockSize: 100, fontFamily: 'serif', isDark: false, flow: 'paginated'},
cbxReaderSetting: {pageSpread: 'EVEN', pageViewMode: 'SINGLE_PAGE', fitMode: 'AUTO'},
newPdfReaderSetting: {pageSpread: 'EVEN', pageViewMode: 'SINGLE_PAGE', fitMode: 'AUTO'},
sidebarLibrarySorting: {field: 'name', order: 'asc'},
sidebarShelfSorting: {field: 'id', order: 'desc'},
sidebarMagicShelfSorting: {field: 'name', order: 'desc'},
filterMode: 'and',
metadataCenterViewMode: 'route',
enableSeriesView: true,
entityViewPreferences: {global: {sortKey: 'title', sortDir: 'ASC', view: 'GRID', coverSize: 100, seriesCollapsed: false, overlayBookType: false}, overrides: []},
koReaderEnabled: false,
autoSaveMetadata: true,
} as UserSettings;
}
function createUser(): User {
return {
id: 9,
username: 'tester',
name: 'Tester',
email: 'tester@example.com',
assignedLibraries: [],
permissions: {
admin: false,
canUpload: false,
canDownload: false,
canEmailBook: false,
canDeleteBook: false,
canEditMetadata: false,
canManageLibrary: false,
canManageMetadataConfig: false,
canSyncKoReader: false,
canSyncKobo: false,
canAccessOpds: false,
canAccessBookdrop: false,
canAccessLibraryStats: false,
canAccessUserStats: false,
canAccessTaskManager: false,
canManageEmailConfig: false,
canManageGlobalPreferences: false,
canManageIcons: false,
canManageFonts: false,
demoUser: false,
canBulkAutoFetchMetadata: false,
canBulkCustomFetchMetadata: false,
canBulkEditMetadata: false,
canBulkRegenerateCover: false,
canMoveOrganizeFiles: false,
canBulkLockUnlockMetadata: false,
},
userSettings: createUserSettings(),
};
}
describe('SidebarSortingPreferencesComponent', () => {
let fixture: ComponentFixture<SidebarSortingPreferencesComponent>;
let updateUserSetting: ReturnType<typeof vi.fn>;
let setLibrarySort: ReturnType<typeof vi.fn>;
let messageService: {add: ReturnType<typeof vi.fn>};
let librarySort: WritableSignal<SortPref>;
let shelfSort: WritableSignal<SortPref>;
let magicShelfSort: WritableSignal<SortPref>;
beforeEach(() => {
updateUserSetting = vi.fn();
librarySort = signal<SortPref>({field: 'name', order: 'asc'});
shelfSort = signal<SortPref>({field: 'id', order: 'desc'});
magicShelfSort = signal<SortPref>({field: 'name', order: 'desc'});
setLibrarySort = vi.fn((value: SortPref) => librarySort.set(value));
messageService = {add: vi.fn()};
TestBed.configureTestingModule({
imports: [SidebarSortingPreferencesComponent, getTranslocoModule({translocoConfig: {reRenderOnLangChange: false}})],
providers: [
{provide: UserService, useValue: {currentUser: signal(createUser()), updateUserSetting}},
{
provide: LayoutService,
useValue: {
librarySort,
shelfSort,
magicShelfSort,
setLibrarySort,
setShelfSort: vi.fn((value: SortPref) => shelfSort.set(value)),
setMagicShelfSort: vi.fn((value: SortPref) => magicShelfSort.set(value)),
},
},
{provide: MessageService, useValue: messageService},
],
});
@@ -97,18 +55,18 @@ describe('SidebarSortingPreferencesComponent', () => {
it('hydrates sidebar sorting selections from the current user', () => {
const component = fixture.componentInstance;
expect(component.selectedLibrarySorting).toEqual({field: 'name', order: 'asc'});
expect(component.selectedShelfSorting).toEqual({field: 'id', order: 'desc'});
expect(component.sortingOptions).not.toHaveLength(0);
expect(component.selectedLibrarySorting()).toEqual({field: 'name', order: 'asc'});
expect(component.selectedShelfSorting()).toEqual({field: 'id', order: 'desc'});
expect(component.selectedMagicShelfSorting()).toEqual({field: 'name', order: 'desc'});
expect(component.sortingOptions()).not.toHaveLength(0);
});
it('persists library sorting changes and shows a success toast', () => {
const component = fixture.componentInstance;
component.selectedLibrarySorting = {field: 'id', order: 'asc'};
component.onLibrarySortingChange();
component.onLibrarySortingChange({field: 'id', order: 'asc'});
expect(updateUserSetting).toHaveBeenCalledWith(9, 'sidebarLibrarySorting', {field: 'id', order: 'asc'});
expect(setLibrarySort).toHaveBeenCalledWith({field: 'id', order: 'asc'});
expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'success'}));
});
});
@@ -1,12 +1,11 @@
import {Component, DestroyRef, effect, inject, OnInit} from '@angular/core';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
import {Component, computed, inject} from '@angular/core';
import {toSignal} from '@angular/core/rxjs-interop';
import {Select} from 'primeng/select';
import {SidebarLibrarySorting, SidebarMagicShelfSorting, SidebarShelfSorting, User, UserService, UserSettings} from '../../user-management/user.service';
import {MessageService} from 'primeng/api';
import {FormsModule} from '@angular/forms';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
type MutableSettingsBranch = Record<string, unknown>;
import {LayoutService} from '../../../../shared/layout/layout.service';
import {SortPref} from '../../../../shared/layout/sidebar-sort-preferences';
@Component({
selector: 'app-sidebar-sorting-preferences',
@@ -18,73 +17,47 @@ type MutableSettingsBranch = Record<string, unknown>;
templateUrl: './sidebar-sorting-preferences.component.html',
styleUrl: './sidebar-sorting-preferences.component.scss'
})
export class SidebarSortingPreferencesComponent implements OnInit {
export class SidebarSortingPreferencesComponent {
private readonly sortingOptionDefs = [
{value: {field: 'name', order: 'asc'}, translationKey: 'nameAsc'},
{value: {field: 'name', order: 'desc'}, translationKey: 'nameDesc'},
{value: {field: 'id', order: 'asc'}, translationKey: 'creationAsc'},
{value: {field: 'id', order: 'desc'}, translationKey: 'creationDesc'},
];
] satisfies {value: SortPref; translationKey: string}[];
sortingOptions: {label: string; value: {field: string; order: string}; translationKey: string}[] = [];
selectedLibrarySorting: SidebarLibrarySorting = {field: 'id', order: 'asc'};
selectedShelfSorting: SidebarShelfSorting = {field: 'id', order: 'asc'};
selectedMagicShelfSorting: SidebarMagicShelfSorting = {field: 'id', order: 'asc'};
private readonly userService = inject(UserService);
private readonly layoutService = inject(LayoutService);
private readonly messageService = inject(MessageService);
private readonly t = inject(TranslocoService);
private readonly destroyRef = inject(DestroyRef);
private readonly activeLang = toSignal(this.t.langChanges$, {initialValue: this.t.getActiveLang()});
private currentUser: User | null = null;
private hasInitialized = false;
readonly selectedLibrarySorting = this.layoutService.librarySort;
readonly selectedShelfSorting = this.layoutService.shelfSort;
readonly selectedMagicShelfSorting = this.layoutService.magicShelfSort;
private readonly syncUserEffect = effect(() => {
const user = this.userService.currentUser();
if (!user) return;
this.currentUser = user;
if (!this.hasInitialized) {
this.hasInitialized = true;
this.loadPreferences(user.userSettings);
}
});
ngOnInit(): void {
this.buildSortingOptions();
this.t.langChanges$.pipe(takeUntilDestroyed(this.destroyRef)).subscribe(() => this.buildSortingOptions());
}
private buildSortingOptions(): void {
this.sortingOptions = this.sortingOptionDefs.map(opt => ({
readonly sortingOptions = computed(() => {
this.activeLang();
return this.sortingOptionDefs.map(opt => ({
...opt,
label: this.t.translate('settingsView.sidebarSort.' + opt.translationKey)
}));
});
onLibrarySortingChange(value: SortPref) {
this.layoutService.setLibrarySort(value);
this.showSuccessToast();
}
private loadPreferences(settings: UserSettings): void {
this.selectedLibrarySorting = settings.sidebarLibrarySorting;
this.selectedShelfSorting = settings.sidebarShelfSorting;
this.selectedMagicShelfSorting = settings.sidebarMagicShelfSorting;
onShelfSortingChange(value: SortPref) {
this.layoutService.setShelfSort(value);
this.showSuccessToast();
}
private updatePreference(path: string[], value: unknown): void {
if (!this.currentUser) return;
let target = this.currentUser.userSettings as unknown as MutableSettingsBranch;
for (let i = 0; i < path.length - 1; i++) {
const next = target[path[i]];
if (!next || typeof next !== 'object') {
target[path[i]] = {};
}
target = target[path[i]] as MutableSettingsBranch;
}
target[path.at(-1)!] = value;
onMagicShelfSortingChange(value: SortPref) {
this.layoutService.setMagicShelfSort(value);
this.showSuccessToast();
}
const [rootKey] = path;
const updatedValue = this.currentUser.userSettings[rootKey as keyof UserSettings];
this.userService.updateUserSetting(this.currentUser.id, rootKey, updatedValue);
private showSuccessToast(): void {
this.messageService.add({
severity: 'success',
summary: this.t.translate('settingsView.sidebarSort.prefsUpdated'),
@@ -92,16 +65,4 @@ export class SidebarSortingPreferencesComponent implements OnInit {
life: 1500
});
}
onLibrarySortingChange() {
this.updatePreference(['sidebarLibrarySorting'], this.selectedLibrarySorting);
}
onShelfSortingChange() {
this.updatePreference(['sidebarShelfSorting'], this.selectedShelfSorting);
}
onMagicShelfSortingChange() {
this.updatePreference(['sidebarMagicShelfSorting'], this.selectedMagicShelfSorting);
}
}
@@ -0,0 +1,15 @@
<ng-container *transloco="let t; prefix: 'settingsView.theme'">
<div class="settings-card">
<div class="section-header">
<h3 class="section-title">
<i class="pi pi-palette"></i>
{{ t('sectionTitle') }}
</h3>
<p class="section-description">{{ t('sectionDesc') }}</p>
</div>
<div class="section-body">
<app-theme-configurator></app-theme-configurator>
</div>
</div>
</ng-container>
@@ -0,0 +1,21 @@
@use '../../../../shared/styles/settings-shared' as settings;
.settings-card {
@include settings.settings-card;
}
.section-header {
@include settings.settings-section-header;
}
.section-title {
@include settings.settings-section-title;
}
.section-description {
@include settings.settings-section-description;
}
.section-body {
@include settings.settings-section-body;
}
@@ -0,0 +1,12 @@
import {Component} from '@angular/core';
import {TranslocoDirective} from '@jsverse/transloco';
import {ThemeConfiguratorComponent} from '../../../../shared/layout/theme-configurator/theme-configurator.component';
@Component({
selector: 'app-theme-preferences',
standalone: true,
imports: [TranslocoDirective, ThemeConfiguratorComponent],
templateUrl: './theme-preferences.component.html',
styleUrl: './theme-preferences.component.scss',
})
export class ThemePreferencesComponent {}
@@ -10,6 +10,11 @@
</p>
</div>
<app-language-preferences></app-language-preferences>
<div class="section-divider"><hr></div>
<app-theme-preferences></app-theme-preferences>
<div class="section-divider"><hr></div>
<app-view-preferences></app-view-preferences>
<div class="section-divider"><hr></div>
<app-filter-preferences></app-filter-preferences>
@@ -35,10 +40,9 @@
<div class="slider-container">
<p-slider
[(ngModel)]="sidebarWidth"
[min]="175"
[max]="400"
[min]="SIDEBAR_MIN_WIDTH"
[max]="SIDEBAR_MAX_WIDTH"
[step]="1"
(onChange)="onSidebarWidthChange()"
(onSlideEnd)="saveSidebarWidth()">
</p-slider>
</div>
@@ -1,22 +1,30 @@
import {signal} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {describe, expect, it, vi} from 'vitest';
import {ViewPreferencesParentComponent} from './view-preferences-parent.component';
import {LocalStorageService} from '../../../shared/service/local-storage.service';
import {MessageService} from 'primeng/api';
import {TranslocoService} from '@jsverse/transloco';
import {LayoutService} from '../../../shared/layout/layout.service';
describe('ViewPreferencesParentComponent', () => {
it('loads and saves the sidebar width', () => {
const localStorageGet = vi.fn(() => 312);
const localStorageSet = vi.fn();
function createLayoutService(initialWidth: number) {
const sidebarWidth = signal(initialWidth);
return {
sidebarWidth,
setSidebarWidth: vi.fn((value: number) => sidebarWidth.set(value)),
};
}
it('reads the sidebar width from LayoutService and saves it back with persistence', () => {
const layoutService = createLayoutService(312);
const messageAdd = vi.fn();
const translate = vi.fn(key => key);
TestBed.configureTestingModule({
imports: [ViewPreferencesParentComponent],
providers: [
{provide: LocalStorageService, useValue: {get: localStorageGet, set: localStorageSet}},
{provide: LayoutService, useValue: layoutService},
{provide: MessageService, useValue: {add: messageAdd}},
{provide: TranslocoService, useValue: {translate}},
]
@@ -25,12 +33,11 @@ describe('ViewPreferencesParentComponent', () => {
const fixture = TestBed.createComponent(ViewPreferencesParentComponent);
const component = fixture.componentInstance;
component.ngOnInit();
expect(component.sidebarWidth).toBe(312);
component.saveSidebarWidth();
expect(localStorageSet).toHaveBeenCalledWith('sidebarWidth', 312);
expect(layoutService.setSidebarWidth).toHaveBeenCalledWith(312, true);
expect(messageAdd).toHaveBeenCalledWith({
severity: 'success',
summary: 'settingsView.layout.saved',
@@ -38,13 +45,13 @@ describe('ViewPreferencesParentComponent', () => {
});
});
it('updates the sidebar CSS variable when the width changes', () => {
const localStorageGet = vi.fn(() => 225);
it('updates the layout service width immediately while the slider moves', () => {
const layoutService = createLayoutService(225);
TestBed.configureTestingModule({
imports: [ViewPreferencesParentComponent],
providers: [
{provide: LocalStorageService, useValue: {get: localStorageGet, set: vi.fn()}},
{provide: LayoutService, useValue: layoutService},
{provide: MessageService, useValue: {add: vi.fn()}},
{provide: TranslocoService, useValue: {translate: vi.fn()}},
]
@@ -54,16 +61,18 @@ describe('ViewPreferencesParentComponent', () => {
const component = fixture.componentInstance;
component.sidebarWidth = 287;
component.onSidebarWidthChange();
expect(document.documentElement.style.getPropertyValue('--sidebar-width')).toBe('287px');
expect(layoutService.setSidebarWidth).toHaveBeenCalledWith(287, false);
expect(component.sidebarWidth).toBe(287);
});
it('falls back to the default width when no value is stored', () => {
it('falls back to the layout service default width when nothing custom is loaded', () => {
const layoutService = createLayoutService(225);
TestBed.configureTestingModule({
imports: [ViewPreferencesParentComponent],
providers: [
{provide: LocalStorageService, useValue: {get: vi.fn(() => null), set: vi.fn()}},
{provide: LayoutService, useValue: layoutService},
{provide: MessageService, useValue: {add: vi.fn()}},
{provide: TranslocoService, useValue: {translate: vi.fn()}},
]
@@ -72,8 +81,6 @@ describe('ViewPreferencesParentComponent', () => {
const fixture = TestBed.createComponent(ViewPreferencesParentComponent);
const component = fixture.componentInstance;
component.ngOnInit();
expect(component.sidebarWidth).toBe(225);
});
});
@@ -1,4 +1,4 @@
import {Component, inject, OnInit} from '@angular/core';
import {Component, inject} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {TableModule} from 'primeng/table';
@@ -6,10 +6,12 @@ import {ViewPreferencesComponent} from './view-preferences/view-preferences.comp
import {SidebarSortingPreferencesComponent} from './sidebar-sorting-preferences/sidebar-sorting-preferences.component';
import {MetaCenterViewModeComponent} from './meta-center-view-mode/meta-center-view-mode-component';
import {FilterPreferencesComponent} from './filter-preferences/filter-preferences.component';
import {LanguagePreferencesComponent} from './language-preferences/language-preferences.component';
import {ThemePreferencesComponent} from './theme-preferences/theme-preferences.component';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
import {Slider} from 'primeng/slider';
import {MessageService} from 'primeng/api';
import {LocalStorageService} from '../../../shared/service/local-storage.service';
import {LayoutService, SIDEBAR_MAX_WIDTH, SIDEBAR_MIN_WIDTH} from '../../../shared/layout/layout.service';
@Component({
selector: 'app-view-preferences-parent',
@@ -21,30 +23,32 @@ import {LocalStorageService} from '../../../shared/service/local-storage.service
SidebarSortingPreferencesComponent,
MetaCenterViewModeComponent,
FilterPreferencesComponent,
LanguagePreferencesComponent,
ThemePreferencesComponent,
TranslocoDirective,
Slider,
],
templateUrl: './view-preferences-parent.component.html',
styleUrl: './view-preferences-parent.component.scss'
})
export class ViewPreferencesParentComponent implements OnInit {
export class ViewPreferencesParentComponent {
sidebarWidth = 225;
readonly SIDEBAR_MIN_WIDTH = SIDEBAR_MIN_WIDTH;
readonly SIDEBAR_MAX_WIDTH = SIDEBAR_MAX_WIDTH;
private localStorageService = inject(LocalStorageService);
private layoutService = inject(LayoutService);
private messageService = inject(MessageService);
private t = inject(TranslocoService);
ngOnInit(): void {
this.sidebarWidth = this.localStorageService.get<number>('sidebarWidth') ?? 225;
get sidebarWidth(): number {
return this.layoutService.sidebarWidth();
}
onSidebarWidthChange(): void {
document.documentElement.style.setProperty('--sidebar-width', this.sidebarWidth + 'px');
set sidebarWidth(value: number) {
this.layoutService.setSidebarWidth(value, false);
}
saveSidebarWidth(): void {
this.localStorageService.set('sidebarWidth', this.sidebarWidth);
this.layoutService.setSidebarWidth(this.layoutService.sidebarWidth(), true);
this.messageService.add({
severity: 'success',
summary: this.t.translate('settingsView.layout.saved'),
@@ -2,7 +2,8 @@
max-width: 2500px;
margin: 0 auto;
background: transparent;
height: calc(100dvh - 6.25rem);
box-sizing: border-box;
height: 100%;
overflow-y: auto;
padding: 0.5rem;
}
@@ -1,8 +1,9 @@
.user-stats-container {
max-width: 1800px;
margin: 0 auto;
box-sizing: border-box;
padding: 0.5rem;
height: calc(100dvh - 6.25rem);
height: 100%;
overflow-y: auto;
}
@@ -3,6 +3,7 @@
flex-direction: column;
gap: 1rem;
width: 25rem;
max-width: 100%;
max-height: 60vh;
overflow-y: auto;
border-radius: 0.5rem;
@@ -12,3 +13,10 @@
margin: 0 !important;
padding: 0 !important;
}
@media (width <= 991px) {
.metadata-progress-box {
width: min(25rem, calc(100vw - 1.5rem));
max-height: calc(100dvh - 1rem);
}
}
@@ -1,14 +1,31 @@
<ng-container *transloco="let t; prefix: 'layout'">
<div class="layout-wrapper" [ngClass]="containerClass()">
<app-topbar></app-topbar>
<div class="layout-sidebar">
<div class="layout-wrapper" [ngClass]="containerClass()" [style.--sidebar-stored-width]="storedSidebarWidth()">
<app-mobile-topbar></app-mobile-topbar>
<nav
class="layout-sidebar"
[attr.aria-label]="t('menu.primaryNav')"
[attr.aria-hidden]="sidebarHidden() ? 'true' : null"
[attr.inert]="sidebarHidden() ? '' : null"
[cdkTrapFocus]="layoutService.mobileDrawerOpen()"
>
<app-menu></app-menu>
</div>
<div class="layout-main-container">
<div class="layout-main">
<router-outlet></router-outlet>
</div>
</div>
<div
class="layout-sidebar-resize-handle"
tabindex="0"
role="slider"
[attr.aria-label]="t('menu.resizeSidebar')"
[attr.aria-valuemin]="sidebarMinWidth"
[attr.aria-valuemax]="sidebarMaxWidth"
[attr.aria-valuenow]="layoutService.sidebarWidth()"
aria-orientation="horizontal"
(mousedown)="startResize($event)"
(keydown)="onResizeKeydown($event)"
(keyup)="onResizeKeyup($event)"
></div>
</nav>
<main class="layout-main">
<router-outlet></router-outlet>
</main>
<button type="button" class="layout-mask" [attr.aria-label]="t('closeNavigation')" (click)="closeMobileSidebar()"></button>
</div>
</ng-container>
@@ -5,7 +5,7 @@ import { provideRouter, Router } from '@angular/router';
import { TranslocoTestingModule } from '@jsverse/transloco';
import { AppLayoutComponent } from './app.layout.component';
import { AppMenuComponent } from '../layout-menu/app.menu.component';
import { AppTopBarComponent } from '../layout-topbar/app.topbar.component';
import { AppMobileTopbarComponent } from '../layout-mobile-topbar/app.mobile-topbar.component';
import { LocalStorageService } from '../../service/local-storage.service';
import { LayoutService } from '../layout.service';
@@ -17,11 +17,11 @@ import { LayoutService } from '../layout.service';
class StubMenuComponent {}
@Component({
selector: 'app-topbar',
selector: 'app-mobile-topbar',
standalone: true,
template: '',
})
class StubTopBarComponent {}
class StubMobileTopbarComponent {}
@Component({
standalone: true,
@@ -34,11 +34,21 @@ describe('AppLayoutComponent', () => {
let router: Router;
let layoutService: LayoutService;
const localStorageValues: Record<string, unknown> = {};
const localStorageService = {
get: vi.fn(() => 225),
get: vi.fn((key: string) => localStorageValues[key]),
set: vi.fn((key: string, value: unknown) => {
localStorageValues[key] = value;
}),
};
beforeEach(async () => {
for (const key of Object.keys(localStorageValues)) {
delete localStorageValues[key];
}
localStorageValues['sidebarWidth'] = 225;
localStorageService.get.mockClear();
localStorageService.set.mockClear();
TestBed.resetTestingModule();
TestBed.configureTestingModule({
imports: [
@@ -56,10 +66,10 @@ describe('AppLayoutComponent', () => {
TestBed.overrideComponent(AppLayoutComponent, {
remove: {
imports: [AppMenuComponent, AppTopBarComponent],
imports: [AppMenuComponent, AppMobileTopbarComponent],
},
add: {
imports: [StubMenuComponent, StubTopBarComponent],
imports: [StubMenuComponent, StubMobileTopbarComponent],
},
});
@@ -79,35 +89,110 @@ describe('AppLayoutComponent', () => {
});
it('closes the mobile sidebar when the mask is clicked', () => {
layoutService.mobileSidebarOpen.set(true);
layoutService.mobileDrawerOpen.set(true);
fixture.detectChanges();
const mask = fixture.nativeElement.querySelector('.layout-mask') as HTMLDivElement;
mask.click();
fixture.detectChanges();
expect(layoutService.mobileSidebarOpen()).toBe(false);
expect(layoutService.mobileDrawerOpen()).toBe(false);
});
it('toggles the body scroll lock with mobile sidebar state', () => {
layoutService.mobileSidebarOpen.set(true);
layoutService.mobileDrawerOpen.set(true);
fixture.detectChanges();
expect(document.body.classList.contains('blocked-scroll')).toBe(true);
layoutService.mobileSidebarOpen.set(false);
layoutService.mobileDrawerOpen.set(false);
fixture.detectChanges();
expect(document.body.classList.contains('blocked-scroll')).toBe(false);
});
it('closes the mobile sidebar on navigation', async () => {
layoutService.mobileSidebarOpen.set(true);
layoutService.mobileDrawerOpen.set(true);
fixture.detectChanges();
await router.navigateByUrl('/next');
fixture.detectChanges();
expect(layoutService.mobileSidebarOpen()).toBe(false);
expect(layoutService.mobileDrawerOpen()).toBe(false);
});
it('uses an explicit sidebar-hidden shell state when the desktop sidebar is hidden', () => {
layoutService.isDesktop.set(true);
layoutService.sidebarVisible.set(false);
fixture.detectChanges();
const wrapper = fixture.nativeElement.querySelector('.layout-wrapper') as HTMLDivElement;
const sidebar = fixture.nativeElement.querySelector('.layout-sidebar') as HTMLElement;
expect(wrapper.classList.contains('layout-sidebar-hidden')).toBe(true);
expect(sidebar.getAttribute('aria-hidden')).toBe('true');
expect(sidebar.hasAttribute('inert')).toBe(true);
});
it('keeps the mobile drawer reachable when the desktop sidebar preference is hidden', () => {
layoutService.isDesktop.set(false);
layoutService.sidebarVisible.set(false);
layoutService.mobileDrawerOpen.set(true);
fixture.detectChanges();
const wrapper = fixture.nativeElement.querySelector('.layout-wrapper') as HTMLDivElement;
const sidebar = fixture.nativeElement.querySelector('.layout-sidebar') as HTMLElement;
expect(wrapper.classList.contains('layout-sidebar-hidden')).toBe(false);
expect(sidebar.getAttribute('aria-hidden')).toBeNull();
expect(sidebar.hasAttribute('inert')).toBe(false);
});
it('cleans up an active sidebar resize when the component is destroyed', () => {
const component = fixture.componentInstance;
layoutService.sidebarCollapsed.set(false);
layoutService.isDesktop.set(true);
component.startResize(new MouseEvent('mousedown', { clientX: 200 }));
expect(document.body.classList.contains('layout-resizing-cursor')).toBe(true);
fixture.destroy();
document.dispatchEvent(new MouseEvent('mousemove', { clientX: 260 }));
expect(document.body.classList.contains('layout-resizing-cursor')).toBe(false);
expect(layoutService.sidebarWidth()).toBe(225);
});
it('supports keyboard resizing for the desktop sidebar handle', () => {
layoutService.sidebarCollapsed.set(false);
layoutService.isDesktop.set(true);
layoutService.sidebarWidth.set(225);
fixture.detectChanges();
const handle = fixture.nativeElement.querySelector('.layout-sidebar-resize-handle') as HTMLDivElement;
handle.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowRight' }));
fixture.detectChanges();
expect(layoutService.sidebarWidth()).toBe(241);
expect(localStorageService.set).not.toHaveBeenCalledWith('sidebarWidth', 241);
handle.dispatchEvent(new KeyboardEvent('keyup', { key: 'ArrowRight' }));
fixture.detectChanges();
expect(localStorageService.set).toHaveBeenCalledWith('sidebarWidth', 241);
expect(handle.getAttribute('role')).toBe('slider');
expect(handle.getAttribute('tabindex')).toBe('0');
});
it('uses the collapsed rail width while preserving the stored expanded width', () => {
layoutService.sidebarWidth.set(225);
layoutService.sidebarCollapsed.set(true);
layoutService.isDesktop.set(true);
fixture.detectChanges();
const wrapper = fixture.nativeElement.querySelector('.layout-wrapper') as HTMLDivElement;
expect(document.documentElement.style.getPropertyValue('--sidebar-width')).toBe('var(--sidebar-collapsed-width)');
expect(wrapper.style.getPropertyValue('--sidebar-stored-width')).toBe('225px');
});
});
@@ -1,47 +1,77 @@
import { DOCUMENT, NgClass } from '@angular/common';
import { computed, Component, DestroyRef, effect, inject, OnInit } from '@angular/core';
import { computed, Component, DestroyRef, effect, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { NavigationEnd, Router, RouterOutlet } from '@angular/router';
import { filter } from 'rxjs';
import { LayoutService } from '../layout.service';
import { CdkTrapFocus } from '@angular/cdk/a11y';
import { LayoutService, SIDEBAR_MAX_WIDTH, SIDEBAR_MIN_WIDTH } from '../layout.service';
import { AppMenuComponent } from '../layout-menu/app.menu.component';
import { AppTopBarComponent } from '../layout-topbar/app.topbar.component';
import { AppMobileTopbarComponent } from '../layout-mobile-topbar/app.mobile-topbar.component';
import { TranslocoDirective } from '@jsverse/transloco';
import { LocalStorageService } from '../../service/local-storage.service';
const SIDEBAR_COLLAPSED_WIDTH = 'var(--sidebar-collapsed-width)';
const SIDEBAR_KEYBOARD_STEP = 16;
const SIDEBAR_KEYBOARD_PAGE_STEP = 48;
@Component({
selector: 'app-layout',
imports: [
RouterOutlet,
AppMenuComponent,
AppTopBarComponent,
AppMobileTopbarComponent,
CdkTrapFocus,
NgClass,
TranslocoDirective
],
templateUrl: './app.layout.component.html'
})
export class AppLayoutComponent implements OnInit {
export class AppLayoutComponent {
readonly layoutService = inject(LayoutService);
readonly sidebarMinWidth = SIDEBAR_MIN_WIDTH;
readonly sidebarMaxWidth = SIDEBAR_MAX_WIDTH;
private readonly router = inject(Router);
private readonly localStorageService = inject(LocalStorageService);
private readonly document = inject(DOCUMENT);
private readonly destroyRef = inject(DestroyRef);
private resizeStartX = 0;
private resizeStartWidth = 0;
private isResizing = false;
private keyboardResizing = false;
readonly containerClass = computed(() => ({
'layout-static': true,
'layout-static-inactive': !this.layoutService.sidebarOpen(),
'layout-mobile-active': this.layoutService.mobileSidebarOpen()
'layout-sidebar-hidden': this.sidebarHidden(),
'layout-mobile-active': this.layoutService.mobileDrawerOpen(),
'layout-collapsed': this.layoutService.sidebarCollapsed() && this.layoutService.isDesktop()
}));
readonly sidebarHidden = computed(() => this.layoutService.isDesktop() && !this.layoutService.sidebarVisible());
readonly storedSidebarWidth = computed(() => `${this.layoutService.sidebarWidth()}px`);
constructor() {
this.destroyRef.onDestroy(() => {
if (this.keyboardResizing) {
this.layoutService.setSidebarWidth(this.layoutService.sidebarWidth(), true);
}
this.cleanupResize(false);
});
effect((onCleanup) => {
const body = this.document.body;
body.classList.toggle('blocked-scroll', this.layoutService.mobileSidebarOpen());
body.classList.toggle('blocked-scroll', this.layoutService.mobileDrawerOpen());
onCleanup(() => {
body.classList.remove('blocked-scroll');
});
});
effect(() => {
const collapsed = this.layoutService.sidebarCollapsed();
const isDesktop = this.layoutService.isDesktop();
const storedWidth = this.layoutService.sidebarWidth();
const width = (collapsed && isDesktop) ? SIDEBAR_COLLAPSED_WIDTH : `${storedWidth}px`;
this.document.documentElement.style.setProperty('--sidebar-width', width);
});
this.router.events
.pipe(
filter((event): event is NavigationEnd => event instanceof NavigationEnd),
@@ -52,12 +82,86 @@ export class AppLayoutComponent implements OnInit {
});
}
ngOnInit(): void {
const width = this.localStorageService.get<number>('sidebarWidth') ?? 225;
this.document.documentElement.style.setProperty('--sidebar-width', `${width}px`);
}
closeMobileSidebar(): void {
this.layoutService.closeMobileSidebar();
}
startResize(event: MouseEvent): void {
if (this.layoutService.sidebarCollapsed() || !this.layoutService.isDesktop()) {
return;
}
event.preventDefault();
this.isResizing = true;
this.resizeStartX = event.clientX;
this.resizeStartWidth = this.layoutService.sidebarWidth();
this.document.body.classList.add('layout-resizing-cursor');
this.document.addEventListener('mousemove', this.onResizeMove);
this.document.addEventListener('mouseup', this.onResizeEnd);
}
onResizeKeydown(event: KeyboardEvent): void {
if (this.layoutService.sidebarCollapsed() || !this.layoutService.isDesktop()) {
return;
}
const nextWidth = this.getKeyboardResizeWidth(event.key, this.layoutService.sidebarWidth());
if (nextWidth === null) return;
event.preventDefault();
this.keyboardResizing = true;
this.layoutService.setSidebarWidth(nextWidth, false);
}
onResizeKeyup(event: KeyboardEvent): void {
if (!this.layoutService.isDesktop()) return;
if (!this.isResizeKey(event.key)) return;
this.layoutService.setSidebarWidth(this.layoutService.sidebarWidth(), true);
this.keyboardResizing = false;
}
private readonly onResizeMove = (event: MouseEvent) => {
if (!this.isResizing) return;
const dx = event.clientX - this.resizeStartX;
this.layoutService.setSidebarWidth(this.resizeStartWidth + dx, false);
};
private readonly onResizeEnd = () => {
this.cleanupResize(true);
};
private isResizeKey(key: string): boolean {
return this.getKeyboardResizeWidth(key, 0) !== null;
}
private getKeyboardResizeWidth(key: string, currentWidth: number): number | null {
switch (key) {
case 'ArrowLeft':
case 'ArrowDown':
return currentWidth - SIDEBAR_KEYBOARD_STEP;
case 'ArrowRight':
case 'ArrowUp':
return currentWidth + SIDEBAR_KEYBOARD_STEP;
case 'PageDown':
return currentWidth - SIDEBAR_KEYBOARD_PAGE_STEP;
case 'PageUp':
return currentWidth + SIDEBAR_KEYBOARD_PAGE_STEP;
case 'Home':
return SIDEBAR_MIN_WIDTH;
case 'End':
return SIDEBAR_MAX_WIDTH;
default:
return null;
}
}
private cleanupResize(persistWidth: boolean): void {
if (!this.isResizing) return;
this.isResizing = false;
if (persistWidth) {
this.layoutService.setSidebarWidth(this.layoutService.sidebarWidth(), true);
}
this.document.body.classList.remove('layout-resizing-cursor');
this.document.removeEventListener('mousemove', this.onResizeMove);
this.document.removeEventListener('mouseup', this.onResizeEnd);
}
}
@@ -0,0 +1,82 @@
<div
class="menu-item-container"
[class.active-route-container]="isRouteActive()"
[class.menu-open]="menuOpen()"
>
@let currentItem = item();
@if (currentItem.action) {
<button
type="button"
class="menu-item-link"
[pTooltip]="currentItem.label"
[tooltipDisabled]="!layoutService.sidebarCollapsed()"
tooltipPosition="right"
(click)="runAction($event)"
>
<span class="menu-item-chrome">
<span class="menu-item-leading">
<app-icon-display
[icon]="getIconSelection()"
iconClass="layout-menuitem-icon"
size="18px"
[displayEmpty]="true"
></app-icon-display>
</span>
<span class="layout-menuitem-text menu-item-text">{{ currentItem.label }}</span>
</span>
</button>
} @else if (currentItem.routerLink) {
<a
class="menu-item-link"
[class.active-route]="isRouteActive()"
[attr.aria-current]="isRouteActive() ? 'page' : null"
[routerLink]="currentItem.routerLink"
[pTooltip]="currentItem.label"
[tooltipDisabled]="!layoutService.sidebarCollapsed()"
tooltipPosition="right"
tabindex="0"
>
<span class="menu-item-chrome">
<span class="menu-item-leading">
@if (currentItem.unhealthy) {
<span
class="library-health-dot"
role="img"
[attr.aria-label]="'common.libraryPathInaccessible' | transloco"
[pTooltip]="'common.libraryPathInaccessible' | transloco"
tooltipPosition="right"
></span>
}
<app-icon-display
[icon]="getIconSelection()"
iconClass="layout-menuitem-icon"
size="18px"
[displayEmpty]="true"
></app-icon-display>
</span>
<span class="layout-menuitem-text menu-item-text">{{ currentItem.label }}</span>
</span>
</a>
}
<span class="menu-item-end-content">
@if (shouldShowContextMenuButton()) {
<button
type="button"
class="entity-menu-button"
[attr.aria-label]="'common.moreActionsFor' | transloco: { label: currentItem.label }"
aria-haspopup="menu"
(click)="openContextMenu($event, entitymenu)"
>
<span class="entity-menu-button-content">
<i class="pi pi-ellipsis-v entity-menu-icon" aria-hidden="true"></i>
<span class="entity-menu-count">{{ formatCount(currentItem.bookCount) }}</span>
</span>
</button>
<p-menu #entitymenu [model]="currentItem.contextMenuItems" [popup]="true" appendTo="body" (onHide)="closeContextMenu()"></p-menu>
} @else if (currentItem.bookCount) {
<p class="book-count">{{ formatCount(currentItem.bookCount) }}</p>
}
</span>
</div>
@@ -0,0 +1,200 @@
:host {
display: block;
width: 100%;
list-style: none;
}
.menu-item-container {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
align-items: center;
box-sizing: border-box;
width: 100%;
height: var(--sidebar-row-min-height);
min-height: var(--sidebar-row-min-height);
min-width: 0;
border-radius: var(--sidebar-row-radius);
&:hover,
&:focus-within {
background-color: var(--surface-hover);
}
}
.menu-item-container.active-route-container {
background-color: color-mix(in srgb, var(--primary-color) 8%, transparent);
}
.menu-item-link {
display: flex;
align-items: center;
box-sizing: border-box;
width: 100%;
height: var(--sidebar-row-min-height);
min-height: var(--sidebar-row-min-height);
min-width: 0;
background-color: transparent;
}
button.menu-item-link,
a.menu-item-link {
padding: 0;
border: 0;
background: transparent;
color: inherit;
font: inherit;
text-align: left;
text-decoration: none;
white-space: nowrap;
cursor: pointer;
&:focus-visible {
outline: none;
}
}
.menu-item-link:focus-visible .menu-item-chrome {
background-color: var(--surface-hover);
box-shadow: var(--sidebar-focus-ring);
border-radius: var(--sidebar-row-radius);
}
a.menu-item-link.active-route {
color: var(--primary-color);
}
.menu-item-chrome {
display: flex;
align-items: center;
box-sizing: border-box;
gap: var(--sidebar-row-gap);
width: 100%;
min-width: 0;
min-height: var(--sidebar-row-min-height);
padding: var(--sidebar-row-padding-block) var(--sidebar-row-padding-inline-end) var(--sidebar-row-padding-block) var(--sidebar-row-padding-inline-start);
transition: padding var(--transition-base), width var(--transition-base);
}
.menu-item-chevron {
font-size: var(--text-sm);
color: var(--text-color-secondary);
padding-right: var(--space-3);
transition: color var(--transition-fast);
}
.menu-item-container:hover .menu-item-chevron {
color: var(--text-color);
}
.menu-item-text {
flex: 1 1 auto;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: var(--text-base);
}
.menu-item-leading {
position: relative;
display: inline-flex;
align-items: center;
justify-content: center;
flex: 0 0 var(--sidebar-row-icon-size);
width: var(--sidebar-row-icon-size);
min-width: var(--sidebar-row-icon-size);
height: var(--sidebar-row-icon-size);
}
.menu-item-leading > app-icon-display {
display: inline-flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
overflow: hidden;
}
.menu-item-end-content {
display: flex;
align-items: center;
flex-shrink: 0;
}
.entity-menu-button {
display: flex;
align-items: center;
justify-content: center;
min-width: 2rem;
height: 1.875rem;
padding: 0 var(--space-2);
border: 0;
border-radius: var(--radius-pill);
background: transparent;
color: var(--text-color-secondary);
cursor: pointer;
font: inherit;
font-size: var(--text-sm);
transition: color var(--transition-base);
}
.entity-menu-button:hover {
background-color: transparent;
color: var(--primary-color);
}
.entity-menu-button:focus-visible {
background-color: var(--surface-hover);
box-shadow: var(--sidebar-focus-ring);
outline: none;
}
.entity-menu-button-content {
display: flex;
align-items: center;
justify-content: center;
}
.entity-menu-icon {
display: none;
}
.menu-item-container:hover .entity-menu-icon,
.menu-item-container.menu-open .entity-menu-icon {
display: inline;
}
.menu-item-container:hover .entity-menu-count,
.menu-item-container.menu-open .entity-menu-count {
display: none;
}
.book-count {
color: var(--text-color-secondary);
padding-right: var(--space-3);
font-size: var(--text-sm);
}
.library-health-dot {
position: absolute;
top: -1px;
left: -1px;
display: inline-block;
width: 10px;
height: 10px;
border-radius: 50%;
background-color: #ef4444;
animation: pulse 2s ease-in-out infinite;
}
@keyframes pulse {
0%, 100% {
opacity: 1;
box-shadow: 0 0 0 0 rgb(239 68 68 / 70%);
}
50% {
opacity: 0.85;
box-shadow: 0 0 0 5px rgb(239 68 68 / 0%);
}
}
@@ -1,39 +1,24 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { signal } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { AppMenuitemComponent } from './app.menuitem.component';
import { MenuService } from './app.menu.service';
import { DialogLauncherService } from '../../services/dialog-launcher.service';
import { BookDialogHelperService } from '../../../features/book/components/book-browser/book-dialog-helper.service';
import { AppMenuItemRowComponent } from './app.menu-item-row.component';
import { UserService } from '../../../features/settings/user-management/user.service';
import { LayoutService } from '../layout.service';
describe('AppMenuitemComponent', () => {
let fixture: ComponentFixture<AppMenuitemComponent>;
let component: AppMenuitemComponent;
describe('AppMenuItemRowComponent', () => {
let fixture: ComponentFixture<AppMenuItemRowComponent>;
let component: AppMenuItemRowComponent;
const menuService = {
const layoutService = {
sidebarCollapsed: signal(false),
currentPath: signal('/'),
};
beforeEach(() => {
TestBed.resetTestingModule();
TestBed.configureTestingModule({
imports: [AppMenuitemComponent],
imports: [AppMenuItemRowComponent],
providers: [
{ provide: MenuService, useValue: menuService },
{
provide: DialogLauncherService,
useValue: {
openLibraryCreateDialog: vi.fn(),
openMagicShelfCreateDialog: vi.fn(),
},
},
{
provide: BookDialogHelperService,
useValue: {
openShelfCreatorDialog: vi.fn(),
},
},
{
provide: UserService,
useValue: {
@@ -45,39 +30,41 @@ describe('AppMenuitemComponent', () => {
}),
},
},
{ provide: LayoutService, useValue: layoutService },
],
});
TestBed.overrideComponent(AppMenuitemComponent, {
set: {
template: '',
},
});
TestBed.overrideComponent(AppMenuItemRowComponent, { set: { template: '' } });
fixture = TestBed.createComponent(AppMenuitemComponent);
fixture = TestBed.createComponent(AppMenuItemRowComponent);
component = fixture.componentInstance;
component.index = 0;
fixture.componentRef.setInput('index', 0);
fixture.componentRef.setInput('parentKey', 'home-0');
layoutService.sidebarCollapsed.set(false);
});
function setItem(item: Parameters<ComponentFixture<AppMenuItemRowComponent>['componentRef']['setInput']>[1]): void {
fixture.componentRef.setInput('item', item);
}
it('passes context menu items through to the template', () => {
const editCommand = vi.fn();
const nestedCommand = vi.fn();
component.item = {
const item = {
id: 'shelf-a',
label: 'Shelf A',
type: 'shelf',
contextMenuItems: [
{ label: 'Edit', command: editCommand },
{
label: 'More',
items: [{ label: 'Delete', command: nestedCommand }],
},
{ label: 'More', items: [{ label: 'Delete', command: nestedCommand }] },
],
};
setItem(item);
fixture.detectChanges();
const items = component.item.contextMenuItems!;
const items = component.item().contextMenuItems!;
expect(items[0].label).toBe('Edit');
items[0].command?.({} as never);
expect(editCommand).toHaveBeenCalled();
@@ -88,45 +75,30 @@ describe('AppMenuitemComponent', () => {
});
it('hides the context menu button for items without context menu actions', () => {
component.item = {
label: 'Unshelved',
type: 'shelf',
};
setItem({ id: 'unshelved', label: 'Unshelved', type: 'shelf' });
fixture.detectChanges();
expect(component.shouldShowContextMenuButton()).toBe(false);
});
it('exposes admin and canManipulateLibrary as computed signals from UserService', () => {
component.item = { label: 'Test' };
setItem({ id: 'test', label: 'Test' });
fixture.detectChanges();
expect(component.admin()).toBe(true);
expect(component.canManipulateLibrary()).toBe(true);
});
it('reports route as active when currentPath matches item routerLink', () => {
component.item = {
label: 'Dashboard',
routerLink: ['/dashboard'],
};
menuService.currentPath.set('/dashboard');
setItem({ id: 'dashboard', label: 'Dashboard', routerLink: ['/dashboard'] });
layoutService.currentPath.set('/dashboard');
fixture.detectChanges();
expect(component.isRouteActive()).toBe(true);
});
it('reports route as inactive when currentPath does not match', () => {
component.item = {
label: 'Dashboard',
routerLink: ['/dashboard'],
};
menuService.currentPath.set('/library/1/books');
setItem({ id: 'dashboard', label: 'Dashboard', routerLink: ['/dashboard'] });
layoutService.currentPath.set('/library/1/books');
fixture.detectChanges();
expect(component.isRouteActive()).toBe(false);
});
});
@@ -0,0 +1,92 @@
import { ChangeDetectionStrategy, Component, computed, inject, input, signal } from '@angular/core';
import { RouterLink } from '@angular/router';
import { Menu } from 'primeng/menu';
import { Tooltip } from 'primeng/tooltip';
import { TranslocoPipe } from '@jsverse/transloco';
import { UserService } from '../../../features/settings/user-management/user.service';
import { IconDisplayComponent } from '../../components/icon-display/icon-display.component';
import { IconSelection } from '../../service/icon-picker.service';
import { LayoutService } from '../layout.service';
import { SidebarLeaf } from '../navigation/nav-item.model';
@Component({
// Attribute selector so the row renders into its host <li> inside a <ul>.
// eslint-disable-next-line @angular-eslint/component-selector
selector: '[app-menu-item-row]',
templateUrl: './app.menu-item-row.component.html',
styleUrls: ['./app.menu-item-row.component.scss'],
imports: [
RouterLink,
Menu,
IconDisplayComponent,
Tooltip,
TranslocoPipe,
],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AppMenuItemRowComponent {
readonly item = input.required<SidebarLeaf>();
readonly index = input.required<number>();
readonly parentKey = input.required<string>();
readonly menuOpen = signal(false);
readonly key = computed(() => `${this.parentKey()}-${this.index()}`);
private readonly userService = inject(UserService);
readonly layoutService = inject(LayoutService);
readonly isRouteActive = computed(() => {
const route = this.item().routerLink?.[0];
if (!route) return false;
return this.layoutService.currentPath() === route;
});
readonly canManipulateLibrary = computed(() =>
this.userService.currentUser()?.permissions.canManageLibrary ?? false
);
readonly admin = computed(() =>
this.userService.currentUser()?.permissions.admin ?? false
);
runAction(event: Event): void {
event.preventDefault();
this.item().action?.();
}
openContextMenu(event: Event, menu: Menu): void {
menu.toggle(event);
this.menuOpen.update((open) => !open);
event.stopPropagation();
}
closeContextMenu(): void {
this.menuOpen.set(false);
}
getIconSelection(): IconSelection | null {
const item = this.item();
if (!item.icon) return null;
return {
type: item.iconType || 'PRIME_NG',
value: item.icon,
};
}
hasContextMenu(): boolean {
return (this.item().contextMenuItems?.length ?? 0) > 0;
}
shouldShowContextMenuButton(): boolean {
const item = this.item();
return this.hasContextMenu()
&& (item.type !== 'library' || (this.admin() || this.canManipulateLibrary()));
}
formatCount(count: number | null | undefined): string {
if (!count) return '';
if (count >= 1000) return Math.floor(count / 100) / 10 + 'K';
return count.toString();
}
}
@@ -0,0 +1,45 @@
@let currentItem = item();
@if (isExpandable) {
<button
type="button"
class="layout-menuitem-root-text root-item-with-dropdown"
[attr.aria-label]="currentItem.label"
[attr.aria-expanded]="expanded"
(click)="toggleExpand()"
>
<span class="root-item-label-container">
<span>{{ currentItem.label }}</span>
</span>
<span class="expand-icon-button" aria-hidden="true">
<i
[ngClass]="{ 'pi': true, 'pi-angle-up': expanded, 'pi-angle-down': !expanded }"
class="expand-icon"
aria-hidden="true"
></i>
</span>
</button>
<div class="sidebar-section-divider" aria-hidden="true"></div>
} @else {
<div class="layout-menuitem-root-text root-item">
<div>{{ currentItem.label }}</div>
</div>
}
<div
class="submenu-container"
[class.expanded]="submenuVisible"
[attr.aria-hidden]="!submenuVisible"
[attr.inert]="submenuVisible ? null : ''"
>
<ul>
@for (child of visibleChildren(); track child.id; let i = $index) {
<li
app-menu-item-row
[item]="child"
[index]="i"
[parentKey]="key()"
></li>
}
</ul>
</div>
@@ -0,0 +1,108 @@
:host {
display: block;
list-style: none;
}
.expand-icon-button {
display: inline-flex;
align-items: center;
justify-content: center;
padding: 0;
flex-shrink: 0;
opacity: 1;
}
.root-item-with-dropdown {
display: flex;
align-items: center;
justify-content: space-between;
box-sizing: border-box;
width: 100%;
height: var(--sidebar-section-min-height);
min-height: var(--sidebar-section-min-height);
padding: 0 var(--sidebar-section-inline-end) 0 var(--sidebar-section-inline-start);
border: 0;
background: none;
cursor: pointer;
text-align: left;
font: inherit;
color: inherit;
&:focus-visible {
background-color: var(--surface-hover);
box-shadow: var(--sidebar-focus-ring);
outline: none;
}
}
.root-item-label-container {
display: flex;
align-items: center;
justify-content: space-between;
flex: 1 1 auto;
min-width: 0;
gap: var(--sidebar-row-gap);
> span {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
}
.expand-icon {
color: var(--surface-500);
&:hover {
color: var(--surface-200);
}
}
.root-item {
display: flex;
align-items: center;
justify-content: space-between;
box-sizing: border-box;
height: var(--sidebar-section-min-height);
min-height: var(--sidebar-section-min-height);
min-width: 0;
> div {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
}
.submenu-container {
display: grid;
grid-template-rows: 0fr;
transition: grid-template-rows 400ms cubic-bezier(0.86, 0, 0.07, 1);
overflow: hidden;
@media (prefers-reduced-motion: reduce) {
transition: none;
}
> * {
overflow: hidden;
}
&.expanded {
grid-template-rows: 1fr;
}
}
@media (width <= 991px) {
.expand-icon-button {
opacity: 1;
width: 2rem;
height: 2rem;
margin-right: -0.25rem;
}
.expand-icon {
font-size: 1.125rem;
color: var(--text-color-secondary);
}
}
@@ -0,0 +1,90 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { signal } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { AppMenuSectionComponent } from './app.menu-section.component';
import { LayoutService } from '../layout.service';
describe('AppMenuSectionComponent', () => {
let fixture: ComponentFixture<AppMenuSectionComponent>;
let component: AppMenuSectionComponent;
const layoutService = {
sidebarCollapsed: signal(false),
sidebarExpandedState: signal<Readonly<Record<string, boolean>>>({}),
isSidebarExpanded: vi.fn((key: string, defaultExpanded: boolean) => {
const value = layoutService.sidebarExpandedState()[key];
return value === undefined ? defaultExpanded : value;
}),
setSidebarExpanded: vi.fn((key: string, expanded: boolean) => {
layoutService.sidebarExpandedState.set({
...layoutService.sidebarExpandedState(),
[key]: expanded,
});
}),
};
beforeEach(() => {
TestBed.resetTestingModule();
TestBed.configureTestingModule({
imports: [AppMenuSectionComponent],
providers: [{ provide: LayoutService, useValue: layoutService }],
});
TestBed.overrideComponent(AppMenuSectionComponent, { set: { template: '' } });
fixture = TestBed.createComponent(AppMenuSectionComponent);
component = fixture.componentInstance;
layoutService.sidebarExpandedState.set({});
layoutService.isSidebarExpanded.mockClear();
layoutService.setSidebarExpanded.mockClear();
});
it('treats expandable sections as default-expanded', () => {
fixture.componentRef.setInput('item', {
id: 'libraries',
menuKey: 'library',
label: 'Libraries',
expandable: true,
items: [{ id: 'library-1', label: 'Library A', routerLink: ['/library/1/books'] }],
});
fixture.detectChanges();
expect(component.isExpandable).toBe(true);
expect(component.expanded).toBe(true);
});
it('persists expanded state through LayoutService when toggled', () => {
fixture.componentRef.setInput('item', {
id: 'libraries',
menuKey: 'library',
label: 'Libraries',
expandable: true,
items: [{ id: 'library-1', label: 'Library A' }],
});
fixture.detectChanges();
component.toggleExpand();
expect(layoutService.setSidebarExpanded).toHaveBeenCalledWith('library', false);
});
it('keeps children available while the sidebar is collapsed even if the saved section state is closed', () => {
fixture.componentRef.setInput('item', {
id: 'libraries',
menuKey: 'library',
label: 'Libraries',
expandable: true,
items: [{ id: 'library-1', label: 'Library A', routerLink: ['/library/1/books'] }],
});
layoutService.sidebarExpandedState.set({ 'library': false });
layoutService.sidebarCollapsed.set(true);
fixture.detectChanges();
expect(component.expanded).toBe(false);
expect(component.submenuVisible).toBe(true);
});
});
@@ -0,0 +1,50 @@
import { ChangeDetectionStrategy, Component, HostBinding, computed, inject, input } from '@angular/core';
import { NgClass } from '@angular/common';
import { LayoutService } from '../layout.service';
import { AppMenuItemRowComponent } from './app.menu-item-row.component';
import { SidebarLeaf, SidebarSection } from '../navigation/nav-item.model';
@Component({
// Attribute selector so the section renders into its host <li> inside a <ul>.
// eslint-disable-next-line @angular-eslint/component-selector
selector: '[app-menu-section]',
templateUrl: './app.menu-section.component.html',
styleUrls: ['./app.menu-section.component.scss'],
imports: [NgClass, AppMenuItemRowComponent],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AppMenuSectionComponent {
readonly item = input.required<SidebarSection>();
// Applied on the <li> host so global styles in assets/layout/styles/layout/_menu.scss
// (e.g. `.layout-root-menuitem > .layout-menuitem-root-text`) target section headings.
@HostBinding('class.layout-root-menuitem') readonly isRoot = true;
readonly key = computed(() => this.item().menuKey);
readonly layoutService = inject(LayoutService);
get isExpandable(): boolean {
const item = this.item();
return !!item.expandable && item.items.length > 0;
}
get expanded(): boolean {
if (!this.isExpandable) return true;
return this.layoutService.isSidebarExpanded(this.key(), true);
}
get submenuVisible(): boolean {
return this.layoutService.sidebarCollapsed() || this.expanded;
}
toggleExpand(): void {
if (!this.isExpandable) return;
this.layoutService.setSidebarExpanded(this.key(), !this.expanded);
}
visibleChildren(): SidebarLeaf[] {
return this.item().items;
}
}
@@ -1,94 +1,213 @@
<ng-container *transloco="let t; prefix: 'layout.menu'">
<div class="menu-container">
<div>
<div class="home-menu-section">
<ul class="layout-menu">
@if (homeMenu(); as homeMenu) {
@for (item of homeMenu; track item.label; let i = $index) {
<li app-menuitem [item]="item" [index]="i" [root]="true" menuKey="home"></li>
}
}
</ul>
<button
type="button"
class="sidebar-width-btn pi pi-objects-column"
[attr.aria-label]="t('adjustSidebarWidth')"
(click)="widthPanel.toggle($event)"
></button>
<p-popover #widthPanel appendTo="body">
<div class="sidebar-width-popover">
<span class="sidebar-width-popover-label">{{ sidebarWidth }}px</span>
<p-slider
[(ngModel)]="sidebarWidth"
[min]="175"
[max]="400"
[step]="1"
(onChange)="onSidebarWidthChange()"
(onSlideEnd)="saveSidebarWidth()">
</p-slider>
</div>
</p-popover>
</div>
<div class="sidebar-header">
<a class="sidebar-brand" [routerLink]="['/dashboard']" [attr.aria-label]="t('goToDashboard')">
<span class="sidebar-brand-mark" aria-hidden="true">
<svg class="sidebar-brand-icon" viewBox="0 0 100 126" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M25.8062 106.614V113.077V119.537V126L32.2559 119.537L38.7093 126V119.537V113.077V106.614H25.8062Z" fill="white"/>
<path d="M38.7093 29.0758H96.7715C98.5535 29.0758 99.9964 27.6307 99.9964 25.846V3.22984C99.9964 1.44512 98.5535 0 96.7715 0H12.9031C10.5512 0 8.35077 0.63224 6.44975 1.73414C4.49102 2.86856 2.86054 4.50155 1.72787 6.4633C0.631268 8.36363 0 10.5674 0 12.923V106.614C0 113.753 5.7752 119.537 12.9031 119.537H21.1529V113.077H12.9031C9.33915 113.077 6.44975 110.183 6.44975 106.614C6.44975 103.044 9.33915 100.15 12.9031 100.15H93.5466C97.1106 100.15 100 97.2566 100 93.6871V41.9988C100 38.4293 97.1106 35.5355 93.5466 35.5355H38.7093C36.9273 35.5355 35.4845 36.9806 35.4845 38.7653V61.3815C35.4845 63.1662 36.9273 64.6113 38.7093 64.6113H67.7404C69.5224 64.6113 70.9653 66.0564 70.9653 67.8412C70.9653 69.6259 69.5224 71.071 67.7404 71.071H38.7093C33.3634 71.071 29.0311 66.732 29.0311 61.3779V38.7617C29.0311 33.4076 33.3634 29.0686 38.7093 29.0686V29.0758Z" fill="url(#sidebar-brand-primary-gradient)"/>
<path d="M96.7715 113.077H43.5539V119.537H96.7715C98.5535 119.537 99.9964 118.092 99.9964 116.307C99.9964 114.522 98.5535 113.077 96.7715 113.077Z" fill="url(#sidebar-brand-secondary-gradient)"/>
<defs>
<linearGradient id="sidebar-brand-primary-gradient" x1="50" y1="0" x2="50" y2="119.537" gradientUnits="userSpaceOnUse">
<stop offset="0" style="stop-color: var(--primary-300)"/>
<stop offset="1" style="stop-color: var(--primary-500)"/>
</linearGradient>
<linearGradient id="sidebar-brand-secondary-gradient" x1="50" y1="0" x2="50" y2="119.537" gradientUnits="userSpaceOnUse">
<stop offset="0" style="stop-color: var(--primary-300)"/>
<stop offset="1" style="stop-color: var(--primary-500)"/>
</linearGradient>
</defs>
</svg>
</span>
<svg class="sidebar-brand-wordmark" width="2500" height="350" viewBox="0 0 2500 350" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
<g clip-path="url(#sidebar-brand-wordmark-clip)">
<path d="M71.8311 296.149V314.103V332.047V350L89.7839 332.047L107.747 350V332.047V314.103V296.149H71.8311Z" fill="white"/>
<path d="M1748.64 102.654H1701.96C1691.71 102.654 1683.37 110.983 1683.37 121.23V165.376C1683.37 175.622 1691.7 183.952 1701.96 183.952H1748.64C1757.49 183.952 1764.7 176.746 1764.7 167.895V118.721C1764.7 109.869 1757.49 102.664 1748.64 102.664V102.654Z" style="fill: var(--primary-400)"/>
<path d="M896.673 102.654H852.504C842.263 102.654 833.919 110.983 833.919 121.23V167.885C833.919 176.736 841.128 183.942 849.984 183.942H899.184C908.039 183.942 915.249 176.736 915.249 167.885V121.23C915.249 110.983 906.915 102.654 896.663 102.654H896.673Z" style="fill: var(--primary-400)"/>
<path d="M653.709 183.942H697.878C708.119 183.942 716.463 175.612 716.463 165.366V118.711C716.463 109.859 709.254 102.654 700.398 102.654H651.199C642.343 102.654 635.134 109.859 635.134 118.711V165.366C635.134 175.612 643.467 183.942 653.719 183.942H653.709Z" style="fill: var(--primary-400)"/>
<path d="M107.747 80.7661H269.361C274.322 80.7661 278.338 76.7519 278.338 71.7944V8.97179C278.338 4.01422 274.322 0 269.361 0H35.9155C29.369 0 23.2442 1.75622 17.9527 4.81707C12.5007 7.96823 7.96226 12.5043 4.80949 17.9536C1.75712 23.2323 0 29.354 0 35.8972V296.149C0 315.979 16.0751 332.046 35.9155 332.046H58.8786V314.103H35.9155C25.9953 314.103 17.9527 306.064 17.9527 296.149C17.9527 286.234 25.9953 278.196 35.9155 278.196H260.385C270.305 278.196 278.348 270.157 278.348 260.242V116.663C278.348 106.748 270.305 98.7097 260.385 98.7097H107.747C102.786 98.7097 98.7702 102.724 98.7702 107.681V170.504C98.7702 175.462 102.786 179.476 107.747 179.476H188.554C193.514 179.476 197.53 183.49 197.53 188.448C197.53 193.405 193.514 197.419 188.554 197.419H107.747C92.8663 197.419 80.8074 185.367 80.8074 170.494V107.671C80.8074 92.7988 92.8663 80.7461 107.747 80.7461V80.7661Z" fill="url(#sidebar-brand-wordmark-gradient)"/>
<path d="M269.361 314.103H121.231V332.046H269.361C274.322 332.046 278.338 328.032 278.338 323.075C278.338 318.117 274.322 314.103 269.361 314.103Z" fill="url(#sidebar-brand-wordmark-gradient)"/>
<path d="M1620.14 3.3017C1600.16 3.3017 1583.98 19.489 1583.98 39.4498V248.099C1583.98 267.538 1599.74 283.294 1619.19 283.294H1847.17C1856.53 283.294 1864.11 275.717 1864.11 266.364V19.6898C1864.11 10.6377 1856.77 3.3017 1847.72 3.3017H1620.14ZM1782.77 167.885C1782.77 186.701 1767.46 202.006 1748.64 202.006H1701.96C1681.74 202.006 1665.3 185.567 1665.3 165.366V121.219C1665.3 101.018 1681.74 84.5796 1701.96 84.5796H1748.64C1767.46 84.5796 1782.77 99.8839 1782.77 118.701V167.885Z" fill="url(#sidebar-brand-wordmark-gradient)"/>
<path d="M849.994 202.006C831.168 202.006 815.856 186.701 815.856 167.885V121.229C815.856 101.028 832.302 84.5897 852.514 84.5897H896.683C897.527 84.5897 898.37 84.6298 899.204 84.69V84.5897C908.059 84.5897 915.269 77.3842 915.269 68.5328V19.6898C915.269 10.6377 907.929 3.3017 898.872 3.3017H671.31C651.329 3.3017 635.144 19.489 635.144 39.4498V68.5328C635.144 77.3842 642.353 84.5897 651.209 84.5897H700.408C719.234 84.5897 734.546 99.8939 734.546 118.711V165.366C734.546 185.567 718.1 202.006 697.888 202.006H653.719C652.875 202.006 652.032 201.966 651.199 201.905V202.006C642.343 202.006 635.134 209.211 635.134 218.063V248.099C635.134 267.538 650.897 283.294 670.346 283.294H898.33C907.688 283.294 915.269 275.717 915.269 266.364V218.063C915.269 209.211 908.059 202.006 899.204 202.006H849.994Z" fill="url(#sidebar-brand-wordmark-gradient)"/>
<path d="M1215.14 3.3017H987.582C967.601 3.3017 951.415 19.489 951.415 39.4498V248.099C951.415 267.538 967.179 283.294 986.628 283.294H1016.52C1025.37 283.294 1032.58 276.088 1032.58 267.237V93.6217C1032.58 88.634 1036.63 84.5897 1041.62 84.5897C1046.61 84.5897 1050.66 88.634 1050.66 93.6217V267.417C1050.76 276.188 1057.92 283.294 1066.71 283.294H1116.07C1124.93 283.294 1132.14 276.088 1132.14 267.237V93.6217C1132.14 88.634 1136.18 84.5897 1141.17 84.5897C1146.16 84.5897 1150.21 88.634 1150.21 93.6217V267.237C1150.21 276.088 1157.41 283.294 1166.28 283.294H1214.6C1223.96 283.294 1231.54 275.717 1231.54 266.364V19.6898C1231.54 10.6377 1224.2 3.3017 1215.14 3.3017Z" fill="url(#sidebar-brand-wordmark-gradient)"/>
<path d="M1531.43 3.3017H1303.86C1283.88 3.3017 1267.7 19.489 1267.7 39.4498V248.099C1267.7 267.538 1283.46 283.294 1302.91 283.294H1332.8C1341.66 283.294 1348.87 276.088 1348.87 267.237V93.6217C1348.87 88.634 1352.91 84.5897 1357.9 84.5897C1362.89 84.5897 1366.94 88.634 1366.94 93.6217V267.417C1367.04 276.188 1374.2 283.294 1382.99 283.294H1432.35C1441.21 283.294 1448.42 276.088 1448.42 267.237V93.6217C1448.42 88.634 1452.47 84.5897 1457.46 84.5897C1462.45 84.5897 1466.49 88.634 1466.49 93.6217V267.237C1466.49 276.088 1473.69 283.294 1482.56 283.294H1530.88C1540.24 283.294 1547.82 275.717 1547.82 266.364V19.6898C1547.82 10.6377 1540.48 3.3017 1531.43 3.3017Z" fill="url(#sidebar-brand-wordmark-gradient)"/>
<path d="M2090.02 202.006C2085.03 202.006 2080.98 197.961 2080.98 192.974C2080.98 187.986 2085.03 183.942 2090.02 183.942H2164.32C2173.18 183.942 2180.38 176.736 2180.38 167.885V19.6898C2180.38 10.6377 2173.05 3.3017 2163.99 3.3017H1936.43C1916.45 3.3017 1900.26 19.489 1900.26 39.4498V248.099C1900.26 267.538 1916.02 283.294 1935.47 283.294H1965.52C1974.38 283.294 1981.59 276.088 1981.59 267.237V247.216C1981.59 247.216 1981.59 247.186 1981.59 247.166V192.974C1981.59 187.986 1985.64 183.942 1990.63 183.942C1995.62 183.942 1999.66 187.986 1999.66 192.974V247.216C1999.68 267.116 2015.89 283.294 2035.81 283.294H2163.46C2172.81 283.294 2180.4 275.717 2180.4 266.364V218.063C2180.4 209.211 2173.19 202.006 2164.33 202.006H2090.02ZM1990.62 102.684C1985.63 102.684 1981.58 98.6395 1981.58 93.6518C1981.58 88.6641 1985.63 84.6198 1990.62 84.6198H2090.02C2095.01 84.6198 2099.06 88.6641 2099.06 93.6518C2099.06 98.6395 2095.01 102.684 2090.02 102.684H1990.62Z" fill="url(#sidebar-brand-wordmark-gradient)"/>
<path d="M508.611 202.006C503.621 202.006 499.574 197.961 499.574 192.974C499.574 187.986 503.621 183.942 508.611 183.942H582.912C591.768 183.942 598.977 176.736 598.977 167.885V19.6898C598.977 10.6377 591.637 3.3017 582.581 3.3017H355.019C335.038 3.3017 318.852 19.489 318.852 39.4498V248.099C318.852 267.538 334.616 283.294 354.065 283.294H384.116C392.972 283.294 400.182 276.088 400.182 267.237V247.216C400.182 247.216 400.182 247.186 400.182 247.166V192.974C400.182 187.986 404.228 183.942 409.218 183.942C414.208 183.942 418.255 187.986 418.255 192.974V247.216C418.275 267.116 434.481 283.294 454.401 283.294H582.048C591.406 283.294 598.987 275.717 598.987 266.364V218.063C598.987 209.211 591.778 202.006 582.922 202.006H508.611ZM409.208 102.684C404.218 102.684 400.171 98.6395 400.171 93.6518C400.171 88.6641 404.218 84.6198 409.208 84.6198H508.611C513.601 84.6198 517.647 88.6641 517.647 93.6518C517.647 98.6395 513.601 102.684 508.611 102.684H409.208Z" fill="url(#sidebar-brand-wordmark-gradient)"/>
<path d="M2480.27 3.3017H2379.19C2370.33 3.3017 2363.13 10.5072 2363.13 19.3586V93.6217C2363.13 98.6094 2359.08 102.654 2354.09 102.654C2349.1 102.654 2345.05 98.6094 2345.05 93.6217V19.3586C2345.05 10.5072 2337.84 3.3017 2328.99 3.3017H2252.7C2232.72 3.3017 2216.53 19.489 2216.53 39.4498V147.814C2216.53 167.734 2232.75 183.942 2252.68 183.942H2406.3C2411.29 183.942 2415.34 187.986 2415.34 192.974C2415.34 197.961 2411.29 202.006 2406.3 202.006H2232.43C2223.65 202.096 2216.53 209.261 2216.53 218.053V248.089C2216.53 267.528 2232.3 283.284 2251.74 283.284H2479.73C2489.09 283.284 2496.67 275.707 2496.67 266.354V19.6898C2496.67 10.6377 2489.33 3.3017 2480.27 3.3017Z" fill="url(#sidebar-brand-wordmark-gradient)"/>
<path d="M2491.43 314.103H327.818C322.858 314.103 318.842 318.117 318.842 323.075C318.842 328.032 322.858 332.046 327.818 332.046H2491.43C2496.39 332.046 2500.4 328.032 2500.4 323.075C2500.4 318.117 2496.39 314.103 2491.43 314.103Z" fill="url(#sidebar-brand-wordmark-gradient)"/>
</g>
<defs>
<linearGradient id="sidebar-brand-wordmark-gradient" x1="1250.2" y1="0" x2="1250.2" y2="332.046" gradientUnits="userSpaceOnUse">
<stop offset="0" style="stop-color: var(--primary-300)"/>
<stop offset="1" style="stop-color: var(--primary-500)"/>
</linearGradient>
<clipPath id="sidebar-brand-wordmark-clip">
<rect width="2500" height="350" fill="white"/>
</clipPath>
</defs>
</svg>
</a>
<ul class="layout-menu">
@if (libraryMenu(); as libraryMenu) {
@for (item of libraryMenu; track item.label; let i = $index) {
<li app-menuitem [item]="item" [index]="i" [root]="true" menuKey="library"></li>
}
}
</ul>
<button
type="button"
class="sidebar-icon-button sidebar-mobile-close-button"
[attr.aria-label]="'layout.closeNavigation' | transloco"
(click)="closeMobileSidebar()"
>
<i class="pi pi-times" aria-hidden="true"></i>
</button>
</div>
<ul class="layout-menu">
@if (shelfMenu(); as shelfMenu) {
@for (item of shelfMenu; track item.label; let i = $index) {
<li app-menuitem [item]="item" [index]="i" [root]="true" menuKey="shelf"></li>
}
}
</ul>
<div class="sidebar-nav-top">
<button
type="button"
class="sidebar-action-link sidebar-search-button"
[pTooltip]="t('search')"
[tooltipDisabled]="!layoutService.sidebarCollapsed()"
tooltipPosition="right"
(click)="openSearch()"
>
<i class="pi pi-search" aria-hidden="true"></i>
<span>{{ t('search') }}</span>
<kbd class="sidebar-search-shortcut" aria-hidden="true">{{ searchShortcutLabel }}</kbd>
</button>
</div>
<div class="sidebar-nav">
<ul class="layout-menu">
@if (magicShelfMenu(); as magicShelfMenu) {
@for (item of magicShelfMenu; track item.label; let i = $index) {
<li app-menuitem [item]="item" [index]="i" [root]="true" menuKey="magicShelf"></li>
}
@for (section of sections(); track section.id) {
<li app-menu-section [item]="section"></li>
}
</ul>
</div>
@if (versionInfo(); as versionInfo) {
<div class="version-info" style="margin-top: auto;">
<div class="version-text">
@if (isSemanticVersion(versionInfo.current)) {
<a
[href]="getVersionUrl(versionInfo.current)"
target="_blank"
rel="noopener noreferrer"
class="version-link"
>
{{ versionInfo.current }}
</a>
} @else {
<button
type="button"
class="version-label version-copy-trigger"
(click)="copyVersion(versionInfo.current)"
>
{{ versionInfo.current }}
</button>
}
</div>
@if (isSemanticVersion(versionInfo.current) && versionInfo.latest && versionInfo.latest !== versionInfo.current) {
<div>
<button
type="button"
class="update-link"
(click)="openChangelogDialog()"
>
{{ t('update') }}
</button>
</div>
}
<div class="sidebar-footer">
<div class="sidebar-footer-actions">
<button
type="button"
class="sidebar-action-link sidebar-footer-action sidebar-toolbar-button"
[pTooltip]="t('add')"
tooltipPosition="top"
[attr.aria-label]="t('add')"
(click)="openSidebarOverlay($event, addMenu, 'above')"
>
<i class="pi pi-plus" aria-hidden="true"></i>
<span>{{ t('add') }}</span>
</button>
<button
type="button"
class="sidebar-action-link sidebar-footer-action"
[attr.aria-label]="t('notifications')"
[pTooltip]="t('notifications')"
tooltipPosition="top"
(click)="openSidebarOverlay($event, notificationsPopover, layoutService.isDesktop() ? 'below' : 'above')"
>
<i class="pi pi-bell" aria-hidden="true"></i>
<span>{{ t('notifications') }}</span>
</button>
<button
type="button"
class="sidebar-action-link sidebar-footer-action"
[attr.aria-label]="t('more')"
[pTooltip]="t('more')"
tooltipPosition="top"
(click)="openSidebarOverlay($event, moreMenu, 'above')"
>
<i class="pi pi-ellipsis-h" aria-hidden="true"></i>
<span>{{ t('more') }}</span>
</button>
</div>
}
<p-menu #addMenu [model]="addMenuItems()" [popup]="true" appendTo="body" styleClass="sidebar-more-menu sidebar-footer-popover" (onShow)="applyOverlayBottom(addMenu)"/>
<p-popover #notificationsPopover appendTo="body" styleClass="sidebar-flyout-popover" (onShow)="applyOverlayBottom(notificationsPopover)">
<app-unified-notification-popover-component></app-unified-notification-popover-component>
</p-popover>
<p-menu #moreMenu [model]="moreMenuItems()" [popup]="true" appendTo="body" styleClass="sidebar-more-menu sidebar-footer-popover" (onShow)="applyOverlayBottom(moreMenu)"/>
@if (currentUser(); as user) {
<div class="sidebar-footer-bottom">
<button
type="button"
class="sidebar-user-trigger"
[attr.aria-label]="t('profile')"
aria-haspopup="menu"
[pTooltip]="user.name || user.username"
[tooltipDisabled]="!layoutService.sidebarCollapsed()"
tooltipPosition="right"
(click)="openSidebarOverlay($event, userMenu, 'below')"
>
<span class="sidebar-user-avatar" aria-hidden="true">{{ userInitials() }}</span>
<span class="sidebar-user-meta">
<span class="sidebar-user-name">{{ user.name || user.username }}</span>
@if (user.name) {
<span class="sidebar-user-handle">&#64;{{ user.username }}</span>
}
</span>
</button>
<button
type="button"
class="sidebar-icon-button sidebar-collapse-button"
[attr.aria-label]="layoutService.sidebarCollapsed() ? t('expandSidebar') : t('collapseSidebar')"
[attr.aria-expanded]="!layoutService.sidebarCollapsed()"
[pTooltip]="layoutService.sidebarCollapsed() ? t('expandSidebar') : t('collapseSidebar')"
[tooltipDisabled]="!layoutService.sidebarCollapsed()"
tooltipPosition="right"
(click)="layoutService.toggleSidebarCollapsed()"
>
<i
class="pi"
[class.pi-angle-double-left]="!layoutService.sidebarCollapsed()"
[class.pi-angle-double-right]="layoutService.sidebarCollapsed()"
aria-hidden="true"
></i>
</button>
</div>
<p-menu #userMenu [model]="userMenuItems()" [popup]="true" appendTo="body" styleClass="sidebar-user-menu" (onShow)="applyOverlayBottom(userMenu)">
<ng-template pTemplate="start">
<div class="sidebar-user-menu-header">
<span class="sidebar-user-avatar" aria-hidden="true">{{ userInitials() }}</span>
<span class="sidebar-user-meta">
<span class="sidebar-user-name">{{ user.name || user.username }}</span>
@if (user.name) {
<span class="sidebar-user-handle">&#64;{{ user.username }}</span>
}
</span>
</div>
</ng-template>
<ng-template pTemplate="end">
@if (version(); as v) {
<div class="sidebar-user-menu-footer">
<span>Grimmory v{{ v.current }}</span>
@if (hasUpdate()) {
<span class="sidebar-user-update">{{ t('update') }}</span>
}
</div>
}
</ng-template>
</p-menu>
} @else {
<div class="sidebar-footer-bottom">
<button
type="button"
class="sidebar-icon-button sidebar-collapse-button"
[attr.aria-label]="layoutService.sidebarCollapsed() ? t('expandSidebar') : t('collapseSidebar')"
[attr.aria-expanded]="!layoutService.sidebarCollapsed()"
[pTooltip]="layoutService.sidebarCollapsed() ? t('expandSidebar') : t('collapseSidebar')"
[tooltipDisabled]="!layoutService.sidebarCollapsed()"
tooltipPosition="right"
(click)="layoutService.toggleSidebarCollapsed()"
>
<i
class="pi"
[class.pi-angle-double-left]="!layoutService.sidebarCollapsed()"
[class.pi-angle-double-right]="layoutService.sidebarCollapsed()"
aria-hidden="true"
></i>
</button>
</div>
}
</div>
</div>
</ng-container>
@@ -2,109 +2,435 @@
display: flex;
flex-direction: column;
height: 100%;
min-height: 0;
}
.home-menu-section {
position: relative;
.sidebar-width-btn {
position: absolute;
top: 0.125rem;
right: 0.5rem;
display: inline-flex;
align-items: center;
justify-content: center;
padding: 0;
border: 0;
background: none;
font-size: 0.8rem;
color: var(--surface-500);
cursor: pointer;
transition: color 0.2s ease;
&:hover {
color: var(--primary-color);
}
}
}
.sidebar-width-popover {
.sidebar-header {
display: flex;
align-items: center;
gap: 0.75rem;
min-width: 200px;
padding: 0.25rem;
.sidebar-width-popover-label {
font-size: 0.8rem;
color: var(--text-muted-color);
white-space: nowrap;
min-width: 38px;
text-align: right;
}
p-slider {
flex: 1;
}
justify-content: flex-start;
gap: var(--space-2);
padding: var(--sidebar-header-padding-block) 0;
margin-bottom: var(--sidebar-header-gap-after);
}
.version-info {
padding: 1rem;
text-align: center;
.sidebar-brand {
/* Shared rendered-height for both SVGs — derived from wordmark's width × aspect
at default sidebar width. Keeps the wordmark and G-only mark the same pixel
size so they visually align across the collapse/expand toggle. */
--brand-content-height: calc((225px - 2.5rem) * 350 / 2500);
--sidebar-brand-optical-nudge: -1px;
display: grid;
align-items: center;
box-sizing: border-box;
grid-template-columns: var(--sidebar-row-icon-size) minmax(0, 1fr);
gap: var(--space-4);
width: 100%;
font-size: 0.875rem;
}
.version-text {
color: var(--text-color-secondary);
}
.version-link {
font-size: 0.875rem;
min-width: 0;
min-height: var(--sidebar-row-min-height);
padding: var(--sidebar-row-padding-block) var(--sidebar-row-padding-inline-end) var(--sidebar-row-padding-block) var(--sidebar-row-padding-inline-start);
color: var(--text-color);
text-decoration: none;
letter-spacing: 0.02em;
&:hover {
text-decoration: underline;
color: var(--high-contrast-text-color);
}
}
.version-label {
font-size: 0.875rem;
}
.version-copy-trigger {
padding: 0;
border: 0;
background: none;
font-family: inherit;
line-height: inherit;
cursor: pointer;
user-select: text;
&:hover {
text-decoration: underline;
color: var(--high-contrast-text-color);
color: var(--primary-color);
}
&:focus-visible {
outline: 1px solid var(--primary-color);
outline-offset: 0.2rem;
border-radius: 0.25rem;
background-color: var(--surface-hover);
box-shadow: var(--sidebar-focus-ring);
outline: none;
}
}
.update-link {
.sidebar-brand-mark {
/* Shown only in collapsed state (see _menu.scss). */
display: none;
align-items: center;
/* Left-align the SVG — its natural width is wider than the 18px icon column,
and centering it would push the G ~1.5px left of where the wordmark's G
starts, breaking alignment during the collapse/expand toggle. */
justify-content: flex-start;
width: var(--sidebar-row-icon-size);
min-width: var(--sidebar-row-icon-size);
overflow: visible;
grid-column: 1;
}
.sidebar-brand-icon {
height: var(--brand-content-height);
width: auto;
flex-shrink: 0;
max-width: none;
transform: translateX(var(--sidebar-brand-optical-nudge));
}
.sidebar-brand-wordmark {
/* In-flow grid item with fixed width + min-width. The min-width pin prevents
the wordmark from shrinking when the grid tracks shrink during the sidebar
expand animation. Width = min(default-sidebar-content, stored-content): fills
exactly at default 225px, scales down when the user resizes narrower. Height
is pinned alongside width so the wordmark and G-only icon are the same size. */
--wordmark-width: calc(min(225px, var(--sidebar-stored-width, 225px)) - 2.5rem);
display: block;
width: var(--wordmark-width);
min-width: var(--wordmark-width);
height: var(--brand-content-height);
grid-column: 1 / -1;
justify-self: start;
transform: translateX(var(--sidebar-brand-optical-nudge));
}
.sidebar-toolbar-button {
font-weight: 500;
}
.sidebar-icon-button.sidebar-mobile-close-button {
display: none;
}
.sidebar-action-link.sidebar-toolbar-button {
color: var(--primary-color);
&:hover {
color: var(--primary-color);
}
}
.sidebar-icon-button {
display: inline-flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
box-sizing: border-box;
width: var(--sidebar-row-min-height);
height: var(--sidebar-row-min-height);
padding: 0;
border: 0;
background: none;
border-radius: var(--sidebar-row-radius);
color: var(--text-color-secondary);
cursor: pointer;
color: var(--primary-text-color);
font-family: inherit;
font-size: 0.75rem;
line-height: inherit;
transition: background-color var(--transition-fast), color var(--transition-fast);
&:hover {
text-decoration: underline;
color: var(--primary-hover-color);
background-color: var(--surface-hover);
color: var(--text-color);
}
&:focus-visible {
background-color: var(--surface-hover);
box-shadow: var(--sidebar-focus-ring);
outline: none;
}
i {
font-size: var(--text-base);
}
}
.sidebar-nav {
flex: 1 1 auto;
overflow-y: auto;
min-height: 0;
.layout-root-menuitem + .layout-root-menuitem {
margin-top: var(--sidebar-group-gap);
}
}
.sidebar-nav-top {
display: flex;
flex-direction: column;
gap: var(--space-2);
padding-bottom: var(--sidebar-group-gap);
}
.sidebar-footer {
display: flex;
flex-direction: column;
gap: var(--space-1);
padding-top: var(--space-2);
margin-top: var(--space-2);
border-top: 1px solid var(--border-color);
}
.sidebar-action-link {
display: flex;
align-items: center;
box-sizing: border-box;
gap: var(--sidebar-row-gap);
height: var(--sidebar-row-min-height);
min-height: var(--sidebar-row-min-height);
width: 100%;
min-width: 0;
padding: var(--sidebar-row-padding-block) var(--sidebar-row-padding-inline-end) var(--sidebar-row-padding-block) var(--sidebar-row-padding-inline-start);
border: 0;
background: none;
border-radius: var(--sidebar-row-radius);
color: var(--text-color);
font: inherit;
font-size: var(--text-base);
text-align: left;
cursor: pointer;
transition: background-color var(--transition-fast), padding var(--transition-base);
&:hover {
background-color: var(--surface-hover);
}
&:focus-visible {
background-color: var(--surface-hover);
box-shadow: var(--sidebar-focus-ring);
outline: none;
}
&.active-route {
color: var(--primary-color);
background-color: color-mix(in srgb, var(--primary-color) 8%, transparent);
}
i {
width: var(--sidebar-row-icon-size);
height: var(--sidebar-row-icon-size);
font-size: var(--text-base);
display: inline-flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
span {
margin-left: var(--sidebar-row-label-offset);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
}
.sidebar-footer-actions {
display: flex;
align-items: center;
gap: var(--space-1);
}
.sidebar-footer-action {
flex: 1 1 0;
width: auto;
min-width: 0;
justify-content: center;
padding-left: 0;
padding-right: 0;
span {
display: none;
}
i {
margin: 0;
}
}
.sidebar-footer-bottom {
display: flex;
align-items: center;
gap: var(--space-2);
}
.sidebar-search-button {
padding-inline-end: var(--space-2);
background-color: var(--surface-hover);
&:hover {
background-color: color-mix(in srgb, var(--surface-hover), white 15%);
}
}
.sidebar-search-shortcut {
display: inline-flex;
align-items: center;
justify-content: center;
align-self: center;
padding: 0;
border: 0;
background: transparent;
margin-left: auto;
color: var(--text-color-secondary);
font-family: inherit;
font-size: var(--text-xs);
line-height: 1;
white-space: nowrap;
flex-shrink: 0;
}
.sidebar-user-trigger {
display: flex;
align-items: center;
box-sizing: border-box;
gap: var(--sidebar-row-gap);
width: 100%;
min-width: 0;
height: 2.75rem;
min-height: 2.75rem;
padding: 0 var(--sidebar-row-padding-inline-end) 0 var(--sidebar-row-padding-inline-start);
border: 0;
background: none;
border-radius: var(--sidebar-row-radius);
color: var(--text-color);
font: inherit;
text-align: left;
cursor: pointer;
transition: background-color var(--transition-fast);
&:hover {
background-color: var(--surface-hover);
}
&:focus-visible {
background-color: var(--surface-hover);
box-shadow: var(--sidebar-focus-ring);
outline: none;
}
}
.sidebar-footer-bottom .sidebar-user-trigger {
flex: 1 1 auto;
}
.sidebar-collapse-button {
margin-left: auto;
}
.sidebar-user-avatar {
display: inline-flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
width: 1.75rem;
height: 1.75rem;
border-radius: var(--radius-pill);
background-color: color-mix(in srgb, var(--primary-color) 18%, transparent);
color: var(--primary-color);
font-size: var(--text-xs);
font-weight: 600;
letter-spacing: 0.02em;
line-height: 1;
text-transform: uppercase;
}
/* Align the circle's center with the sidebar icon column (18px icons vs 28px avatar). */
.sidebar-user-trigger .sidebar-user-avatar {
margin-left: calc((var(--sidebar-row-icon-size) - 1.75rem) / 2);
}
.sidebar-user-meta {
display: flex;
flex-direction: column;
flex: 1 1 auto;
min-width: 0;
line-height: 1.15;
}
.sidebar-user-name {
font-size: var(--text-base);
font-weight: 500;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.sidebar-user-handle {
font-size: var(--text-xs);
color: var(--text-color-secondary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
@media (width <= 991px) {
.sidebar-header {
align-items: flex-start;
margin-bottom: var(--space-3);
}
.sidebar-brand {
width: auto;
flex: 1 1 auto;
}
.sidebar-icon-button.sidebar-mobile-close-button {
display: inline-flex;
width: 3rem;
height: 3rem;
border-radius: var(--radius-pill);
background-color: var(--surface-hover);
color: var(--text-color);
&:hover {
background-color: color-mix(in srgb, var(--surface-hover), white 15%);
}
}
.sidebar-nav-top {
display: none;
}
.sidebar-search-shortcut {
display: none;
}
.sidebar-footer {
gap: var(--space-2);
padding-top: var(--space-3);
margin-top: var(--space-3);
}
.sidebar-footer-actions {
gap: var(--space-2);
}
.sidebar-footer-action {
container-type: inline-size;
flex-direction: column;
gap: 0.35rem;
height: auto;
min-height: 4.75rem;
padding: var(--space-2) var(--space-1);
border-radius: var(--radius-lg);
background-color: var(--surface-hover);
&:hover {
background-color: color-mix(in srgb, var(--surface-hover), white 15%);
}
}
.sidebar-footer-action span {
display: inline-flex;
margin-left: 0;
font-size: var(--text-sm);
line-height: 1.15;
white-space: normal;
text-align: center;
text-wrap: balance;
color: var(--text-color-secondary);
overflow-wrap: anywhere;
}
@container (width <= 6.25rem) {
.sidebar-footer-action span {
font-size: var(--text-xs);
}
}
.sidebar-footer-action i {
font-size: 1.125rem;
}
.sidebar-collapse-button {
display: none;
}
}
@@ -1,17 +1,197 @@
import {describe, it} from 'vitest';
import { signal, WritableSignal } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { of } from 'rxjs';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
// NOTE(frontend-seam): Real menu coverage needs coordinated signals for libraries, shelves,
// magic shelves, authors, books, user permissions, translation changes, and version/dialog
// behavior. The component is a large computed-menu assembler, and a low-value shallow spec would
// not honestly verify the menu trees that matter.
describe.skip('AppMenuComponent', () => {
it('needs a menu-data seam to verify computed home/library/shelf/magic-shelf menu trees', () => {
// TODO(seam): Cover computed menu composition once the dependent signals/services can be
// driven through a stable test harness rather than an all-up runtime mock graph.
import { getTranslocoModule } from '../../../core/testing/transloco-testing';
import { BookDialogHelperService } from '../../../features/book/components/book-browser/book-dialog-helper.service';
import { BookService } from '../../../features/book/service/book.service';
import { LibraryHealthService } from '../../../features/book/service/library-health.service';
import { LibraryService } from '../../../features/book/service/library.service';
import { LibraryShelfMenuService } from '../../../features/book/service/library-shelf-menu.service';
import { ShelfService } from '../../../features/book/service/shelf.service';
import { AuthorService } from '../../../features/author-browser/service/author.service';
import { MagicShelfService } from '../../../features/magic-shelf/service/magic-shelf.service';
import { SeriesDataService } from '../../../features/series-browser/service/series-data.service';
import { UserService } from '../../../features/settings/user-management/user.service';
import { CommandPaletteService } from '../../../features/command-palette/command-palette.service';
import { AuthService } from '../../service/auth.service';
import { VersionService } from '../../service/version.service';
import { DialogLauncherService } from '../../services/dialog-launcher.service';
import { LayoutService } from '../layout.service';
import { AppMenuComponent } from './app.menu.component';
interface MenuOverlay {
container: HTMLElement;
toggle: (event: MouseEvent) => void;
}
function createRect(top: number, bottom: number, left: number): DOMRect {
return {
x: left,
y: top,
top,
bottom,
left,
right: left + 40,
width: 40,
height: bottom - top,
toJSON: () => ({}),
} as DOMRect;
}
interface TestUser {
name: string;
username: string;
permissions: Record<string, boolean>;
}
describe('AppMenuComponent', () => {
let fixture: ComponentFixture<AppMenuComponent>;
let component: AppMenuComponent;
let commandPaletteService: { open: ReturnType<typeof vi.fn> };
let currentUser: WritableSignal<TestUser | null>;
const layoutService = {
sidebarCollapsed: signal(false),
isDesktop: signal(true),
librarySort: signal({ field: 'name', order: 'desc' }),
shelfSort: signal({ field: 'name', order: 'asc' }),
magicShelfSort: signal({ field: 'name', order: 'asc' }),
closeMobileSidebar: vi.fn(),
};
beforeEach(() => {
commandPaletteService = { open: vi.fn() };
currentUser = signal<TestUser | null>(null);
TestBed.configureTestingModule({
imports: [AppMenuComponent, getTranslocoModule()],
providers: [
{ provide: LibraryService, useValue: { libraries: signal([]), bookCountByLibraryId: signal(new Map()) } },
{ provide: LibraryHealthService, useValue: { isUnhealthy: vi.fn(() => false) } },
{ provide: ShelfService, useValue: { shelves: signal([]), bookCountByShelfId: signal(new Map()), unshelvedBookCount: signal(0) } },
{ provide: BookService, useValue: { books: signal([]) } },
{
provide: LibraryShelfMenuService,
useValue: {
initializeLibraryMenuItems: vi.fn(() => []),
initializeShelfMenuItems: vi.fn(() => []),
initializeMagicShelfMenuItems: vi.fn(() => []),
},
},
{
provide: DialogLauncherService,
useValue: {
openLibraryCreateDialog: vi.fn(),
openMagicShelfCreateDialog: vi.fn(),
openFileUploadDialog: vi.fn(),
},
},
{ provide: CommandPaletteService, useValue: commandPaletteService },
{ provide: BookDialogHelperService, useValue: { openShelfCreatorDialog: vi.fn() } },
{ provide: AuthService, useValue: { logout: vi.fn() } },
{ provide: LayoutService, useValue: layoutService },
{ provide: UserService, useValue: { currentUser } },
{ provide: MagicShelfService, useValue: { shelves: signal([]), bookCountByMagicShelfId: signal(new Map()) } },
{ provide: SeriesDataService, useValue: { allSeries: signal([]) } },
{ provide: AuthorService, useValue: { allAuthors: signal([]) } },
{ provide: VersionService, useValue: { getVersion: vi.fn(() => of(null)) } },
],
});
TestBed.overrideComponent(AppMenuComponent, { set: { template: '' } });
fixture = TestBed.createComponent(AppMenuComponent);
component = fixture.componentInstance;
layoutService.isDesktop.set(true);
layoutService.closeMobileSidebar.mockReset();
});
it('needs a version-dialog and local-storage seam to verify side effects around dialogs and sidebar sizing', () => {
// TODO(seam): Cover version dialog and sidebar width behavior after those side effects are
// exposed behind a narrower facade.
afterEach(() => {
TestBed.resetTestingModule();
vi.restoreAllMocks();
});
it('opens the command palette from the sidebar search trigger', () => {
component.openSearch();
expect(commandPaletteService.open).toHaveBeenCalled();
});
it('closes the mobile drawer from the sidebar header close action', () => {
component.closeMobileSidebar();
expect(layoutService.closeMobileSidebar).toHaveBeenCalled();
});
it('anchors above-placement overlays from the trigger top edge when the sidebar is expanded', () => {
const trigger = document.createElement('button');
vi.spyOn(trigger, 'getBoundingClientRect').mockReturnValue(createRect(100, 148, 40));
const container = document.createElement('div');
const overlay = { container, toggle: vi.fn() };
const menuHarness = component as unknown as { applyOverlayBottom(overlay: MenuOverlay): void };
component.openSidebarOverlay({ currentTarget: trigger } as unknown as MouseEvent, overlay as never, 'above');
menuHarness.applyOverlayBottom(overlay);
expect(overlay.toggle).toHaveBeenCalled();
expect(container.style.getPropertyValue('--sidebar-popover-bottom')).toBe(`${window.innerHeight - 100 + 8}px`);
expect(container.style.getPropertyValue('--sidebar-popover-left')).toBe('40px');
});
it('anchors below-placement overlays from the trigger bottom edge', () => {
const trigger = document.createElement('button');
vi.spyOn(trigger, 'getBoundingClientRect').mockReturnValue(createRect(220, 260, 24));
const container = document.createElement('div');
const overlay = { container, toggle: vi.fn() };
const menuHarness = component as unknown as { applyOverlayBottom(overlay: MenuOverlay): void };
component.openSidebarOverlay({ currentTarget: trigger } as unknown as MouseEvent, overlay as never, 'below');
menuHarness.applyOverlayBottom(overlay);
expect(container.style.getPropertyValue('--sidebar-popover-bottom')).toBe(`${window.innerHeight - 260}px`);
expect(container.style.getPropertyValue('--sidebar-popover-left')).toBe('');
});
it('derives user initials from a multi-part display name', () => {
currentUser.set({ name: 'Alex Bilbie', username: 'alex', permissions: {} });
expect(component.userInitials()).toBe('AB');
});
it('falls back to the first initial when the display name is a single part', () => {
currentUser.set({ name: ' Cher ', username: 'cher', permissions: {} });
expect(component.userInitials()).toBe('C');
});
it('uses the username when the display name is empty', () => {
currentUser.set({ name: '', username: 'alex', permissions: {} });
expect(component.userInitials()).toBe('A');
});
it('returns an empty string when no user is signed in', () => {
currentUser.set(null);
expect(component.userInitials()).toBe('');
});
it('anchors notifications above the trigger and keeps them inside the viewport on mobile', () => {
layoutService.isDesktop.set(false);
const trigger = document.createElement('button');
vi.spyOn(trigger, 'getBoundingClientRect').mockReturnValue(createRect(220, 260, 980));
const container = document.createElement('div');
Object.defineProperty(container, 'offsetWidth', { value: 120, configurable: true });
const overlay = { container, toggle: vi.fn() };
const menuHarness = component as unknown as { applyOverlayBottom(overlay: MenuOverlay): void };
component.openSidebarOverlay({ currentTarget: trigger } as unknown as MouseEvent, overlay as never, 'above');
menuHarness.applyOverlayBottom(overlay);
expect(container.style.getPropertyValue('--sidebar-popover-bottom')).toBe(`${window.innerHeight - 220 + 8}px`);
expect(container.style.getPropertyValue('--sidebar-popover-left')).toBe(`${window.innerWidth - 128}px`);
});
});
@@ -1,49 +1,61 @@
import { Component, computed, effect, inject, signal } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { AppMenuitemComponent } from './app.menuitem.component';
import { Component, computed, inject } from '@angular/core';
import { RouterLink } from '@angular/router';
import { AppMenuSectionComponent } from './app.menu-section.component';
import { Popover } from 'primeng/popover';
import { Menu } from 'primeng/menu';
import { BookDialogHelperService } from '../../../features/book/components/book-browser/book-dialog-helper.service';
import { UnifiedNotificationBoxComponent } from '../../components/unified-notification-popover/unified-notification-popover-component';
import { LibraryService } from '../../../features/book/service/library.service';
import { LibraryHealthService } from '../../../features/book/service/library-health.service';
import { ShelfService } from '../../../features/book/service/shelf.service';
import { BookService } from '../../../features/book/service/book.service';
import { LibraryShelfMenuService } from '../../../features/book/service/library-shelf-menu.service';
import { VersionService } from '../../service/version.service';
import { UserService } from '../../../features/settings/user-management/user.service';
import { MagicShelfService } from '../../../features/magic-shelf/service/magic-shelf.service';
import { SeriesDataService } from '../../../features/series-browser/service/series-data.service';
import { AuthorService } from '../../../features/author-browser/service/author.service';
import { DialogLauncherService } from '../../services/dialog-launcher.service';
import { TranslocoDirective, TranslocoService } from '@jsverse/transloco';
import { Slider } from 'primeng/slider';
import { FormsModule } from '@angular/forms';
import { Popover } from 'primeng/popover';
import { MessageService } from 'primeng/api';
import { LocalStorageService } from '../../service/local-storage.service';
import { CommandPaletteService } from '../../../features/command-palette/command-palette.service';
import { AuthService } from '../../service/auth.service';
import { LayoutService } from '../layout.service';
import { TranslocoDirective, TranslocoPipe, TranslocoService } from '@jsverse/transloco';
import { Tooltip } from 'primeng/tooltip';
import type { MenuItem } from 'primeng/api';
import { AppVersion, VersionService } from '../../service/version.service';
import { toSignal } from '@angular/core/rxjs-interop';
import { catchError, of } from 'rxjs';
import { NavItem, SidebarSection } from '../navigation/nav-item.model';
import { buildQuickActionNavItems, findPageNavItem } from '../navigation/nav-catalog';
import {
buildHomeSection,
buildLibrarySection,
buildMagicShelfSection,
buildShelfSection,
} from './sidebar-sections';
export type NavIconType = 'PRIME_NG' | 'CUSTOM_SVG';
const DOCUMENTATION_URL = 'https://grimmory.org/docs/getting-started';
export type NavItemType =
| 'library' | 'shelf' | 'magicShelf'
| 'allBooks' | 'series' | 'authors';
function computeInitials(name: string | null | undefined, username: string | null | undefined): string {
const source = (name?.trim() || username?.trim() || '').trim();
if (!source) return '';
const parts = source.split(/\s+/).filter(Boolean);
if (parts.length >= 2) {
return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
}
return parts[0][0].toUpperCase();
}
export interface NavItem {
label: string;
icon?: string;
iconType?: NavIconType;
routerLink?: string[];
type?: NavItemType;
group?: boolean;
bookCount?: number;
unhealthy?: boolean;
items?: NavItem[];
hasDropDown?: boolean;
hasCreate?: boolean;
contextMenuItems?: MenuItem[];
function hasAppUpdate(version: AppVersion | null): boolean {
return !!version && !!version.latest && version.latest !== version.current;
}
function detectSearchShortcut(userAgent: string): string {
return /Mac|iPhone|iPad|iPod/i.test(userAgent) ? '⌘K' : 'Ctrl+K';
}
@Component({
selector: 'app-menu',
imports: [AppMenuitemComponent, TranslocoDirective, Slider, FormsModule, Popover],
imports: [AppMenuSectionComponent, Popover, Menu, UnifiedNotificationBoxComponent, RouterLink, TranslocoDirective, TranslocoPipe, Tooltip],
templateUrl: './app.menu.component.html',
styleUrl: './app.menu.component.scss',
})
@@ -52,348 +64,188 @@ export class AppMenuComponent {
private readonly libraryHealthService = inject(LibraryHealthService);
private readonly shelfService = inject(ShelfService);
private readonly bookService = inject(BookService);
private readonly versionService = inject(VersionService);
private readonly libraryShelfMenuService = inject(LibraryShelfMenuService);
private readonly dialogLauncherService = inject(DialogLauncherService);
private readonly messageService = inject(MessageService);
private readonly commandPaletteService = inject(CommandPaletteService);
private readonly bookDialogHelperService = inject(BookDialogHelperService);
private readonly authService = inject(AuthService);
readonly layoutService = inject(LayoutService);
private readonly userService = inject(UserService);
private readonly magicShelfService = inject(MagicShelfService);
private readonly seriesDataService = inject(SeriesDataService);
private readonly authorService = inject(AuthorService);
private readonly versionService = inject(VersionService);
private readonly t = inject(TranslocoService);
private readonly localStorageService = inject(LocalStorageService);
private readonly activeLang = toSignal(this.t.langChanges$, {initialValue: this.t.getActiveLang()});
private readonly currentUser = this.userService.currentUser;
readonly currentUser = this.userService.currentUser;
readonly version = toSignal<AppVersion | null>(
this.versionService.getVersion().pipe(catchError(() => of(null))),
{ initialValue: null },
);
private readonly allAuthors = this.authorService.allAuthors;
private readonly activeLang = toSignal(this.t.langChanges$, { initialValue: this.t.getActiveLang() });
private readonly translate = (key: string): string => this.t.translate(key);
readonly versionInfo = toSignal(this.versionService.getVersion(), { initialValue: null });
readonly searchShortcutLabel = detectSearchShortcut(
typeof navigator !== 'undefined' ? navigator.userAgent : ''
);
librarySortField = signal<'name' | 'id'>('name');
librarySortOrder = signal<'asc' | 'desc'>('desc');
shelfSortField = signal<'name' | 'id'>('name');
shelfSortOrder = signal<'asc' | 'desc'>('asc');
magicShelfSortField = signal<'name' | 'id'>('name');
magicShelfSortOrder = signal<'asc' | 'desc'>('asc');
sidebarWidth = this.localStorageService.get<number>('sidebarWidth') ?? 225;
private readonly libraryBookCounts = computed(() => {
const counts = new Map<number, number>();
for (const book of this.bookService.books()) {
if (book.libraryId != null) {
counts.set(book.libraryId, (counts.get(book.libraryId) ?? 0) + 1);
}
}
return counts;
});
private readonly shelfBookCounts = computed(() => {
const currentUserId = this.currentUser()?.id;
const counts = new Map<number, number>();
let unshelvedCount = 0;
for (const book of this.bookService.books()) {
if (!book.shelves || book.shelves.length === 0) {
unshelvedCount++;
} else {
for (const shelf of book.shelves) {
if (shelf.id != null) {
counts.set(shelf.id, (counts.get(shelf.id) ?? 0) + 1);
}
}
}
}
// For shelves not owned by the current user, fall back to the shelf's bookCount field
for (const shelf of this.shelfService.shelves()) {
if (shelf.userId !== currentUserId && shelf.id != null) {
counts.set(shelf.id, shelf.bookCount || 0);
}
}
counts.set(-1, unshelvedCount); // sentinel key for unshelved count
return counts;
});
private readonly magicShelfBookCounts = computed(() => {
const counts = new Map<number, number>();
const shelves = this.magicShelfService.shelves();
if (shelves.length === 0) return counts;
for (const shelf of shelves) {
if (shelf.id != null) {
counts.set(shelf.id, this.magicShelfService.getBookCountValue(shelf.id));
}
}
return counts;
});
readonly homeMenu = computed<NavItem[]>(() => {
readonly sections = computed<SidebarSection[]>(() => {
this.activeLang();
return [
{
label: this.t.translate('layout.menu.home'),
items: [
{
label: this.t.translate('layout.menu.dashboard'),
icon: 'pi pi-fw pi-home',
routerLink: ['/dashboard'],
},
{
label: this.t.translate('layout.menu.allBooks'),
type: 'allBooks',
icon: 'pi pi-fw pi-book',
routerLink: ['/all-books'],
bookCount: this.bookService.books().length,
},
{
label: this.t.translate('layout.menu.series'),
type: 'series',
icon: 'pi pi-fw pi-objects-column',
routerLink: ['/series'],
bookCount: this.seriesDataService.allSeries().length,
},
{
label: this.t.translate('layout.menu.authors'),
type: 'authors',
icon: 'pi pi-fw pi-users',
routerLink: ['/authors'],
bookCount: this.allAuthors()?.length ?? 0,
},
{
label: this.t.translate('layout.menu.notebook'),
icon: 'pi pi-fw pi-pencil',
routerLink: ['/notebook'],
}
],
},
...buildHomeSection(this.translate, {
allBooks: this.bookService.books().length,
series: this.seriesDataService.allSeries().length,
authors: this.allAuthors()?.length ?? 0,
}),
...buildLibrarySection(
this.libraryService.libraries(),
this.libraryService.bookCountByLibraryId(),
this.layoutService.librarySort(),
this.translate,
{ health: this.libraryHealthService, menuItems: this.libraryShelfMenuService },
),
...buildShelfSection(
this.shelfService.shelves(),
this.shelfService.bookCountByShelfId(),
this.shelfService.unshelvedBookCount(),
this.layoutService.shelfSort(),
this.translate,
{ menuItems: this.libraryShelfMenuService },
),
...buildMagicShelfSection(
this.magicShelfService.shelves(),
this.magicShelfService.bookCountByMagicShelfId(),
this.layoutService.magicShelfSort(),
this.translate,
{ menuItems: this.libraryShelfMenuService },
),
];
});
readonly libraryMenu = computed<NavItem[]>(() => {
readonly addMenuItems = computed<MenuItem[]>(() => {
this.activeLang();
const libCounts = this.libraryBookCounts();
const sortedLibraries = this.sortArray(
this.libraryService.libraries(),
this.librarySortField(),
this.librarySortOrder()
);
return [
{
label: this.t.translate('layout.menu.libraries'),
type: 'library',
group: true,
hasDropDown: true,
hasCreate: true,
items: sortedLibraries.map((library) => ({
contextMenuItems: this.libraryShelfMenuService.initializeLibraryMenuItems(library),
label: library.name,
type: 'library',
icon: library.icon || undefined,
iconType: this.toNavIconType(library.iconType),
routerLink: [`/library/${library.id}/books`],
bookCount: libCounts.get(library.id ?? 0) ?? 0,
unhealthy: this.libraryHealthService.isUnhealthy(library.id ?? 0),
})),
},
];
});
readonly magicShelfMenu = computed<NavItem[]>(() => {
this.activeLang();
const sortedShelves = this.sortArray(
this.magicShelfService.shelves(),
this.magicShelfSortField(),
this.magicShelfSortOrder()
);
return [
{
label: this.t.translate('layout.menu.magicShelves'),
type: 'magicShelf',
group: true,
hasDropDown: true,
hasCreate: true,
items: sortedShelves.map((shelf) => ({
label: shelf.name,
type: 'magicShelf',
icon: shelf.icon || undefined,
iconType: this.toNavIconType(shelf.iconType),
contextMenuItems: this.libraryShelfMenuService.initializeMagicShelfMenuItems(shelf),
routerLink: [`/magic-shelf/${shelf.id}/books`],
bookCount: this.magicShelfBookCounts().get(shelf.id ?? 0) ?? 0,
})),
},
];
});
readonly shelfMenu = computed<NavItem[]>(() => {
this.activeLang();
const shelfCounts = this.shelfBookCounts();
const sortedShelves = this.sortArray(
this.shelfService.shelves(),
this.shelfSortField(),
this.shelfSortOrder()
);
const shelves = [...sortedShelves];
const koboShelfIndex = shelves.findIndex(shelf => shelf.name === 'Kobo');
let koboShelf = null;
if (koboShelfIndex !== -1) {
koboShelf = shelves.splice(koboShelfIndex, 1)[0];
}
const shelfItems = shelves.map((shelf) => ({
contextMenuItems: this.libraryShelfMenuService.initializeShelfMenuItems(shelf),
label: shelf.name,
type: 'shelf' as const,
icon: shelf.icon || undefined,
iconType: this.toNavIconType(shelf.iconType),
routerLink: [`/shelf/${shelf.id}/books`],
bookCount: shelfCounts.get(shelf.id ?? 0) ?? 0,
}));
const items: NavItem[] = [{
label: this.t.translate('layout.menu.unshelved'),
type: 'shelf',
icon: 'pi pi-inbox',
iconType: 'PRIME_NG',
routerLink: ['/unshelved-books'],
bookCount: shelfCounts.get(-1) ?? 0,
}];
if (koboShelf) {
items.push({
label: koboShelf.name,
type: 'shelf',
icon: koboShelf.icon || undefined,
iconType: this.toNavIconType(koboShelf.iconType),
routerLink: [`/shelf/${koboShelf.id}/books`],
bookCount: shelfCounts.get(koboShelf.id ?? 0) ?? 0,
});
}
items.push(...shelfItems);
return [
{
type: 'shelf',
group: true,
label: this.t.translate('layout.menu.shelves'),
hasDropDown: true,
hasCreate: true,
items,
},
];
});
private readonly syncSortPreferencesEffect = effect(() => {
const user = this.currentUser();
if (!user) {
return;
}
if (!user) return [];
if (user.userSettings.sidebarLibrarySorting) {
this.librarySortField.set(this.validateSortField(user.userSettings.sidebarLibrarySorting.field));
this.librarySortOrder.set(this.validateSortOrder(user.userSettings.sidebarLibrarySorting.order));
}
if (user.userSettings.sidebarShelfSorting) {
this.shelfSortField.set(this.validateSortField(user.userSettings.sidebarShelfSorting.field));
this.shelfSortOrder.set(this.validateSortOrder(user.userSettings.sidebarShelfSorting.order));
}
if (user.userSettings.sidebarMagicShelfSorting) {
this.magicShelfSortField.set(this.validateSortField(user.userSettings.sidebarMagicShelfSorting.field));
this.magicShelfSortOrder.set(this.validateSortOrder(user.userSettings.sidebarMagicShelfSorting.order));
}
const actions = buildQuickActionNavItems(this.translate, user.permissions, {
createLibrary: () => this.dialogLauncherService.openLibraryCreateDialog(),
createShelf: () => this.bookDialogHelperService.openShelfCreatorDialog(),
createMagicShelf: () => this.dialogLauncherService.openMagicShelfCreateDialog(),
uploadBook: () => this.dialogLauncherService.openFileUploadDialog(),
});
const bookdrop = findPageNavItem('bookdrop', this.translate, user.permissions);
return this.toMenuItems(bookdrop ? [...actions, bookdrop] : actions);
});
onSidebarWidthChange(): void {
document.documentElement.style.setProperty('--sidebar-width', this.sidebarWidth + 'px');
}
readonly userInitials = computed(() => {
const user = this.currentUser();
return user ? computeInitials(user.name, user.username) : '';
});
saveSidebarWidth(): void {
this.localStorageService.set('sidebarWidth', this.sidebarWidth);
}
readonly hasUpdate = computed(() => hasAppUpdate(this.version()));
openChangelogDialog() {
this.dialogLauncherService.openVersionChangelogDialog();
}
readonly userMenuItems = computed<MenuItem[]>(() => {
this.activeLang();
const user = this.currentUser();
if (!user) return [];
async copyVersion(version: string | undefined): Promise<void> {
if (!version) {
return;
}
const items: MenuItem[] = [];
const detailKey = 'layout.menu.versionCopyFailed';
const clipboard = globalThis.navigator?.clipboard;
if (!clipboard?.writeText) {
this.messageService.add({
severity: 'error',
summary: this.t.translate('common.error'),
detail: this.t.translate(detailKey, { version }),
});
return;
}
try {
await clipboard.writeText(version);
this.messageService.add({
severity: 'success',
summary: this.t.translate('common.success'),
detail: this.t.translate('layout.menu.versionCopied', { version }),
});
} catch {
this.messageService.add({
severity: 'error',
summary: this.t.translate('common.error'),
detail: this.t.translate(detailKey, { version }),
if (!user.permissions.demoUser) {
items.push({
label: this.t.translate('layout.menu.account'),
icon: 'pi pi-user',
command: () => this.dialogLauncherService.openUserProfileDialog(),
});
}
}
getVersionUrl(version: string | undefined): string {
if (!version) return '#';
return version.startsWith('v')
? `https://github.com/grimmory-tools/grimmory/releases/tag/${version}`
: `https://github.com/grimmory-tools/grimmory/commit/${version}`;
}
isSemanticVersion(version: string | undefined): boolean {
if (!version) return false;
const semanticVersionPattern = /^v\d+\.\d+\.\d+$/;
return semanticVersionPattern.test(version);
}
private sortArray<T extends { name?: string | null; id?: number | null }>(
items: T[],
field: 'name' | 'id',
order: 'asc' | 'desc'
): T[] {
const sorted = [...items].sort((a, b) => {
if (field === 'id') {
return (a.id ?? 0) - (b.id ?? 0);
}
return (a.name ?? '').localeCompare(b.name ?? '');
items.push({
label: this.t.translate('layout.menu.documentation'),
icon: 'pi pi-info-circle',
command: () => window.open(DOCUMENTATION_URL, '_blank', 'noopener,noreferrer'),
});
return order === 'desc' ? sorted.reverse() : sorted;
items.push({ separator: true });
items.push({
label: this.t.translate('layout.menu.logout'),
icon: 'pi pi-sign-out',
command: () => this.authService.logout(),
});
return items;
});
readonly moreMenuItems = computed<MenuItem[]>(() => {
this.activeLang();
const user = this.currentUser();
if (!user) return [];
const perms = user.permissions;
return this.toMenuItems([
findPageNavItem('settings', this.translate, perms),
findPageNavItem('libraryStats', this.translate, perms),
findPageNavItem('readingStats', this.translate, perms),
findPageNavItem('metadataManager', this.translate, perms),
]);
});
openSearch(): void {
this.commandPaletteService.open();
}
private validateSortField(field: string): 'name' | 'id' {
return field === 'id' ? 'id' : 'name';
closeMobileSidebar(): void {
this.layoutService.closeMobileSidebar();
}
private validateSortOrder(order: string): 'asc' | 'desc' {
return order === 'desc' ? 'desc' : 'asc';
// Each overlay remembers its own trigger so the position can be re-read when the
// panel renders. Scoping the offset to each panel (instead of a shared variable on
// <html>) means a closing overlay holds its place while a new one opens elsewhere.
private readonly anchorByOverlay = new WeakMap<Menu | Popover, { trigger: HTMLElement; placement: 'above' | 'below' }>();
protected applyOverlayBottom(overlay: Menu | Popover): void {
const anchor = this.anchorByOverlay.get(overlay);
const panel = overlay.container;
if (!anchor || !panel) return;
const rect = anchor.trigger.getBoundingClientRect();
const panelWidth = panel.offsetWidth;
const left = Math.max(Math.min(rect.left, window.innerWidth - panelWidth - 8), 8);
// `above` collapses to `below` when the sidebar is narrow, because the
// anchored left offset assumes an expanded footer row.
const anchorAbove = anchor.placement === 'above' && !this.layoutService.sidebarCollapsed();
if (anchorAbove) {
const bottom = Math.max(window.innerHeight - rect.top + 8, 8);
panel.style.setProperty('--sidebar-popover-bottom', `${bottom}px`);
panel.style.setProperty('--sidebar-popover-left', `${left}px`);
} else {
const bottom = Math.max(window.innerHeight - rect.bottom, 8);
panel.style.setProperty('--sidebar-popover-bottom', `${bottom}px`);
if (this.layoutService.isDesktop()) {
panel.style.removeProperty('--sidebar-popover-left');
} else {
panel.style.setProperty('--sidebar-popover-left', `${left}px`);
}
}
}
private toNavIconType(iconType: string | null | undefined): NavIconType | undefined {
return iconType === 'PRIME_NG' || iconType === 'CUSTOM_SVG' ? iconType : undefined;
private toMenuItems(items: readonly (NavItem | null | undefined)[]): MenuItem[] {
return items.flatMap((item) =>
item ? [{
label: item.label,
icon: item.icon ? `pi ${item.icon}` : undefined,
routerLink: item.routerLink,
command: item.action ? () => item.action?.() : undefined,
}] : []
);
}
openSidebarOverlay(event: MouseEvent, overlay: Menu | Popover, placement: 'above' | 'below'): void {
if (event.currentTarget instanceof HTMLElement) {
this.anchorByOverlay.set(overlay, { trigger: event.currentTarget, placement });
}
overlay.toggle(event);
}
}
@@ -1,49 +0,0 @@
import { describe, expect, it } from 'vitest';
import { TestBed } from '@angular/core/testing';
import { Router, NavigationEnd } from '@angular/router';
import { Subject } from 'rxjs';
import { MenuService } from './app.menu.service';
describe('MenuService', () => {
it('exposes the current path from the router URL', () => {
const routerEvents = new Subject<unknown>();
TestBed.configureTestingModule({
providers: [
MenuService,
{
provide: Router,
useValue: {
url: '/dashboard?tab=recent',
events: routerEvents.asObservable(),
},
},
],
});
const service = TestBed.inject(MenuService);
expect(service.currentPath()).toBe('/dashboard');
});
it('updates currentPath on NavigationEnd', () => {
const routerEvents = new Subject<unknown>();
TestBed.configureTestingModule({
providers: [
MenuService,
{
provide: Router,
useValue: {
url: '/',
events: routerEvents.asObservable(),
},
},
],
});
const service = TestBed.inject(MenuService);
routerEvents.next(new NavigationEnd(1, '/library/1/books', '/library/1/books'));
expect(service.currentPath()).toBe('/library/1/books');
});
});
@@ -1,25 +0,0 @@
import { inject, Injectable, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { NavigationEnd, Router } from '@angular/router';
import { filter } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class MenuService {
private readonly router = inject(Router);
/** Current URL path (without query string), updated once per navigation. */
readonly currentPath = signal(this.router.url.split('?')[0]);
constructor() {
this.router.events
.pipe(
filter((event): event is NavigationEnd => event instanceof NavigationEnd),
takeUntilDestroyed()
)
.subscribe((event) => {
this.currentPath.set(event.urlAfterRedirects.split('?')[0]);
});
}
}
@@ -1,112 +0,0 @@
<ng-container>
@if (root) {
@if (item.hasDropDown) {
<div class="layout-menuitem-root-text root-item-with-dropdown">
<div class="root-item-label-container">
<div>{{ item.label }}</div>
@if (item.hasCreate) {
<button
type="button"
class="plus-icon-button"
[attr.aria-label]="item.label"
(click)="openDialog(item)"
>
<i class="pi pi-plus plus-icon" aria-hidden="true"></i>
</button>
}
</div>
<button
type="button"
class="expand-icon-button"
[attr.aria-label]="item.label"
[attr.aria-expanded]="expanded"
(click)="toggleExpand()"
>
<i
[ngClass]="{
'pi': true,
'pi-angle-up': expanded,
'pi-angle-down': !expanded
}"
class="expand-icon"
aria-hidden="true"
></i>
</button>
</div>
} @else {
<div class="layout-menuitem-root-text root-item">
<div>{{ item.label }}</div>
</div>
}
}
<div>
<div
class="menu-item-container"
[class.active-route-container]="isRouteActive()"
[class.menu-open]="menuOpen"
>
@if (item.routerLink && !item.items) {
<a
class="menu-item-link"
[class.active-route]="isRouteActive()"
[routerLink]="item.routerLink"
tabindex="0"
>
@if (item.unhealthy) {
<span
class="library-health-dot"
[pTooltip]="'common.libraryPathInaccessible' | transloco"
tooltipPosition="right"
></span>
}
<app-icon-display
[icon]="getIconSelection()"
iconClass="layout-menuitem-icon"
size="18px"
[displayEmpty]="true"
></app-icon-display>
<span class="layout-menuitem-text menu-item-text">
{{ item.label }}
</span>
</a>
}
<span class="menu-item-end-content">
@if (shouldShowContextMenuButton()) {
<button
type="button"
class="entity-menu-button"
[attr.aria-label]="item.label"
(click)="entitymenu.toggle($event); menuOpen = !menuOpen; $event.stopPropagation()"
>
<span class="entity-menu-button-content">
<i class="pi pi-ellipsis-v entity-menu-icon" aria-hidden="true"></i>
<span class="entity-menu-count">{{ item.bookCount?.toString() || '' }}</span>
</span>
</button>
<p-menu #entitymenu [model]="item.contextMenuItems" [popup]="true" appendTo="body" (onHide)="menuOpen = false"></p-menu>
} @else if (item.bookCount !== undefined) {
<p class="book-count">
{{ formatCount(item.bookCount) }}
</p>
}
</span>
</div>
<div
class="submenu-container"
[class.expanded]="expanded"
[attr.aria-hidden]="!expanded"
[attr.inert]="expanded ? null : ''"
>
@if (item.items) {
<ul>
@for (child of item.items; track child.routerLink?.join('/') ?? child.label; let i = $index) {
<li app-menuitem [item]="child" [index]="i" [parentKey]="key"></li>
}
</ul>
}
</div>
</div>
</ng-container>
@@ -1,196 +0,0 @@
.plus-icon-button,
.expand-icon-button {
display: inline-flex;
align-items: center;
justify-content: center;
padding: 0;
border: 0;
background: none;
cursor: pointer;
}
.plus-icon {
color: var(--primary-color);
transition: color 0.2s ease;
font-size: 0.8rem;
cursor: pointer;
&:hover {
color: var(--primary-hover-color);
}
}
.root-item-with-dropdown {
display: flex;
align-items: center;
justify-content: space-between;
cursor: pointer;
padding-top: 1rem;
}
.root-item-label-container {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.5rem;
cursor: pointer;
}
.expand-icon {
color: var(--surface-500);
&:hover {
color: var(--surface-200);
}
}
.expand-icon-button {
padding-right: 0.75rem;
}
.root-item {
display: flex;
align-items: center;
justify-content: space-between;
}
.menu-item-container {
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
border-radius: 8px;
cursor: pointer;
&:hover {
background-color: var(--surface-hover);
}
}
.menu-item-container.active-route-container {
background-color: color-mix(in srgb, var(--primary-color) 8%, transparent);
}
.menu-item-link {
display: flex;
align-items: center;
gap: 0.5rem;
width: 100%;
min-width: 0;
background-color: transparent;
&:hover,
&:focus {
background-color: transparent;
}
}
.menu-item-text {
width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
margin-left: 0.35rem;
font-size: 0.985rem;
}
.menu-item-end-content {
display: flex;
align-items: center;
flex-shrink: 0;
}
.entity-menu-button {
display: flex;
align-items: center;
justify-content: center;
min-width: 2rem;
height: 30px;
padding: 0 0.55rem;
border: 0;
border-radius: 999px;
background: transparent;
color: var(--primary-color);
cursor: pointer;
font: inherit;
transition: color 0.2s ease;
}
.entity-menu-button:hover {
background-color: transparent;
color: var(--primary-hover-color);
}
.entity-menu-button-content {
display: flex;
align-items: center;
justify-content: center;
}
.entity-menu-icon {
display: none;
}
.menu-item-container:hover .entity-menu-icon,
.menu-item-container.menu-open .entity-menu-icon {
display: inline;
}
.menu-item-container:hover .entity-menu-count,
.menu-item-container.menu-open .entity-menu-count {
display: none;
}
.book-count {
color: var(--primary-color);
padding-right: 0.75rem;
transition: color 0.2s ease;
}
.menu-item-container:hover .book-count,
.menu-item-container:hover .entity-menu-button {
color: var(--primary-hover-color);
}
.submenu-container {
display: grid;
grid-template-rows: 0fr;
transition: grid-template-rows 400ms cubic-bezier(0.86, 0, 0.07, 1);
@media (prefers-reduced-motion: reduce) {
transition: none;
}
overflow: hidden;
> * {
overflow: hidden;
}
&.expanded {
grid-template-rows: 1fr;
}
}
.library-health-dot {
display: inline-block;
flex-shrink: 0;
width: 10px;
height: 10px;
border-radius: 50%;
background-color: #ef4444;
animation: pulse 2s ease-in-out infinite;
}
@keyframes pulse {
0%, 100% {
opacity: 1;
box-shadow: 0 0 0 0 rgb(239 68 68 / 70%);
}
50% {
opacity: 0.85;
box-shadow: 0 0 0 5px rgb(239 68 68 / 0%);
}
}
@@ -1,105 +0,0 @@
import { ChangeDetectionStrategy, Component, computed, HostBinding, inject, Input, OnInit } from '@angular/core';
import { RouterLink } from '@angular/router';
import { MenuService } from './app.menu.service';
import { NgClass } from '@angular/common';
import { Menu } from 'primeng/menu';
import { UserService } from '../../../features/settings/user-management/user.service';
import { DialogLauncherService } from '../../services/dialog-launcher.service';
import { BookDialogHelperService } from '../../../features/book/components/book-browser/book-dialog-helper.service';
import { IconDisplayComponent } from '../../components/icon-display/icon-display.component';
import { Tooltip } from 'primeng/tooltip';
import { IconSelection } from '../../service/icon-picker.service';
import { TranslocoPipe } from '@jsverse/transloco';
import { NavItem } from './app.menu.component';
@Component({
// Keep this attribute selector so recursive menu items remain valid <li> children.
// eslint-disable-next-line @angular-eslint/component-selector
selector: '[app-menuitem]',
templateUrl: './app.menuitem.component.html',
styleUrls: ['./app.menuitem.component.scss'],
imports: [
RouterLink,
NgClass,
Menu,
IconDisplayComponent,
Tooltip,
TranslocoPipe,
],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class AppMenuitemComponent implements OnInit {
@Input() item!: NavItem;
@Input() index!: number;
@Input() @HostBinding('class.layout-root-menuitem') root!: boolean;
@Input() parentKey!: string;
@Input() menuKey!: string;
menuOpen = false;
key: string = '';
expanded = true;
private readonly menuService = inject(MenuService);
private readonly userService = inject(UserService);
private readonly dialogLauncher = inject(DialogLauncherService);
private readonly bookDialogHelperService = inject(BookDialogHelperService);
readonly isRouteActive = computed(() => {
const route = this.item?.routerLink?.[0];
if (!route) return false;
return this.menuService.currentPath() === route;
});
readonly canManipulateLibrary = computed(() =>
this.userService.currentUser()?.permissions.canManageLibrary ?? false
);
readonly admin = computed(() =>
this.userService.currentUser()?.permissions.admin ?? false
);
ngOnInit() {
const rootKey = this.menuKey ? this.menuKey + '-' : '';
this.key = this.parentKey ? this.parentKey + '-' + this.index : rootKey + String(this.index);
}
toggleExpand() {
this.expanded = !this.expanded;
}
openDialog(item: NavItem) {
if (item.type === 'library' && this.canManipulateLibrary()) {
this.dialogLauncher.openLibraryCreateDialog();
}
if (item.type === 'magicShelf') {
this.dialogLauncher.openMagicShelfCreateDialog();
}
if (item.type === 'shelf') {
this.bookDialogHelperService.openShelfCreatorDialog();
}
}
formatCount(count: number | null | undefined): string {
if (count == null) return '0';
if (count >= 1000) return Math.floor(count / 1000) + 'K';
return count.toString();
}
getIconSelection(): IconSelection | null {
if (!this.item.icon) return null;
return {
type: this.item.iconType || 'PRIME_NG',
value: this.item.icon
};
}
hasContextMenu(): boolean {
return (this.item.contextMenuItems?.length ?? 0) > 0;
}
shouldShowContextMenuButton(): boolean {
return this.hasContextMenu()
&& (this.item.type !== 'library' || (this.admin() || this.canManipulateLibrary()));
}
}
@@ -0,0 +1,211 @@
import { describe, expect, it, vi } from 'vitest';
import { Library } from '../../../features/book/model/library.model';
import { Shelf } from '../../../features/book/model/shelf.model';
import { MagicShelf } from '../../../features/magic-shelf/service/magic-shelf.service';
import { normalizeSortPref } from '../sidebar-sort-preferences';
import {
buildHomeSection,
buildLibrarySection,
buildMagicShelfSection,
buildShelfSection,
} from './sidebar-sections';
const translate = (key: string): string => key;
function library(overrides: Partial<Library> & { name: string }): Library {
return { paths: [], watch: false, ...overrides };
}
function shelf(overrides: Partial<Shelf> & { name: string }): Shelf {
return { ...overrides };
}
function magicShelf(overrides: Partial<MagicShelf> & { name: string }): MagicShelf {
return { filterJson: '{}', ...overrides };
}
const libraryDeps = {
health: { isUnhealthy: (id: number) => id === 99 },
menuItems: { initializeLibraryMenuItems: vi.fn(() => []) },
};
const shelfDeps = {
menuItems: { initializeShelfMenuItems: vi.fn(() => []) },
};
const magicShelfDeps = {
menuItems: { initializeMagicShelfMenuItems: vi.fn(() => []) },
};
describe('normalizeSortPref', () => {
it('defaults to name/asc and only honors known field/order values', () => {
expect(normalizeSortPref({}, { field: 'name', order: 'asc' })).toEqual({ field: 'name', order: 'asc' });
expect(normalizeSortPref({ field: 'id', order: 'desc' }, { field: 'name', order: 'asc' })).toEqual({ field: 'id', order: 'desc' });
expect(normalizeSortPref({ field: 'bogus', order: 'sideways' }, { field: 'name', order: 'asc' })).toEqual({ field: 'name', order: 'asc' });
});
});
describe('buildHomeSection', () => {
it('emits the standard home items and attaches counts only to counted entries', () => {
const [section] = buildHomeSection(translate, { allBooks: 12, series: 3, authors: 7 });
expect(section.id).toBe('home');
expect(section.expandable).toBe(true);
expect(section.items?.map((item) => item.id)).toEqual([
'dashboard', 'allBooks', 'series', 'authors', 'notebook',
]);
const counts = Object.fromEntries(
(section.items ?? []).map((item) => [item.id, item.bookCount]),
);
expect(counts).toEqual({
dashboard: undefined,
allBooks: 12,
series: 3,
authors: 7,
notebook: undefined,
});
});
});
describe('buildLibrarySection', () => {
it('returns no section when no libraries are persisted', () => {
expect(buildLibrarySection([], new Map(), { field: 'name', order: 'asc' }, translate, libraryDeps)).toEqual([]);
expect(buildLibrarySection(
[library({ name: 'pending' })],
new Map(),
{ field: 'name', order: 'asc' },
translate,
libraryDeps,
)).toEqual([]);
});
it('sorts ascending and descending by name', () => {
const libs = [
library({ id: 1, name: 'Charlie' }),
library({ id: 2, name: 'Alpha' }),
library({ id: 3, name: 'Bravo' }),
];
const asc = buildLibrarySection(libs, new Map(), { field: 'name', order: 'asc' }, translate, libraryDeps);
expect(asc[0].items?.map((item) => item.label)).toEqual(['Alpha', 'Bravo', 'Charlie']);
const desc = buildLibrarySection(libs, new Map(), { field: 'name', order: 'desc' }, translate, libraryDeps);
expect(desc[0].items?.map((item) => item.label)).toEqual(['Charlie', 'Bravo', 'Alpha']);
});
it('sorts by id when requested', () => {
const libs = [
library({ id: 3, name: 'Gamma' }),
library({ id: 1, name: 'Alpha' }),
library({ id: 2, name: 'Beta' }),
];
const result = buildLibrarySection(libs, new Map(), { field: 'id', order: 'asc' }, translate, libraryDeps);
expect(result[0].items?.map((item) => item.id)).toEqual(['library:1', 'library:2', 'library:3']);
});
it('renders each library with route, count, health, and icon metadata', () => {
const libs = [library({ id: 5, name: 'Fiction', icon: 'pi-book', iconType: 'PRIME_NG' })];
const counts = new Map([[5, 42]]);
const [section] = buildLibrarySection(libs, counts, { field: 'name', order: 'asc' }, translate, libraryDeps);
expect(section.items?.[0]).toMatchObject({
id: 'library:5',
label: 'Fiction',
type: 'library',
icon: 'pi-book',
iconType: 'PRIME_NG',
routerLink: ['/library/5/books'],
bookCount: 42,
unhealthy: false,
});
});
it('flags unhealthy libraries via the injected health service', () => {
const libs = [library({ id: 99, name: 'Broken' })];
const [section] = buildLibrarySection(libs, new Map(), { field: 'name', order: 'asc' }, translate, libraryDeps);
expect(section.items?.[0].unhealthy).toBe(true);
});
});
describe('buildShelfSection', () => {
const sort = { field: 'name', order: 'asc' } as const;
it('renders Unshelved even when no shelves are persisted', () => {
const [section] = buildShelfSection([], new Map(), 5, sort, translate, shelfDeps);
expect(section.items).toEqual([
expect.objectContaining({
id: 'shelfUnshelved',
routerLink: ['/unshelved-books'],
bookCount: 5,
}),
]);
});
it('always renders Unshelved as the first item when shelves exist', () => {
const shelves = [shelf({ id: 1, name: 'Reading' })];
const [section] = buildShelfSection(shelves, new Map(), 9, sort, translate, shelfDeps);
expect(section.items?.[0]).toMatchObject({
id: 'shelfUnshelved',
routerLink: ['/unshelved-books'],
bookCount: 9,
});
});
it('pins the Kobo shelf directly after Unshelved when marked as the system shelf', () => {
const shelves = [
shelf({ id: 1, name: 'Reading' }),
shelf({ id: 2, name: 'Kobo', systemKey: 'kobo' }),
shelf({ id: 3, name: 'Archive' }),
];
const [section] = buildShelfSection(shelves, new Map(), 0, sort, translate, shelfDeps);
expect(section.items?.map((item) => item.label))
.toEqual(['layout.menu.unshelved', 'Kobo', 'Archive', 'Reading']);
});
it('keeps the standard ordering when no shelf is marked for pinning', () => {
const shelves = [
shelf({ id: 1, name: 'Reading' }),
shelf({ id: 2, name: 'Kobo' }),
shelf({ id: 3, name: 'Archive' }),
];
const [section] = buildShelfSection(shelves, new Map(), 0, sort, translate, shelfDeps);
expect(section.items?.map((item) => item.label))
.toEqual(['layout.menu.unshelved', 'Archive', 'Kobo', 'Reading']);
});
});
describe('buildMagicShelfSection', () => {
const sort = { field: 'name', order: 'asc' } as const;
it('returns no section when no magic shelves are persisted', () => {
expect(buildMagicShelfSection([], new Map(), sort, translate, magicShelfDeps)).toEqual([]);
});
it('renders sorted magic shelves with route, icon, and count', () => {
const shelves = [
magicShelf({ id: 2, name: 'Beta', icon: 'pi-sparkles', iconType: 'PRIME_NG' }),
magicShelf({ id: 1, name: 'Alpha' }),
];
const counts = new Map([[1, 4], [2, 7]]);
const [section] = buildMagicShelfSection(shelves, counts, sort, translate, magicShelfDeps);
expect(section.items).toEqual([
expect.objectContaining({
id: 'magicShelf:1', label: 'Alpha', routerLink: ['/magic-shelf/1/books'], bookCount: 4,
}),
expect.objectContaining({
id: 'magicShelf:2', label: 'Beta', icon: 'pi-sparkles', iconType: 'PRIME_NG',
routerLink: ['/magic-shelf/2/books'], bookCount: 7,
}),
]);
});
});
@@ -0,0 +1,186 @@
import { Library } from '../../../features/book/model/library.model';
import { Shelf } from '../../../features/book/model/shelf.model';
import { MagicShelf } from '../../../features/magic-shelf/service/magic-shelf.service';
import { LibraryHealthService } from '../../../features/book/service/library-health.service';
import { LibraryShelfMenuService } from '../../../features/book/service/library-shelf-menu.service';
import { SortPref } from '../sidebar-sort-preferences';
import { SidebarLeaf, SidebarSection } from '../navigation/nav-item.model';
import { buildHomeNavItems } from '../navigation/nav-catalog';
export interface HomeCounts {
allBooks: number;
series: number;
authors: number;
}
export interface LibrarySectionDeps {
health: Pick<LibraryHealthService, 'isUnhealthy'>;
menuItems: Pick<LibraryShelfMenuService, 'initializeLibraryMenuItems'>;
}
export interface ShelfSectionDeps {
menuItems: Pick<LibraryShelfMenuService, 'initializeShelfMenuItems'>;
}
export interface MagicShelfSectionDeps {
menuItems: Pick<LibraryShelfMenuService, 'initializeMagicShelfMenuItems'>;
}
type TranslateFn = (key: string) => string;
/**
* The sidebar only renders persisted entities. Models keep `id` optional
* because they double as create-form payloads, so narrow at this boundary
* and drop anything mid-create.
*/
type WithId<T extends { id?: number | null }> = T & { id: number };
function withIds<T extends { id?: number | null }>(items: T[]): WithId<T>[] {
return items.filter((item): item is WithId<T> => item.id != null);
}
function sortByPref<T extends { id: number; name: string }>(items: T[], pref: SortPref): T[] {
const sorted = [...items].sort((a, b) =>
pref.field === 'id' ? a.id - b.id : a.name.localeCompare(b.name)
);
return pref.order === 'desc' ? sorted.reverse() : sorted;
}
export function buildHomeSection(translate: TranslateFn, counts: HomeCounts): SidebarSection[] {
return [{
id: 'home',
menuKey: 'home',
label: translate('layout.menu.home'),
expandable: true,
items: buildHomeNavItems(translate).map((item) => ({
...item,
bookCount: homeItemBookCount(item.id, counts),
})),
}];
}
function homeItemBookCount(itemId: string, counts: HomeCounts): number | undefined {
switch (itemId) {
case 'allBooks': return counts.allBooks;
case 'series': return counts.series;
case 'authors': return counts.authors;
default: return undefined;
}
}
export function buildLibrarySection(
libraries: Library[],
bookCounts: ReadonlyMap<number, number>,
sort: SortPref,
translate: TranslateFn,
deps: LibrarySectionDeps,
): SidebarSection[] {
const sorted = sortByPref(withIds(libraries), sort);
if (sorted.length === 0) return [];
return [{
id: 'libraries',
menuKey: 'library',
label: translate('layout.menu.libraries'),
type: 'library',
expandable: true,
items: sorted.map((library) => ({
id: `library:${library.id}`,
label: library.name,
type: 'library',
icon: library.icon || undefined,
iconType: library.iconType ?? undefined,
routerLink: [`/library/${library.id}/books`],
bookCount: bookCounts.get(library.id) ?? 0,
unhealthy: deps.health.isUnhealthy(library.id),
contextMenuItems: deps.menuItems.initializeLibraryMenuItems(library),
})),
}];
}
export function buildShelfSection(
shelves: Shelf[],
bookCounts: ReadonlyMap<number, number>,
unshelvedCount: number,
sort: SortPref,
translate: TranslateFn,
deps: ShelfSectionDeps,
): SidebarSection[] {
const sorted = sortByPref(withIds(shelves), sort);
const pinnedIndex = sorted.findIndex((shelf) => shelf.systemKey === 'kobo');
const pinned = pinnedIndex === -1 ? null : sorted.splice(pinnedIndex, 1)[0];
const items: SidebarLeaf[] = [{
id: 'shelfUnshelved',
label: translate('layout.menu.unshelved'),
type: 'shelf',
icon: 'pi pi-inbox',
iconType: 'PRIME_NG',
routerLink: ['/unshelved-books'],
bookCount: unshelvedCount,
}];
if (pinned) {
items.push(toShelfNavItem(pinned, bookCounts, deps));
}
for (const shelf of sorted) {
items.push(toShelfNavItem(shelf, bookCounts, deps));
}
return [{
id: 'shelves',
menuKey: 'shelf',
type: 'shelf',
label: translate('layout.menu.shelves'),
expandable: true,
items,
}];
}
function toShelfNavItem(
shelf: WithId<Shelf>,
bookCounts: ReadonlyMap<number, number>,
deps: ShelfSectionDeps,
): SidebarLeaf {
return {
id: `shelf:${shelf.id}`,
label: shelf.name,
type: 'shelf',
icon: shelf.icon || undefined,
iconType: shelf.iconType ?? undefined,
routerLink: [`/shelf/${shelf.id}/books`],
bookCount: bookCounts.get(shelf.id) ?? 0,
contextMenuItems: deps.menuItems.initializeShelfMenuItems(shelf),
};
}
export function buildMagicShelfSection(
shelves: MagicShelf[],
bookCounts: ReadonlyMap<number, number>,
sort: SortPref,
translate: TranslateFn,
deps: MagicShelfSectionDeps,
): SidebarSection[] {
const sorted = sortByPref(withIds(shelves), sort);
if (sorted.length === 0) return [];
return [{
id: 'magicShelves',
menuKey: 'magicShelf',
label: translate('layout.menu.magicShelves'),
type: 'magicShelf',
expandable: true,
items: sorted.map((shelf) => ({
id: `magicShelf:${shelf.id}`,
label: shelf.name,
type: 'magicShelf',
icon: shelf.icon || undefined,
iconType: shelf.iconType ?? undefined,
routerLink: [`/magic-shelf/${shelf.id}/books`],
bookCount: bookCounts.get(shelf.id) ?? 0,
contextMenuItems: deps.menuItems.initializeMagicShelfMenuItems(shelf),
})),
}];
}
@@ -0,0 +1,49 @@
<ng-container *transloco="let t; prefix: 'layout'">
<header class="mobile-topbar">
<button
type="button"
class="mobile-topbar-button"
[attr.aria-label]="t('menu.toggleNavigation')"
(click)="layoutService.onMenuToggle()"
>
<i class="pi pi-bars" aria-hidden="true"></i>
</button>
<div class="mobile-topbar-brand">
<svg class="mobile-topbar-brand-icon" viewBox="0 0 100 126" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
<path d="M25.8062 106.614V113.077V119.537V126L32.2559 119.537L38.7093 126V119.537V113.077V106.614H25.8062Z" fill="white"/>
<path d="M38.7093 29.0758H96.7715C98.5535 29.0758 99.9964 27.6307 99.9964 25.846V3.22984C99.9964 1.44512 98.5535 0 96.7715 0H12.9031C10.5512 0 8.35077 0.63224 6.44975 1.73414C4.49102 2.86856 2.86054 4.50155 1.72787 6.4633C0.631268 8.36363 0 10.5674 0 12.923V106.614C0 113.753 5.7752 119.537 12.9031 119.537H21.1529V113.077H12.9031C9.33915 113.077 6.44975 110.183 6.44975 106.614C6.44975 103.044 9.33915 100.15 12.9031 100.15H93.5466C97.1106 100.15 100 97.2566 100 93.6871V41.9988C100 38.4293 97.1106 35.5355 93.5466 35.5355H38.7093C36.9273 35.5355 35.4845 36.9806 35.4845 38.7653V61.3815C35.4845 63.1662 36.9273 64.6113 38.7093 64.6113H67.7404C69.5224 64.6113 70.9653 66.0564 70.9653 67.8412C70.9653 69.6259 69.5224 71.071 67.7404 71.071H38.7093C33.3634 71.071 29.0311 66.732 29.0311 61.3779V38.7617C29.0311 33.4076 33.3634 29.0686 38.7093 29.0686V29.0758Z" fill="url(#mobile-topbar-brand-primary-gradient)"/>
<path d="M96.7715 113.077H43.5539V119.537H96.7715C98.5535 119.537 99.9964 118.092 99.9964 116.307C99.9964 114.522 98.5535 113.077 96.7715 113.077Z" fill="url(#mobile-topbar-brand-secondary-gradient)"/>
<defs>
<linearGradient id="mobile-topbar-brand-primary-gradient" x1="50" y1="0" x2="50" y2="119.537" gradientUnits="userSpaceOnUse">
<stop offset="0" style="stop-color: var(--primary-300)"/>
<stop offset="1" style="stop-color: var(--primary-500)"/>
</linearGradient>
<linearGradient id="mobile-topbar-brand-secondary-gradient" x1="50" y1="0" x2="50" y2="119.537" gradientUnits="userSpaceOnUse">
<stop offset="0" style="stop-color: var(--primary-300)"/>
<stop offset="1" style="stop-color: var(--primary-500)"/>
</linearGradient>
</defs>
</svg>
<span class="mobile-topbar-brand-text">Grimmory</span>
</div>
@if (commandPaletteService.isOpen()) {
<button
type="button"
class="mobile-topbar-button"
[attr.aria-label]="'common.close' | transloco"
(click)="closeSearch()"
>
<i class="pi pi-times" aria-hidden="true"></i>
</button>
} @else {
<button
type="button"
class="mobile-topbar-button"
[attr.aria-label]="t('menu.search')"
(click)="openSearch()"
>
<i class="pi pi-search" aria-hidden="true"></i>
</button>
}
</header>
</ng-container>
@@ -0,0 +1,81 @@
:host {
display: contents;
}
.mobile-topbar {
display: none;
position: fixed;
top: 0;
left: 0;
right: 0;
height: 3.5rem;
z-index: 100;
background-color: var(--app-background);
border-bottom: 1px solid var(--content-border-color);
padding: 0 0.75rem;
align-items: center;
justify-content: space-between;
gap: 0.5rem;
}
.mobile-topbar-brand {
display: flex;
align-items: center;
justify-content: center;
flex: 1 1 auto;
min-width: 0;
gap: 0.4rem;
color: var(--text-color);
}
.mobile-topbar-brand-icon {
width: auto;
height: 1.75rem;
flex-shrink: 0;
transform: translateY(1px);
}
.mobile-topbar-brand-text {
font-size: 1.25rem;
font-weight: 600;
line-height: 1;
white-space: nowrap;
}
.mobile-topbar-button {
flex-shrink: 0;
}
.mobile-topbar-button {
display: inline-flex;
align-items: center;
justify-content: center;
width: 2.5rem;
height: 2.5rem;
padding: 0;
border: 0;
background: none;
border-radius: 6px;
color: var(--text-color);
cursor: pointer;
transition: background-color 0.15s ease, color 0.15s ease;
&:hover {
background-color: var(--surface-hover);
}
&:focus-visible {
outline: 2px solid var(--primary-color);
outline-offset: 2px;
}
i {
font-size: 1.25rem;
}
}
@media (width <= 991px) {
.mobile-topbar {
display: flex;
}
}
@@ -0,0 +1,81 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { signal } from '@angular/core';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { getTranslocoModule } from '../../../core/testing/transloco-testing';
import { CommandPaletteService } from '../../../features/command-palette/command-palette.service';
import { LayoutService } from '../layout.service';
import { AppMobileTopbarComponent } from './app.mobile-topbar.component';
describe('AppMobileTopbarComponent', () => {
let fixture: ComponentFixture<AppMobileTopbarComponent>;
let component: AppMobileTopbarComponent;
let layoutService: {
closeMobileSidebar: ReturnType<typeof vi.fn>;
onMenuToggle: ReturnType<typeof vi.fn>;
};
let commandPaletteService: {
open: ReturnType<typeof vi.fn>;
hide: ReturnType<typeof vi.fn>;
toggle: ReturnType<typeof vi.fn>;
isOpen: ReturnType<typeof signal>;
query: ReturnType<typeof signal>;
visibleItems: ReturnType<typeof signal>;
groups: ReturnType<typeof signal>;
};
beforeEach(() => {
layoutService = {
closeMobileSidebar: vi.fn(),
onMenuToggle: vi.fn(),
};
commandPaletteService = {
open: vi.fn(),
hide: vi.fn(),
toggle: vi.fn(),
isOpen: signal(false),
query: signal(''),
visibleItems: signal([]),
groups: signal([]),
};
TestBed.configureTestingModule({
imports: [AppMobileTopbarComponent, getTranslocoModule()],
providers: [
{ provide: LayoutService, useValue: layoutService },
{ provide: CommandPaletteService, useValue: commandPaletteService },
],
});
fixture = TestBed.createComponent(AppMobileTopbarComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('opens the command palette and closes the mobile sidebar when search is pressed', () => {
component.openSearch();
expect(layoutService.closeMobileSidebar).toHaveBeenCalledOnce();
expect(commandPaletteService.open).toHaveBeenCalledOnce();
});
it('shows the search icon when the palette is closed', () => {
commandPaletteService.isOpen.set(false);
fixture.detectChanges();
const icon = fixture.nativeElement.querySelector('.mobile-topbar button:last-of-type i');
expect(icon?.classList.contains('pi-search')).toBe(true);
});
it('swaps to a close button that hides the palette when it is open', () => {
commandPaletteService.isOpen.set(true);
fixture.detectChanges();
const button = fixture.nativeElement.querySelector('.mobile-topbar button:last-of-type') as HTMLButtonElement;
const icon = button.querySelector('i');
expect(icon?.classList.contains('pi-times')).toBe(true);
button.click();
expect(commandPaletteService.hide).toHaveBeenCalledOnce();
});
});
@@ -0,0 +1,24 @@
import { Component, inject } from '@angular/core';
import { TranslocoDirective, TranslocoPipe } from '@jsverse/transloco';
import { CommandPaletteService } from '../../../features/command-palette/command-palette.service';
import { LayoutService } from '../layout.service';
@Component({
selector: 'app-mobile-topbar',
templateUrl: './app.mobile-topbar.component.html',
styleUrl: './app.mobile-topbar.component.scss',
imports: [TranslocoDirective, TranslocoPipe],
})
export class AppMobileTopbarComponent {
readonly layoutService = inject(LayoutService);
protected readonly commandPaletteService = inject(CommandPaletteService);
openSearch(): void {
this.layoutService.closeMobileSidebar();
this.commandPaletteService.open();
}
closeSearch(): void {
this.commandPaletteService.hide();
}
}
@@ -1,319 +0,0 @@
<ng-container *transloco="let t; prefix: 'layout.topbar'">
<div class="layout-topbar">
<a class="layout-topbar-logo topbar-logo" routerLink="">
<svg class="logo-icon half-title" viewBox="0 0 100 126" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M25.8062 106.614V113.077V119.537V126L32.2559 119.537L38.7093 126V119.537V113.077V106.614H25.8062Z" fill="white"/>
<path d="M38.7093 29.0758H96.7715C98.5535 29.0758 99.9964 27.6307 99.9964 25.846V3.22984C99.9964 1.44512 98.5535 0 96.7715 0H12.9031C10.5512 0 8.35077 0.63224 6.44975 1.73414C4.49102 2.86856 2.86054 4.50155 1.72787 6.4633C0.631268 8.36363 0 10.5674 0 12.923V106.614C0 113.753 5.7752 119.537 12.9031 119.537H21.1529V113.077H12.9031C9.33915 113.077 6.44975 110.183 6.44975 106.614C6.44975 103.044 9.33915 100.15 12.9031 100.15H93.5466C97.1106 100.15 100 97.2566 100 93.6871V41.9988C100 38.4293 97.1106 35.5355 93.5466 35.5355H38.7093C36.9273 35.5355 35.4845 36.9806 35.4845 38.7653V61.3815C35.4845 63.1662 36.9273 64.6113 38.7093 64.6113H67.7404C69.5224 64.6113 70.9653 66.0564 70.9653 67.8412C70.9653 69.6259 69.5224 71.071 67.7404 71.071H38.7093C33.3634 71.071 29.0311 66.732 29.0311 61.3779V38.7617C29.0311 33.4076 33.3634 29.0686 38.7093 29.0686V29.0758Z" fill="url(#grimmory-logo-topbar-primary-gradient)"/>
<path d="M96.7715 113.077H43.5539V119.537H96.7715C98.5535 119.537 99.9964 118.092 99.9964 116.307C99.9964 114.522 98.5535 113.077 96.7715 113.077Z" fill="url(#grimmory-logo-topbar-primary-gradient-secondary)"/>
<defs>
<linearGradient id="grimmory-logo-topbar-primary-gradient" x1="50" y1="0" x2="50" y2="119.537" gradientUnits="userSpaceOnUse">
<stop offset="0" style="stop-color: var(--p-primary-300)"/>
<stop offset="1" style="stop-color: var(--p-primary-500)"/>
</linearGradient>
<linearGradient id="grimmory-logo-topbar-primary-gradient-secondary" x1="50" y1="0" x2="50" y2="119.537" gradientUnits="userSpaceOnUse">
<stop offset="0" style="stop-color: var(--p-primary-300)"/>
<stop offset="1" style="stop-color: var(--p-primary-500)"/>
</linearGradient>
</defs>
</svg>
<span class="logo-text">Grimmory</span>
</a>
<button
type="button"
class="layout-menu-button"
[attr.aria-label]="t('toggleNavigation')"
(click)="toggleMenu()"
[ngClass]="{ 'rotate-right': !isMenuVisible, 'rotate-left': isMenuVisible }"
>
<i class="pi pi-bars" aria-hidden="true"></i>
</button>
<div class="topbar-content">
<app-book-searcher class="topbar-search"></app-book-searcher>
<ul class="topbar-items topbar-desktop-items">
<div class="topbar-action-group">
@if (user(); as currentUser) {
@if (currentUser.permissions.canAccessBookdrop || currentUser.permissions.admin) {
<li>
<button type="button" class="topbar-item" (click)="navigateToBookdrop()" [pTooltip]="t('bookdrop')" tooltipPosition="bottom">
<i class="pi pi-inbox topbar-icon"></i>
</button>
</li>
}
@if (currentUser.permissions.canManageLibrary || currentUser.permissions.admin) {
<li>
<button type="button" class="topbar-item" (click)="openLibraryCreatorDialog()" [pTooltip]="t('createNewLibrary')" tooltipPosition="bottom">
<i class="pi pi-plus-circle topbar-icon"></i>
</button>
</li>
}
@if (currentUser.permissions.canUpload || currentUser.permissions.admin) {
<li>
<button type="button" class="topbar-item" (click)="openFileUploadDialog()" [pTooltip]="t('uploadBook')" tooltipPosition="bottom">
<i class="pi pi-upload topbar-icon"></i>
</button>
</li>
}
}
@if (hasStatsAccess) {
<li>
<button
type="button"
class="topbar-item"
(click)="shouldShowStatsMenu ? statsMenu?.toggle($event) : handleStatsButtonClick()"
[pTooltip]="statsTooltip"
tooltipPosition="bottom">
<svg class="multi-color-chart-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" style="width: 1.25rem; height: 1.25rem;">
<rect x="2" y="13" width="4" height="9" rx="1" fill="#ef4444"/>
<rect x="7.5" y="3" width="4" height="19" rx="1" fill="#f59e0b"/>
<rect x="13" y="9" width="4" height="13" rx="1" fill="#3b82f6"/>
<rect x="18.5" y="5" width="4" height="17" rx="1" fill="#10b981"/>
</svg>
</button>
@if (shouldShowStatsMenu) {
<p-menu #statsMenu [model]="statsMenuItems" [popup]="true" appendTo="body"/>
}
</li>
}
@if (user(); as currentUser) {
@if (currentUser.permissions.canManageLibrary || currentUser.permissions.admin) {
<li>
<button type="button" class="topbar-item" (click)="navigateToMetadataManager()" [pTooltip]="t('metadataManager')" tooltipPosition="bottom">
<i class="pi pi-sparkles topbar-icon"></i>
</button>
</li>
}
}
<li>
<button type="button" class="topbar-item" (click)="navigateToSettings()" [pTooltip]="t('settings')" tooltipPosition="bottom">
<i class="pi pi-cog topbar-icon"></i>
</button>
</li>
</div>
<p-divider layout="vertical"/>
<div class="topbar-action-group">
<li class="topbar-item-relative">
<button
type="button"
class="topbar-item"
(click)="notificationPopover.toggle($event)"
>
<i
class="pi"
[ngClass]="iconClass"
[ngStyle]="{ color: iconColor }"
style="font-size: 1.25rem"
[class.pulsating]="iconPulsating"
[attr.aria-label]="t('notificationAriaLabel')"
></i>
</button>
@if (shouldShowNotificationBadge) {
<span class="notification-badge">{{ completedTaskCount }}</span>
}
<p-popover #notificationPopover>
<app-unified-notification-popover-component></app-unified-notification-popover-component>
</p-popover>
</li>
<li class="topbar-item-relative">
<button
type="button"
class="topbar-item"
(click)="langMenu.toggle($event)"
[pTooltip]="t('language')"
tooltipPosition="bottom">
<i class="pi pi-language topbar-icon"></i>
</button>
<p-menu #langMenu [model]="langMenuItems" [popup]="true" appendTo="body"/>
</li>
<li class="topbar-item-relative">
<button type="button"
class="topbar-item config-item"
enterActiveClass="animate-scalein"
enterFromClass="hidden"
leaveActiveClass="animate-fadeout"
leaveToClass="hidden"
pStyleClass="@next" [hideOnOutsideClick]="true">
<i class="pi pi-palette"></i>
</button>
<app-theme-configurator></app-theme-configurator>
</li>
</div>
<p-divider layout="vertical"/>
<div class="topbar-action-group">
<li>
<a class="topbar-item"
href="https://grimmory.org/docs/getting-started"
target="_blank"
rel="noopener noreferrer"
[pTooltip]="t('documentation')"
tooltipPosition="bottom">
<i class="pi pi-info-circle topbar-icon"></i>
</a>
</li>
<!-- Show Profile only to non-demo users -->
@if (user(); as currentUser) {
@if (!currentUser.permissions.demoUser) {
<li>
<button type="button" class="topbar-item" (click)="openUserProfileDialog()" [pTooltip]="t('profile')" tooltipPosition="bottom">
<i class="pi pi-user topbar-icon"></i>
</button>
</li>
}
}
<li>
<button type="button" class="topbar-item" (click)="logout()" [pTooltip]="t('logout')" tooltipPosition="left">
<i class="pi pi-sign-out topbar-icon"></i>
</button>
</li>
</div>
</ul>
<!-- Trigger Button -->
<div class="mobile-trigger">
<button
type="button"
class="mobile-menu-trigger"
[attr.aria-label]="t('toggleNavigation')"
(click)="mobileMenu.toggle($event)"
>
<i class="pi pi-ellipsis-v" aria-hidden="true"></i>
</button>
<p-popover #mobileMenu>
<ul class="mobile-menu-list">
@if (user(); as currentUser) {
@if (currentUser.permissions.canAccessBookdrop || currentUser.permissions.admin) {
<li>
<button
class="mobile-menu-item"
(click)="navigateToBookdrop(); mobileMenu.hide()"
>
<i class="pi pi-inbox topbar-icon"></i>
{{ t('bookdrop') }}
</button>
</li>
}
@if (currentUser.permissions.canManageLibrary || currentUser.permissions.admin) {
<li>
<button
class="mobile-menu-item"
(click)="openLibraryCreatorDialog(); mobileMenu.hide()"
>
<i class="pi pi-plus-circle topbar-icon"></i>
{{ t('createLibrary') }}
</button>
</li>
}
@if (currentUser.permissions.canUpload || currentUser.permissions.admin) {
<li>
<button
class="mobile-menu-item"
(click)="openFileUploadDialog(); mobileMenu.hide()"
>
<i class="pi pi-upload topbar-icon"></i>
{{ t('uploadBook') }}
</button>
</li>
}
@if (currentUser.permissions.canAccessLibraryStats || currentUser.permissions.admin) {
<li>
<button
class="mobile-menu-item"
(click)="navigateToStats(); mobileMenu.hide()"
>
<i class="pi pi-chart-line topbar-icon"></i>
{{ t('libraryStats') }}
</button>
</li>
}
@if (currentUser.permissions.canAccessUserStats || currentUser.permissions.admin) {
<li>
<button
class="mobile-menu-item"
(click)="navigateToUserStats(); mobileMenu.hide()"
>
<i class="pi pi-users topbar-icon"></i>
{{ t('readingStats') }}
</button>
</li>
}
@if (currentUser.permissions.canManageLibrary || currentUser.permissions.admin) {
<li>
<button
class="mobile-menu-item"
(click)="navigateToMetadataManager(); mobileMenu.hide()"
>
<i class="pi pi-sparkles topbar-icon"></i>
{{ t('metadataManager') }}
</button>
</li>
}
}
<li>
<button
class="mobile-menu-item"
(click)="navigateToSettings(); mobileMenu.hide()"
>
<i class="pi pi-cog topbar-icon"></i>
{{ t('settings') }}
</button>
</li>
<li>
<a
class="mobile-menu-item"
href="https://grimmory.org/docs/getting-started"
target="_blank"
rel="noopener noreferrer">
<i class="pi pi-info-circle topbar-icon"></i>
{{ t('documentation') }}
</a>
</li>
<li>
<button
type="button"
class="mobile-menu-item"
(click)="langMenuMobile.toggle($event)"
>
<i class="pi pi-language topbar-icon"></i>
{{ t('language') }}
</button>
<p-menu #langMenuMobile [model]="langMenuItems" [popup]="true"/>
</li>
@if (user(); as currentUser) {
@if (!currentUser.permissions.demoUser) {
<li>
<button
class="mobile-menu-item"
(click)="openUserProfileDialog(); mobileMenu.hide()"
>
<i class="pi pi-user topbar-icon"></i>
{{ t('profile') }}
</button>
</li>
}
}
<li>
<button
class="mobile-menu-item"
(click)="logout(); mobileMenu.hide()"
>
<i class="pi pi-sign-out topbar-icon"></i>
{{ t('logout') }}
</button>
</li>
</ul>
</p-popover>
</div>
</div>
</div>
</ng-container>
@@ -1,271 +0,0 @@
.layout-topbar-logo.topbar-logo {
width: var(--sidebar-width, 225px);
min-width: var(--sidebar-width, 225px);
justify-content: flex-start;
padding-left: 2.05rem;
padding-right: 0;
gap: 0.75rem;
}
.logo-text {
font-size: 1.875rem;
line-height: 2.25rem;
margin: 0;
}
.logo-icon {
width: auto;
height: 2rem;
flex-shrink: 0;
transform: translateY(1px);
}
.topbar-content {
display: flex;
align-items: center;
width: 100%;
min-width: 0;
gap: 1rem;
@media (width <= 767px) {
gap: 0.5rem;
}
}
.topbar-search {
flex-grow: 1;
min-width: 0;
}
.topbar-desktop-items {
display: none;
align-items: center;
gap: 0.75rem;
margin-left: auto;
padding-left: 1rem;
@media (width >= 768px) {
display: flex;
}
}
.topbar-action-group {
display: flex;
gap: 1rem;
}
.topbar-icon {
color: var(--surface-100);
}
.topbar-item-relative {
position: relative;
}
.heart-button {
overflow: visible;
cursor: pointer;
position: relative;
&:hover .heart-icon {
animation: heartbeat 0.6s ease-in-out;
filter: drop-shadow(0 0 8px rgb(236 72 153 / 80%));
}
&:hover .heart-ripple {
animation: ripple-burst 1.2s ease-out infinite;
}
&:hover .heart-ripple-delayed {
animation-delay: 0.4s;
}
}
.heart-ripple {
position: absolute;
z-index: -1;
inset: 0;
border-radius: 50%;
border: 1.5px solid #ec4899;
opacity: 0;
pointer-events: none;
}
.heart-orbit {
position: absolute;
z-index: 11;
width: 4px;
height: 4px;
border-radius: 50%;
pointer-events: none;
top: calc(50% - 2px);
left: calc(50% - 2px);
}
.heart-orbit-1 {
background: #f472b6;
box-shadow: 0 0 10px #f472b6, 0 0 4px #f472b6;
animation: orbit-1 2.5s linear infinite;
}
.heart-orbit-2 {
background: #a78bfa;
box-shadow: 0 0 10px #a78bfa, 0 0 4px #a78bfa;
animation: orbit-2 3.2s linear infinite reverse;
}
.heart-orbit-3 {
background: #38bdf8;
box-shadow: 0 0 10px #38bdf8, 0 0 4px #38bdf8;
animation: orbit-3 4s linear infinite;
}
.heart-icon {
z-index: 10;
color: #e8366d !important;
font-size: 1.05rem;
animation: heart-float 2.5s ease-in-out infinite;
filter: drop-shadow(0 0 6px rgb(232 54 109 / 80%));
transition: filter 0.3s;
}
.heart-button-static {
.heart-icon {
animation: none;
filter: none;
}
&:hover .heart-icon {
animation: none;
filter: none;
}
}
.mobile-trigger {
display: none;
position: relative;
margin-left: auto;
@media (width <= 767px) {
display: block;
}
}
.mobile-menu-list {
display: flex;
flex-direction: column;
gap: 0.25rem;
width: 12rem;
}
.mobile-menu-item {
display: flex;
align-items: center;
gap: 0.5rem;
width: 100%;
text-align: left;
padding: 0.5rem;
border-radius: 0.25rem;
background: none;
border: none;
color: inherit;
font: inherit;
cursor: pointer;
text-decoration: none;
&:hover {
background: var(--surface-700);
}
}
.highlight {
color: red !important;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.spin {
animation: spin 1.5s linear infinite;
}
@keyframes orbit-1 {
0% { transform: rotate(0deg) translateX(16px) rotate(0deg); }
100% { transform: rotate(360deg) translateX(16px) rotate(-360deg); }
}
@keyframes orbit-2 {
0% { transform: rotate(120deg) translateX(14px) rotate(-120deg); }
100% { transform: rotate(480deg) translateX(14px) rotate(-480deg); }
}
@keyframes orbit-3 {
0% { transform: rotate(240deg) translateX(18px) rotate(-240deg); }
100% { transform: rotate(600deg) translateX(18px) rotate(-600deg); }
}
@keyframes ripple-burst {
0% {
transform: scale(0.8);
opacity: 0.6;
}
100% {
transform: scale(2.2);
opacity: 0;
}
}
@keyframes heart-float {
0%, 100% { transform: translateY(1px); }
50% { transform: translateY(-1px); }
}
@keyframes heartbeat {
0% { transform: scale(1); }
25% { transform: scale(1.35); }
40% { transform: scale(0.95); }
55% { transform: scale(1.2); }
100% { transform: scale(1); }
}
@keyframes pulsate {
0% {
transform: scale(1);
opacity: 1;
}
50% {
transform: scale(1.25);
opacity: 0.8;
}
100% {
transform: scale(1);
opacity: 1;
}
}
.pulsating {
animation: pulsate 1.5s infinite ease-in-out;
}
.notification-badge {
position: absolute;
top: -0.4rem;
right: -0.4rem;
background-color: red;
color: white;
border-radius: 50%;
width: 1.2rem;
height: 1.2rem;
font-size: 0.75rem;
font-weight: 600;
display: flex;
align-items: center;
justify-content: center;
pointer-events: none;
user-select: none;
}
@@ -1,17 +0,0 @@
import {describe, it} from 'vitest';
// NOTE(frontend-seam): Real topbar coverage needs a dedicated host harness for view queries,
// timer-driven pulse behavior, router navigation, auth/logout, user-permission signals,
// metadata/bookdrop streams, menu overlays, and transloco language switching. In the current
// shape those concerns are fused tightly enough that a shallow spec would be noisy and dishonest.
describe.skip('AppTopBarComponent', () => {
it('needs a host-view seam to verify menu visibility, pulse state, and notification/task aggregation', () => {
// TODO(seam): Cover timer-driven pulse resets, task counts, and bookdrop visibility after
// the component exposes a narrower facade over its view and timer dependencies.
});
it('needs a navigation and language seam to verify route actions and active language switching', () => {
// TODO(seam): Cover router commands, stats menu composition, and localStorage language writes
// once those side effects can be driven without mocking the entire topbar runtime.
});
});
@@ -1,311 +0,0 @@
import { Component, DestroyRef, effect, inject, OnDestroy, ViewChild } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { LayoutService } from '../layout.service';
import { Router, RouterLink } from '@angular/router';
import { Tooltip } from 'primeng/tooltip';
import { FormsModule } from '@angular/forms';
import { BookSearcherComponent } from '../../../features/book/components/book-searcher/book-searcher.component';
import { NgClass, NgStyle } from '@angular/common';
import { NotificationEventService } from '../../websocket/notification-event.service';
import { StyleClass } from 'primeng/styleclass';
import { Divider } from 'primeng/divider';
import { ThemeConfiguratorComponent } from '../theme-configurator/theme-configurator.component';
import { AuthService } from '../../service/auth.service';
import { UserService } from '../../../features/settings/user-management/user.service';
import { Popover } from 'primeng/popover';
import { MetadataProgressService } from '../../service/metadata-progress.service';
import { MetadataBatchProgressNotification } from '../../model/metadata-batch-progress.model';
import { BookdropFileService } from '../../../features/bookdrop/service/bookdrop-file.service';
import { DialogLauncherService } from '../../services/dialog-launcher.service';
import { UnifiedNotificationBoxComponent } from '../../components/unified-notification-popover/unified-notification-popover-component';
import { Severity, LogNotification } from '../../websocket/model/log-notification.model';
import { Menu } from 'primeng/menu';
import { TranslocoDirective, TranslocoService } from '@jsverse/transloco';
import { AVAILABLE_LANGS, LANG_LABELS } from '../../../core/config/transloco-loader';
import { LANG_STORAGE_KEY } from '../../../core/config/language-initializer';
import type { MenuItem } from 'primeng/api';
@Component({
selector: 'app-topbar',
templateUrl: './app.topbar.component.html',
styleUrls: ['./app.topbar.component.scss'],
imports: [
RouterLink,
Tooltip,
FormsModule,
BookSearcherComponent,
ThemeConfiguratorComponent,
StyleClass,
NgClass,
Divider,
Popover,
UnifiedNotificationBoxComponent,
NgStyle,
Menu,
TranslocoDirective,
],
})
export class AppTopBarComponent implements OnDestroy {
public readonly layoutService = inject(LayoutService);
protected readonly userService = inject(UserService);
protected readonly user = this.userService.currentUser;
private readonly notificationService = inject(NotificationEventService);
private readonly router = inject(Router);
private readonly authService = inject(AuthService);
private readonly metadataProgressService = inject(MetadataProgressService);
private readonly bookdropFileService = inject(BookdropFileService);
private readonly dialogLauncher = inject(DialogLauncherService);
private readonly translocoService = inject(TranslocoService);
statsMenuItems: MenuItem[] = [];
@ViewChild('statsMenu') statsMenu?: Menu;
isMenuVisible = true;
progressHighlight = false;
completedTaskCount = 0;
hasActiveOrCompletedTasks = false;
showPulse = false;
hasAnyTasks = false;
hasPendingBookdropFiles = false;
private readonly destroyRef = inject(DestroyRef);
private eventTimer: number | undefined;
private latestTasks: Record<string, MetadataBatchProgressNotification> = {};
private latestHasPendingFiles = false;
private latestNotificationSeverity?: Severity;
activeLang = this.translocoService.getActiveLang();
langMenuItems: MenuItem[] = [];
constructor() {
this.langMenuItems = this.buildLanguageActions(this.activeLang);
this.subscribeToMetadataProgress();
this.subscribeToNotifications();
this.destroyRef.onDestroy(() => clearTimeout(this.eventTimer));
this.metadataProgressService.activeTasks$
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((tasks) => {
this.latestTasks = tasks;
this.hasAnyTasks = Object.keys(tasks).length > 0;
this.updateCompletedTaskCount();
this.updateTaskVisibility(tasks);
});
this.bookdropFileService.hasPendingFiles$
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((hasPending) => {
this.latestHasPendingFiles = hasPending;
this.hasPendingBookdropFiles = hasPending;
this.updateCompletedTaskCount();
this.updateTaskVisibilityWithBookdrop();
});
effect(() => {
this.user();
this.initializeStatsMenu();
});
this.translocoService.langChanges$
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(() => {
this.initializeStatsMenu();
});
}
ngOnDestroy(): void {
clearTimeout(this.eventTimer);
}
toggleMenu() {
this.isMenuVisible = !this.isMenuVisible;
this.layoutService.onMenuToggle();
}
openLibraryCreatorDialog(): void {
this.dialogLauncher.openLibraryCreateDialog();
}
openFileUploadDialog(): void {
this.dialogLauncher.openFileUploadDialog();
}
openUserProfileDialog(): void {
this.dialogLauncher.openUserProfileDialog();
}
navigateToSettings() {
this.router.navigate(['/settings']);
}
navigateToBookdrop() {
this.router.navigate(['/bookdrop']);
}
navigateToMetadataManager() {
this.router.navigate(['/metadata-manager']);
}
navigateToStats() {
this.router.navigate(['/library-stats']);
}
navigateToUserStats() {
this.router.navigate(['/reading-stats']);
}
switchLanguage(lang: string) {
if (lang === this.activeLang) return;
this.translocoService.load(lang).pipe(takeUntilDestroyed(this.destroyRef)).subscribe(() => {
this.translocoService.setActiveLang(lang);
localStorage.setItem(LANG_STORAGE_KEY, lang);
this.activeLang = lang;
this.langMenuItems = this.buildLanguageActions(lang);
});
}
logout() {
this.authService.logout();
}
handleStatsButtonClick() {
if (this.statsMenuItems.length === 0) {
return;
}
if (this.statsMenuItems.length === 1) {
this.statsMenuItems[0].command?.({});
}
}
private subscribeToMetadataProgress() {
this.metadataProgressService.progressUpdates$
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((progress) => {
this.progressHighlight = progress.status === 'IN_PROGRESS';
});
}
private subscribeToNotifications() {
this.notificationService.latestNotification$
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((notification: LogNotification) => {
this.latestNotificationSeverity = notification.severity;
this.triggerPulseEffect();
});
}
private triggerPulseEffect() {
this.showPulse = true;
clearTimeout(this.eventTimer);
this.eventTimer = setTimeout(() => {
this.showPulse = false;
}, 4000) as unknown as number;
}
private updateCompletedTaskCount() {
const completedMetadataTasks = Object.values(this.latestTasks).length;
const bookdropFileTaskCount = this.latestHasPendingFiles ? 1 : 0;
this.completedTaskCount = completedMetadataTasks + bookdropFileTaskCount;
}
private updateTaskVisibility(tasks: Record<string, MetadataBatchProgressNotification>) {
this.hasActiveOrCompletedTasks =
this.progressHighlight || this.completedTaskCount > 0 || Object.keys(tasks).length > 0;
this.updateTaskVisibilityWithBookdrop();
}
private updateTaskVisibilityWithBookdrop() {
this.hasActiveOrCompletedTasks = this.hasActiveOrCompletedTasks || this.hasPendingBookdropFiles;
}
private initializeStatsMenu() {
const user = this.user();
const actions: MenuItem[] = [];
if (user?.permissions?.canAccessLibraryStats || user?.permissions?.admin) {
actions.push({
label: this.translocoService.translate('layout.topbar.libraryStats'),
icon: 'pi pi-chart-line',
command: () => this.navigateToStats()
});
}
if (user?.permissions?.canAccessUserStats || user?.permissions?.admin) {
actions.push({
label: this.translocoService.translate('layout.topbar.readingStats'),
icon: 'pi pi-users',
command: () => this.navigateToUserStats()
});
}
this.statsMenuItems = actions;
}
get hasStatsAccess(): boolean {
return this.statsMenuItems.length > 0;
}
get shouldShowStatsMenu(): boolean {
return this.statsMenuItems.length > 1;
}
get statsTooltip(): string {
if (this.statsMenuItems.length === 0) {
return this.translocoService.translate('layout.topbar.stats');
}
if (this.statsMenuItems.length === 1) {
return this.statsMenuItems[0].label || this.translocoService.translate('layout.topbar.stats');
}
return this.translocoService.translate('layout.topbar.stats');
}
get iconClass(): string {
if (this.progressHighlight) return 'pi-spinner spin';
if (this.iconPulsating) return 'pi-wave-pulse';
if (this.completedTaskCount > 0 || this.hasPendingBookdropFiles) return 'pi-bell';
return 'pi-wave-pulse';
}
get iconColor(): string {
if (this.progressHighlight) return 'gold';
if (this.showPulse) {
switch (this.latestNotificationSeverity) {
case Severity.ERROR:
return 'crimson';
case Severity.INFO:
return 'aqua';
case Severity.WARN:
return 'orange';
default:
return 'orange';
}
}
if (this.completedTaskCount > 0 || this.hasPendingBookdropFiles)
return 'limegreen';
return 'inherit';
}
get iconPulsating(): boolean {
return !this.progressHighlight && (this.showPulse);
}
get shouldShowNotificationBadge(): boolean {
return (
(this.completedTaskCount > 0 || this.hasPendingBookdropFiles) &&
!this.progressHighlight &&
!this.showPulse
);
}
private buildLanguageActions(activeLang: string): MenuItem[] {
return AVAILABLE_LANGS.map((lang) => ({
label: LANG_LABELS[lang] || lang,
icon: lang === activeLang ? 'pi pi-check' : undefined,
command: () => this.switchLanguage(lang),
}));
}
}
@@ -1,48 +1,91 @@
import { signal } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { NavigationEnd, Router } from '@angular/router';
import { Subject } from 'rxjs';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { LayoutService } from './layout.service';
import { LocalStorageService } from '../service/local-storage.service';
import { UserService } from '../../features/settings/user-management/user.service';
describe('LayoutService', () => {
let service: LayoutService;
let routerEvents: Subject<unknown>;
const currentUser = signal({
id: 7,
userSettings: {
sidebarLibrarySorting: { field: 'id', order: 'DESC' },
sidebarShelfSorting: { field: 'name', order: 'asc' },
sidebarMagicShelfSorting: { field: 'id', order: 'asc' },
},
} as never);
const updateUserSetting = vi.fn();
const localStorageService = {
get: vi.fn((key: string) => {
if (key === 'sidebarCollapsed') {
return false;
}
if (key === 'sidebarWidth') {
return 225;
}
return null;
}),
set: vi.fn(),
};
beforeEach(() => {
routerEvents = new Subject<unknown>();
TestBed.configureTestingModule({
providers: [LayoutService],
providers: [
LayoutService,
{ provide: LocalStorageService, useValue: localStorageService },
{ provide: UserService, useValue: { currentUser, updateUserSetting } },
{
provide: Router,
useValue: {
url: '/dashboard?tab=recent',
events: routerEvents.asObservable(),
},
},
],
});
service = TestBed.inject(LayoutService);
TestBed.flushEffects();
});
afterEach(() => {
TestBed.resetTestingModule();
vi.restoreAllMocks();
localStorageService.get.mockClear();
localStorageService.set.mockClear();
updateUserSetting.mockClear();
});
it('toggles sidebarOpen on desktop', () => {
it('toggles sidebarVisible on desktop', () => {
vi.spyOn(service, 'isDesktop').mockReturnValue(true);
expect(service.sidebarOpen()).toBe(true);
expect(service.sidebarVisible()).toBe(true);
service.onMenuToggle();
expect(service.sidebarOpen()).toBe(false);
expect(service.sidebarVisible()).toBe(false);
service.onMenuToggle();
expect(service.sidebarOpen()).toBe(true);
expect(service.sidebarVisible()).toBe(true);
});
it('toggles mobileSidebarOpen on mobile', () => {
it('toggles mobileDrawerOpen on mobile', () => {
vi.spyOn(service, 'isDesktop').mockReturnValue(false);
expect(service.mobileSidebarOpen()).toBe(false);
expect(service.mobileDrawerOpen()).toBe(false);
service.onMenuToggle();
expect(service.mobileSidebarOpen()).toBe(true);
expect(service.mobileDrawerOpen()).toBe(true);
service.onMenuToggle();
expect(service.mobileSidebarOpen()).toBe(false);
expect(service.mobileDrawerOpen()).toBe(false);
});
it('closeMobileSidebar resets mobileSidebarOpen to false', () => {
service.mobileSidebarOpen.set(true);
it('closeMobileSidebar resets mobileDrawerOpen to false', () => {
service.mobileDrawerOpen.set(true);
service.closeMobileSidebar();
expect(service.mobileSidebarOpen()).toBe(false);
expect(service.mobileDrawerOpen()).toBe(false);
});
it('updates the document root font size when the scale changes', () => {
@@ -51,4 +94,63 @@ describe('LayoutService', () => {
expect(document.documentElement.style.fontSize).toBe('18px');
});
it('persists the collapsed state when toggled', () => {
expect(service.sidebarCollapsed()).toBe(false);
service.toggleSidebarCollapsed();
expect(service.sidebarCollapsed()).toBe(true);
expect(localStorageService.set).toHaveBeenCalledWith('sidebarCollapsed', true);
});
it('tracks the desktop sidebar collapse transition', () => {
vi.useFakeTimers();
try {
service.isDesktop.set(true);
service.toggleSidebarCollapsed();
expect(service.sidebarTransitioning()).toBe(true);
vi.advanceTimersByTime(220);
expect(service.sidebarTransitioning()).toBe(false);
} finally {
vi.useRealTimers();
}
});
it('hydrates sidebar sort preferences from the current user', () => {
expect(service.librarySort()).toEqual({ field: 'id', order: 'desc' });
expect(service.shelfSort()).toEqual({ field: 'name', order: 'asc' });
expect(service.magicShelfSort()).toEqual({ field: 'id', order: 'asc' });
});
it('persists sidebar sort changes through UserService', () => {
service.setLibrarySort({ field: 'name', order: 'asc' });
expect(service.librarySort()).toEqual({ field: 'name', order: 'asc' });
expect(updateUserSetting).toHaveBeenCalledWith(7, 'sidebarLibrarySorting', { field: 'name', order: 'asc' });
});
it('seeds currentPath from the router URL without query string', () => {
expect(service.currentPath()).toBe('/dashboard');
});
it('updates currentPath on NavigationEnd', () => {
routerEvents.next(new NavigationEnd(1, '/library/1/books', '/library/1/books'));
expect(service.currentPath()).toBe('/library/1/books');
});
it('cleans up global listeners and router events when destroyed', () => {
const removeEventListener = vi.spyOn(window, 'removeEventListener');
TestBed.resetTestingModule();
routerEvents.next(new NavigationEnd(1, '/series', '/series'));
expect(removeEventListener).toHaveBeenCalledWith('resize', expect.any(Function));
expect(service.currentPath()).toBe('/dashboard');
});
});
@@ -1,39 +1,196 @@
import { DOCUMENT } from '@angular/common';
import { effect, inject, Injectable, signal } from '@angular/core';
import { DestroyRef, effect, inject, Injectable, signal, WritableSignal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { NavigationEnd, Router } from '@angular/router';
import { filter } from 'rxjs';
import { UserService } from '../../features/settings/user-management/user.service';
import { LocalStorageService } from '../service/local-storage.service';
import {
DEFAULT_LIBRARY_SORT,
DEFAULT_MAGIC_SHELF_SORT,
DEFAULT_SHELF_SORT,
normalizeSortPref,
SidebarSortPreferenceKey,
SortPref,
sortPrefEqual,
} from './sidebar-sort-preferences';
export const SIDEBAR_MIN_WIDTH = 175;
export const SIDEBAR_MAX_WIDTH = 400;
export const SIDEBAR_DEFAULT_WIDTH = 225;
const SIDEBAR_EXPANDED_STATE_KEY = 'sidebarExpandedState';
const SIDEBAR_TRANSITION_MS = 220;
function readBooleanRecord(storage: LocalStorageService, key: string): Record<string, boolean> {
const stored = storage.get<unknown>(key);
if (!stored || typeof stored !== 'object' || Array.isArray(stored)) {
return {};
}
return Object.fromEntries(
Object.entries(stored).flatMap(([k, v]) =>
typeof v === 'boolean' ? [[k, v] as const] : []
)
);
}
@Injectable({
providedIn: 'root',
})
export class LayoutService {
private readonly document = inject(DOCUMENT);
private readonly localStorage = inject(LocalStorageService);
private readonly userService = inject(UserService, { optional: true });
private readonly router = inject(Router);
private readonly destroyRef = inject(DestroyRef);
readonly scale = signal(14);
readonly sidebarOpen = signal(true);
readonly mobileSidebarOpen = signal(false);
readonly currentPath = signal(this.router.url.split('?')[0]);
readonly sidebarVisible = signal(true);
readonly mobileDrawerOpen = signal(false);
readonly sidebarCollapsed = signal(this.localStorage.get<boolean>('sidebarCollapsed') ?? false);
readonly sidebarWidth = signal(this.clampSidebarWidth(this.localStorage.get<number>('sidebarWidth') ?? SIDEBAR_DEFAULT_WIDTH));
readonly isDesktop = signal(this.computeIsDesktop());
readonly sidebarExpandedState = signal<Readonly<Record<string, boolean>>>(
readBooleanRecord(this.localStorage, SIDEBAR_EXPANDED_STATE_KEY)
);
private readonly _sidebarTransitioning = signal(false);
readonly sidebarTransitioning = this._sidebarTransitioning.asReadonly();
private readonly _librarySort = signal<SortPref>(DEFAULT_LIBRARY_SORT, { equal: sortPrefEqual });
readonly librarySort = this._librarySort.asReadonly();
private readonly _shelfSort = signal<SortPref>(DEFAULT_SHELF_SORT, { equal: sortPrefEqual });
readonly shelfSort = this._shelfSort.asReadonly();
private readonly _magicShelfSort = signal<SortPref>(DEFAULT_MAGIC_SHELF_SORT, { equal: sortPrefEqual });
readonly magicShelfSort = this._magicShelfSort.asReadonly();
private sidebarTransitionTimeoutId: ReturnType<typeof setTimeout> | undefined;
constructor() {
effect(() => {
this.changeScale(this.scale());
});
effect(() => {
const settings = this.userService?.currentUser()?.userSettings;
this._librarySort.set(normalizeSortPref(settings?.sidebarLibrarySorting, DEFAULT_LIBRARY_SORT));
this._shelfSort.set(normalizeSortPref(settings?.sidebarShelfSorting, DEFAULT_SHELF_SORT));
this._magicShelfSort.set(normalizeSortPref(settings?.sidebarMagicShelfSorting, DEFAULT_MAGIC_SHELF_SORT));
});
this.document.defaultView?.addEventListener('resize', this.onResize);
this.destroyRef.onDestroy(() => {
this.document.defaultView?.removeEventListener('resize', this.onResize);
if (this.sidebarTransitionTimeoutId) {
clearTimeout(this.sidebarTransitionTimeoutId);
}
});
this.router.events
.pipe(
filter((event): event is NavigationEnd => event instanceof NavigationEnd),
takeUntilDestroyed(this.destroyRef)
)
.subscribe((event) => {
this.currentPath.set(event.urlAfterRedirects.split('?')[0]);
});
}
onMenuToggle(): void {
if (this.isDesktop()) {
this.sidebarOpen.update((value) => !value);
this.sidebarVisible.update((value) => !value);
} else {
this.mobileSidebarOpen.update((value) => !value);
this.mobileDrawerOpen.update((value) => !value);
}
}
closeMobileSidebar(): void {
this.mobileSidebarOpen.set(false);
toggleSidebarCollapsed(): void {
this.setSidebarCollapsed(!this.sidebarCollapsed());
}
isDesktop(): boolean {
setSidebarWidth(width: number, persist = true): void {
const clamped = this.clampSidebarWidth(width);
this.sidebarWidth.set(clamped);
if (persist) {
this.localStorage.set('sidebarWidth', clamped);
}
}
private clampSidebarWidth(width: number): number {
const rounded = Number.isFinite(width) ? Math.round(width) : SIDEBAR_DEFAULT_WIDTH;
return Math.max(SIDEBAR_MIN_WIDTH, Math.min(SIDEBAR_MAX_WIDTH, rounded));
}
closeMobileSidebar(): void {
this.mobileDrawerOpen.set(false);
}
isSidebarExpanded(key: string, defaultExpanded: boolean): boolean {
const value = this.sidebarExpandedState()[key];
return value === undefined ? defaultExpanded : value;
}
setSidebarExpanded(key: string, expanded: boolean): void {
const next = { ...this.sidebarExpandedState(), [key]: expanded };
this.sidebarExpandedState.set(next);
this.localStorage.set(SIDEBAR_EXPANDED_STATE_KEY, next);
}
setLibrarySort(sort: SortPref): void {
this.updateSidebarSort(this._librarySort, 'sidebarLibrarySorting', sort);
}
setShelfSort(sort: SortPref): void {
this.updateSidebarSort(this._shelfSort, 'sidebarShelfSorting', sort);
}
setMagicShelfSort(sort: SortPref): void {
this.updateSidebarSort(this._magicShelfSort, 'sidebarMagicShelfSorting', sort);
}
private computeIsDesktop(): boolean {
return (this.document.defaultView?.innerWidth ?? 992) > 991;
}
private readonly onResize = (): void => {
this.isDesktop.set(this.computeIsDesktop());
};
private setSidebarCollapsed(collapsed: boolean): void {
if (collapsed !== this.sidebarCollapsed() && this.isDesktop()) {
this.startSidebarTransition();
}
this.sidebarCollapsed.set(collapsed);
this.localStorage.set('sidebarCollapsed', collapsed);
}
private startSidebarTransition(): void {
if (this.sidebarTransitionTimeoutId) {
clearTimeout(this.sidebarTransitionTimeoutId);
}
this._sidebarTransitioning.set(true);
this.sidebarTransitionTimeoutId = setTimeout(() => {
this._sidebarTransitioning.set(false);
this.sidebarTransitionTimeoutId = undefined;
}, SIDEBAR_TRANSITION_MS);
}
private changeScale(value: number): void {
this.document.documentElement.style.fontSize = `${value}px`;
}
private updateSidebarSort(
target: WritableSignal<SortPref>,
key: SidebarSortPreferenceKey,
sort: SortPref,
): void {
const normalized = normalizeSortPref(sort, target());
target.set(normalized);
const userService = this.userService;
const user = userService?.currentUser();
if (user && userService) {
userService.updateUserSetting(user.id, key, normalized);
}
}
}
@@ -0,0 +1,79 @@
import { describe, expect, it, vi } from 'vitest';
import { buildAllNavPages, buildHomeNavItems, buildQuickActionNavItems, findPageNavItem } from './nav-catalog';
const translate = (key: string): string => key;
describe('nav-catalog', () => {
it('builds the shared home navigation items from the common model', () => {
expect(buildHomeNavItems(translate).map((item) => item.id)).toEqual([
'dashboard',
'allBooks',
'series',
'authors',
'notebook',
]);
});
it('gates palette page items by permission while keeping the common pages available', () => {
expect(buildAllNavPages(translate, {}).map((item) => item.id)).toEqual([
'dashboard',
'allBooks',
'series',
'authors',
'notebook',
'settings',
]);
expect(buildAllNavPages(translate, {
canAccessLibraryStats: true,
canAccessUserStats: true,
canEditMetadata: true,
canAccessBookdrop: true,
}).map((item) => item.id)).toEqual([
'dashboard',
'allBooks',
'series',
'authors',
'notebook',
'settings',
'libraryStats',
'readingStats',
'metadataManager',
'bookdrop',
]);
});
it('looks up a single page nav item by id, gated by permissions', () => {
expect(findPageNavItem('dashboard', translate, {})?.id).toBe('dashboard');
expect(findPageNavItem('bookdrop', translate, {})).toBeNull();
expect(findPageNavItem('bookdrop', translate, { canAccessBookdrop: true })?.id).toBe('bookdrop');
expect(findPageNavItem('metadataManager', translate, { canManageLibrary: true })).toBeNull();
expect(findPageNavItem('metadataManager', translate, { canEditMetadata: true })?.id).toBe('metadataManager');
expect(findPageNavItem('unknown', translate, {})).toBeNull();
});
it('gates quick actions by permission while preserving the always-available actions', () => {
const handlers = {
createLibrary: vi.fn(),
createShelf: vi.fn(),
createMagicShelf: vi.fn(),
uploadBook: vi.fn(),
};
expect(buildQuickActionNavItems(translate, {}, handlers).map((item) => item.id)).toEqual([
'createShelf',
'createMagicShelf',
]);
expect(buildQuickActionNavItems(translate, {
canManageLibrary: true,
canUpload: true,
}, handlers).map((item) => item.id)).toEqual([
'createLibrary',
'createShelf',
'createMagicShelf',
'uploadBook',
]);
});
});
@@ -0,0 +1,225 @@
import { NavItem, NavItemType } from './nav-item.model';
export interface ShellNavPermissions {
admin?: boolean;
canManageLibrary?: boolean;
canEditMetadata?: boolean;
canUpload?: boolean;
canAccessLibraryStats?: boolean;
canAccessUserStats?: boolean;
canAccessBookdrop?: boolean;
}
export interface ShellActionHandlers {
createLibrary: () => void;
createShelf: () => void;
createMagicShelf: () => void;
uploadBook: () => void;
}
type TranslateFn = (key: string) => string;
interface PageDefinition {
id: string;
labelKey: string;
icon: string;
routerLink: string[];
type?: NavItemType;
isVisible?: (permissions: ShellNavPermissions) => boolean;
}
interface ActionDefinition {
id: string;
labelKey: string;
icon: string;
run: (handlers: ShellActionHandlers) => () => void;
isVisible?: (permissions: ShellNavPermissions) => boolean;
}
function canManageLibraries(permissions: ShellNavPermissions): boolean {
return !!permissions.admin || !!permissions.canManageLibrary;
}
function canAccessLibraryStats(permissions: ShellNavPermissions): boolean {
return !!permissions.admin || !!permissions.canAccessLibraryStats;
}
function canAccessUserStats(permissions: ShellNavPermissions): boolean {
return !!permissions.admin || !!permissions.canAccessUserStats;
}
function canAccessBookdrop(permissions: ShellNavPermissions): boolean {
return !!permissions.admin || !!permissions.canAccessBookdrop;
}
function canEditMetadata(permissions: ShellNavPermissions): boolean {
return !!permissions.admin || !!permissions.canEditMetadata;
}
function canUploadBooks(permissions: ShellNavPermissions): boolean {
return !!permissions.admin || !!permissions.canUpload;
}
const HOME_PAGE_DEFINITIONS: readonly PageDefinition[] = [
{
id: 'dashboard',
labelKey: 'layout.menu.dashboard',
icon: 'pi-home',
routerLink: ['/dashboard'],
},
{
id: 'allBooks',
labelKey: 'layout.menu.allBooks',
icon: 'pi-book',
routerLink: ['/all-books'],
type: 'allBooks',
},
{
id: 'series',
labelKey: 'layout.menu.series',
icon: 'pi-objects-column',
routerLink: ['/series'],
type: 'series',
},
{
id: 'authors',
labelKey: 'layout.menu.authors',
icon: 'pi-users',
routerLink: ['/authors'],
type: 'authors',
},
{
id: 'notebook',
labelKey: 'layout.menu.notebook',
icon: 'pi-pencil',
routerLink: ['/notebook'],
},
] as const;
const SECONDARY_PAGE_DEFINITIONS: readonly PageDefinition[] = [
{
id: 'settings',
labelKey: 'layout.menu.settings',
icon: 'pi-cog',
routerLink: ['/settings'],
},
{
id: 'libraryStats',
labelKey: 'layout.menu.libraryStats',
icon: 'pi-chart-line',
routerLink: ['/library-stats'],
isVisible: canAccessLibraryStats,
},
{
id: 'readingStats',
labelKey: 'layout.menu.readingStats',
icon: 'pi-chart-bar',
routerLink: ['/reading-stats'],
isVisible: canAccessUserStats,
},
{
id: 'metadataManager',
labelKey: 'layout.menu.metadataManager',
icon: 'pi-sparkles',
routerLink: ['/metadata-manager'],
isVisible: canEditMetadata,
},
{
id: 'bookdrop',
labelKey: 'layout.menu.bookdrop',
icon: 'pi-inbox',
routerLink: ['/bookdrop'],
isVisible: canAccessBookdrop,
},
] as const;
const ACTION_DEFINITIONS: readonly ActionDefinition[] = [
{
id: 'createLibrary',
labelKey: 'layout.menu.createLibrary',
icon: 'pi-folder',
run: (handlers) => handlers.createLibrary,
isVisible: canManageLibraries,
},
{
id: 'createShelf',
labelKey: 'book.shelfCreator.title',
icon: 'pi-bookmark',
run: (handlers) => handlers.createShelf,
},
{
id: 'createMagicShelf',
labelKey: 'layout.menu.createMagicShelf',
icon: 'pi-sparkles',
run: (handlers) => handlers.createMagicShelf,
},
{
id: 'uploadBook',
labelKey: 'layout.menu.uploadBook',
icon: 'pi-upload',
run: (handlers) => handlers.uploadBook,
isVisible: canUploadBooks,
},
] as const;
function isVisible<T extends { isVisible?: (permissions: ShellNavPermissions) => boolean }>(
definition: T,
permissions: ShellNavPermissions,
): boolean {
return definition.isVisible ? definition.isVisible(permissions) : true;
}
function toPageNavItem(definition: PageDefinition, translate: TranslateFn): NavItem {
return {
id: definition.id,
label: translate(definition.labelKey),
icon: definition.icon,
routerLink: definition.routerLink,
type: definition.type,
};
}
export function buildHomeNavItems(translate: TranslateFn): NavItem[] {
return HOME_PAGE_DEFINITIONS.map((definition) => toPageNavItem(definition, translate));
}
export function buildAllNavPages(
translate: TranslateFn,
permissions: ShellNavPermissions,
): NavItem[] {
return [...HOME_PAGE_DEFINITIONS, ...SECONDARY_PAGE_DEFINITIONS]
.filter((definition) => isVisible(definition, permissions))
.map((definition) => toPageNavItem(definition, translate));
}
export function buildQuickActionNavItems(
translate: TranslateFn,
permissions: ShellNavPermissions,
handlers: ShellActionHandlers,
): NavItem[] {
return ACTION_DEFINITIONS
.filter((definition) => isVisible(definition, permissions))
.map((definition) => ({
id: definition.id,
label: translate(definition.labelKey),
icon: definition.icon,
action: definition.run(handlers),
}));
}
const ALL_PAGE_DEFINITIONS: readonly PageDefinition[] = [
...HOME_PAGE_DEFINITIONS,
...SECONDARY_PAGE_DEFINITIONS,
] as const;
export function findPageNavItem(
id: string,
translate: TranslateFn,
permissions: ShellNavPermissions,
): NavItem | null {
const definition = ALL_PAGE_DEFINITIONS.find((page) => page.id === id);
if (!definition || !isVisible(definition, permissions)) {
return null;
}
return toPageNavItem(definition, translate);
}
@@ -0,0 +1,34 @@
import type { MenuItem } from 'primeng/api';
export type NavIconType = 'PRIME_NG' | 'CUSTOM_SVG';
export type NavItemType =
| 'library' | 'shelf' | 'magicShelf'
| 'allBooks' | 'series' | 'authors';
export interface NavItem {
id: string;
label: string;
icon?: string;
iconType?: NavIconType;
routerLink?: string[];
type?: NavItemType;
action?: () => void;
}
/** A clickable row inside a sidebar section. */
export interface SidebarLeaf extends NavItem {
bookCount?: number;
unhealthy?: boolean;
contextMenuItems?: MenuItem[];
}
/** A heading that groups leaves in the sidebar. */
export interface SidebarSection {
id: string;
label: string;
menuKey: string;
type?: NavItemType;
expandable?: boolean;
items: SidebarLeaf[];
}
@@ -0,0 +1,33 @@
export type SortField = 'name' | 'id';
export type SortOrder = 'asc' | 'desc';
export interface SortPref {
field: SortField;
order: SortOrder;
}
export type SidebarSortPreferenceKey =
| 'sidebarLibrarySorting'
| 'sidebarShelfSorting'
| 'sidebarMagicShelfSorting';
export const DEFAULT_LIBRARY_SORT: SortPref = { field: 'name', order: 'asc' };
export const DEFAULT_SHELF_SORT: SortPref = { field: 'name', order: 'asc' };
export const DEFAULT_MAGIC_SHELF_SORT: SortPref = { field: 'name', order: 'asc' };
export function normalizeSortPref(
raw: { field?: string; order?: string } | null | undefined,
fallback: SortPref,
): SortPref {
const field = typeof raw?.field === 'string' ? raw.field.toLowerCase() : null;
const order = typeof raw?.order === 'string' ? raw.order.toLowerCase() : null;
return {
field: field === 'id' || field === 'name' ? field : fallback.field,
order: order === 'asc' || order === 'desc' ? order : fallback.order,
};
}
export function sortPrefEqual(a: SortPref, b: SortPref): boolean {
return a.field === b.field && a.order === b.order;
}
@@ -1,35 +1,43 @@
<ng-container *transloco="let t; prefix: 'layout.theme'">
<div class="config-panel-content">
<div class="config-panel-colors">
<span class="config-panel-label">{{ t('primary') }}</span>
<div>
@for (primaryColor of primaryColors(); track primaryColor.name) {
<button
type="button"
[title]="primaryColor.name"
(click)="updateColors($event, 'primary', primaryColor)"
[ngClass]="{ 'active-color': primaryColor.name === selectedPrimaryColor() }"
[style]="{ 'background-color': primaryColor.name === 'noir' ? 'var(--text-color)' : primaryColor.palette['500'] || 'transparent' }"
></button>
}
<div class="setting-item">
<div class="setting-header-standalone">
<span class="setting-label">{{ t('primary') }}</span>
</div>
<div class="setting-options">
<div class="color-swatches">
@for (primaryColor of primaryColors(); track primaryColor.name) {
<button
type="button"
[title]="primaryColor.name"
[attr.aria-label]="primaryColor.name"
[attr.aria-pressed]="primaryColor.name === selectedPrimaryColor()"
(click)="updateColors($event, 'primary', primaryColor)"
[ngClass]="{ 'active-color': primaryColor.name === selectedPrimaryColor() }"
[style]="{ 'background-color': primaryColor.name === 'noir' ? 'var(--text-color)' : primaryColor.palette['500'] || 'transparent' }"
></button>
}
</div>
</div>
</div>
<div class="config-panel-colors">
<span class="config-panel-label">{{ t('surface') }}</span>
<div>
@for (surface of surfaces; track surface.name) {
<button
type="button"
[title]="surface.name"
(click)="updateColors($event, 'surface', surface)"
[ngClass]="{ 'active-color': selectedSurfaceColor() ? selectedSurfaceColor() === surface.name : surface.name === 'zinc' }"
[style]="{'background-color': surface.name === 'noir' ? 'var(--text-color)' : surface.palette['500'] }">
</button>
}
<div class="setting-item">
<div class="setting-header-standalone">
<span class="setting-label">{{ t('surface') }}</span>
</div>
<div class="setting-options">
<div class="color-swatches">
@for (surface of surfaces; track surface.name) {
<button
type="button"
[title]="surface.name"
[attr.aria-label]="surface.name"
[attr.aria-pressed]="selectedSurfaceColor() ? selectedSurfaceColor() === surface.name : surface.name === 'zinc'"
(click)="updateColors($event, 'surface', surface)"
[ngClass]="{ 'active-color': selectedSurfaceColor() ? selectedSurfaceColor() === surface.name : surface.name === 'zinc' }"
[style]="{'background-color': surface.name === 'noir' ? 'var(--text-color)' : surface.palette['500'] }">
</button>
}
</div>
</div>
</div>
</div>
</ng-container>

Some files were not shown because too many files have changed in this diff Show More