diff --git a/composeApp/src/androidMain/ic_launcher-playstore.png b/composeApp/src/androidMain/ic_launcher-playstore.png index bb9e3edb..bed6e9a7 100644 Binary files a/composeApp/src/androidMain/ic_launcher-playstore.png and b/composeApp/src/androidMain/ic_launcher-playstore.png differ diff --git a/composeApp/src/androidMain/res/drawable/ic_launcher_foreground.xml b/composeApp/src/androidMain/res/drawable/ic_launcher_foreground.xml index 949fd94c..48723580 100644 --- a/composeApp/src/androidMain/res/drawable/ic_launcher_foreground.xml +++ b/composeApp/src/androidMain/res/drawable/ic_launcher_foreground.xml @@ -1,113 +1,14 @@ - + android:viewportWidth="512" + android:viewportHeight="512"> + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + android:pathData="M246.31,26C244.88,25.74 243.39,26.79 241.55,28.54C239.71,30.28 236.15,33.14 235.2,36.48C234.24,39.82 237.67,41.82 235.83,48.55C233.99,55.29 227.25,68.63 224.08,76.83C220.9,85.02 218.77,91.18 216.77,97.79C214.77,104.4 213.21,110.56 212,116.54C210.8,122.51 209.94,131.37 209.46,133.69C208.99,136.01 209.62,131.47 209.15,130.51C208.67,129.56 207.02,130.04 206.6,127.97C206.19,125.91 206.38,121.3 206.6,118.12C206.83,114.95 206.99,113.2 207.87,108.91C208.76,104.62 209.37,99.95 212,92.39C214.64,84.83 221.63,69.74 223.76,63.48C225.89,57.22 224.97,57.29 224.71,54.91C224.46,52.52 223.06,50.52 222.17,49.19C221.28,47.85 220.36,47.5 219.31,46.96C218.26,46.42 217.31,45.95 215.82,46.01C214.32,46.07 211.91,46.33 210.42,47.28C208.92,48.23 207.49,50.24 206.92,51.73C206.35,53.22 206.7,55.16 206.92,56.18C207.14,57.19 207.49,57.76 208.19,57.76C208.89,57.76 210.42,55.86 211.05,56.18C211.69,56.49 213.59,55.92 212,59.67C210.42,63.42 204.63,72.54 201.52,78.73C198.41,84.93 195.23,92.07 193.26,96.84C191.29,101.6 191.04,102.33 189.77,107.32C188.5,112.31 186.18,123.3 185.64,126.7C185.1,130.1 184.11,127.43 186.59,127.65C189.07,127.88 197.71,127.65 200.57,127.97C203.43,128.29 202.57,128.67 203.74,129.56C204.92,130.45 206.6,132.1 207.56,133.37C208.51,134.64 209.78,136.14 209.46,137.18C209.15,138.23 207.08,138.3 205.65,139.73C204.22,141.16 213.12,143.7 200.89,145.76C188.65,147.83 147.13,150.46 132.27,152.12C117.4,153.77 99.16,154.43 111.62,155.61C124.07,156.79 190.5,158.21 206.92,159.1C223.35,159.99 208.29,160.37 210.1,161.01C211.91,161.65 212.39,162.54 217.72,162.92C223.06,163.3 237.26,162.82 242.18,163.23C247.11,163.65 245.84,164.25 247.27,165.46C248.7,166.67 250.28,168.89 250.76,170.54C251.24,172.19 251.17,173.72 250.13,175.31C249.08,176.89 246.16,179.05 244.41,180.07C242.66,181.09 244.63,181.09 239.64,181.34C234.66,181.6 219.79,181.28 214.55,181.66C209.3,182.04 210.42,182.61 208.19,183.57C205.97,184.52 203.49,185.69 201.2,187.38C198.92,189.06 196.34,191.44 194.53,193.73C192.72,196.02 191.36,198.88 190.4,201.04C189.45,203.2 189.13,204.53 188.81,206.76C188.5,208.98 188.27,211.84 188.5,214.38C188.72,216.92 189.07,219.3 190.08,222C191.1,224.71 190.5,225.56 194.53,230.58C198.57,235.6 208.29,244.56 214.23,252.18C220.17,259.81 224.97,269.5 230.11,276.33C235.26,283.16 240.98,287.7 245.04,293.17C249.11,298.63 249.87,302.38 254.57,309.05C259.28,315.72 270.14,328.59 273.32,333.19C276.49,337.8 273.86,334.4 273.63,336.69C273.41,338.97 275.64,334.08 272.05,346.85C268.46,359.62 257.05,397.14 252.03,413.25C247.01,429.35 244.63,436.06 241.87,443.43C239.1,450.8 237.2,454.45 235.51,457.41C233.83,460.36 233.51,460.11 231.7,461.22C229.89,462.33 227.09,463.54 224.71,464.08C222.33,464.62 219.47,464.55 217.41,464.39C215.34,464.24 214.13,463.35 212.32,463.12C210.51,462.9 208.03,462.87 206.6,463.12C205.17,463.38 204.48,464.08 203.74,464.71C203.01,465.35 203.81,466.36 202.16,466.94C200.5,467.51 196.03,467.19 193.9,468.21C191.77,469.22 189.35,472.59 189.45,472.97C189.54,473.35 193.1,470.84 194.53,470.43C195.96,470.02 197.55,470.05 198.03,470.43C198.5,470.81 197.33,472.11 197.39,472.65C197.45,473.19 197.71,473.45 198.34,473.61C198.98,473.77 200.41,473.83 201.2,473.61C202,473.39 200.73,472.65 203.11,472.34C205.49,472.02 213.97,471.07 215.5,471.7C217.02,472.34 212.96,474.66 212.32,476.15C211.69,477.64 210.99,480.69 211.69,480.6C212.39,480.5 214.93,476.21 216.45,475.51C217.98,474.81 219.79,476.63 220.9,476.47C222.01,476.31 220.17,475.58 223.12,474.56C226.08,473.54 233.45,470.91 238.69,470.43C243.93,469.95 251.56,471.29 254.57,471.7C257.59,472.11 256,472.75 256.8,472.97C257.59,473.19 258.64,473.19 259.34,472.97C260.04,472.75 260.67,472.18 260.93,471.7C261.18,471.22 260.45,470.37 260.93,470.11C261.4,469.86 262.67,469.64 263.79,470.11C264.9,470.59 267.22,473.23 267.6,472.97C267.98,472.72 266.71,469.64 266.01,468.52C265.31,467.41 264.64,466.71 263.47,466.3C262.29,465.89 259.97,466.24 259.02,465.98C258.07,465.73 258.39,464.78 257.75,464.71C257.12,464.65 256.54,465.67 255.21,465.67C253.87,465.67 251.3,465.19 249.81,464.71C248.32,464.24 247.2,463.6 246.31,462.81C245.42,462.01 244.57,461.76 244.41,459.95C244.25,458.14 243.84,457.88 245.36,452.01C246.89,446.13 248.12,441.59 253.62,424.68C259.12,407.78 273.54,364.71 278.4,350.67C283.26,336.62 282.15,343.2 282.85,340.5C283.55,337.8 283.07,336.31 282.53,334.46C281.99,332.62 280.94,332.88 279.67,329.38C278.4,325.89 276.72,317.56 274.91,313.5C273.09,309.43 270.24,307.24 268.87,304.92C267.5,302.6 264.1,297.04 266.65,299.52C269.19,302 278.34,313.66 284.12,319.85C289.9,326.05 298.35,332.81 301.27,336.69C304.2,340.56 301.18,341.07 301.59,343.04C302,345.01 302.64,342.79 303.81,348.44C304.99,354.1 306.13,359.81 308.58,377.03C311.03,394.25 317.06,437.77 318.43,451.69C319.79,465.6 317.7,458.52 316.84,460.58C315.98,462.65 315,463.22 313.34,464.08C311.69,464.93 309.53,465.57 306.99,465.67C304.45,465.76 300.26,464.65 298.1,464.71C295.94,464.78 295.01,465.41 293.97,465.98C292.92,466.55 293.39,467.79 291.74,468.21C290.09,468.62 286.12,467.95 284.12,468.52C282.12,469.1 280.72,470.49 279.67,471.7C278.62,472.91 277.54,475.67 277.76,475.83C277.99,475.99 279.61,473.39 280.94,472.65C282.28,471.92 284.85,471.29 285.71,471.38C286.56,471.48 285.61,472.88 286.02,473.29C286.44,473.7 288.41,473.13 288.25,473.93C288.09,474.72 285.64,476.69 285.07,478.05C284.5,479.42 284.5,482.12 284.75,482.18C285.01,482.25 285.77,479.39 286.66,478.37C287.55,477.36 289.2,476.24 290.15,476.15C291.11,476.05 291.65,477.48 292.38,477.74C293.11,477.99 292.38,478.44 294.6,477.74C296.83,477.04 302.23,474.56 305.72,473.61C309.21,472.65 313.92,472.11 315.57,472.02C317.22,471.92 315.95,472.65 315.57,472.97C315.19,473.29 314.08,473.04 313.34,473.93C312.61,474.81 311.53,476.4 311.12,478.37C310.71,480.34 310.42,485.3 310.8,485.68C311.18,486.06 312.45,481.39 313.34,480.6C314.23,479.8 314.62,481.61 316.2,480.91C317.79,480.22 321.13,477.17 322.87,476.47C324.62,475.77 325.51,476.15 326.69,476.78C327.86,477.42 328.97,479.64 329.86,480.28C330.75,480.91 331.45,479.8 332.09,480.6C332.72,481.39 333.29,485.04 333.68,485.04C334.06,485.04 334.37,482.41 334.31,480.6C334.25,478.79 334.06,475.77 333.36,474.24C332.66,472.72 329.48,471.7 330.18,471.38C330.88,471.07 335.96,472.27 337.49,472.34C339.01,472.4 338.85,472.24 339.39,471.7C339.93,471.16 340.03,469.41 340.66,469.16C341.3,468.91 342.41,469.54 343.21,470.11C344,470.68 345.21,472.91 345.43,472.65C345.65,472.4 345.27,469.73 344.48,468.52C343.68,467.32 341.68,465.89 340.66,465.35C339.65,464.81 339.01,465.57 338.44,465.35C337.87,465.13 337.96,464.14 337.17,464.08C336.38,464.01 334.79,465.09 333.68,465.03C332.56,464.97 331.52,464.55 330.5,463.76C329.48,462.97 328.5,462.01 327.64,460.26C326.78,458.52 327.58,467.03 325.42,453.28C323.26,439.52 316.93,394.98 314.62,377.67C312.3,360.35 312.01,355.97 311.44,349.39C310.87,342.82 311.37,340.82 311.12,338.28C310.87,335.73 310.58,335.48 309.85,334.15C309.12,332.81 308.01,332.46 306.67,330.33C305.34,328.21 298.32,321.5 301.91,321.44C305.5,321.38 319.22,327.95 328.28,330.02C337.33,332.08 351.21,333.03 356.23,333.83C361.25,334.62 356.8,333.35 358.45,334.78C360.11,336.21 363.95,340.56 366.08,342.41C368.21,344.25 370.37,345.74 371.16,345.9C371.96,346.06 370.05,343.1 370.84,343.36C371.64,343.61 375.13,347.11 375.93,347.49C376.72,347.87 375.04,345.42 375.61,345.58C376.18,345.74 378.88,348.35 379.42,348.44C379.96,348.54 378.25,346.15 378.79,346.22C379.33,346.28 382.12,348.51 382.6,348.76C383.08,349.01 381.71,348.03 381.65,347.81C381.58,347.58 381.11,347.08 382.28,347.49C383.46,347.9 388,350.35 388.63,350.35C389.27,350.35 385.78,347.65 386.09,347.49C386.41,347.33 389.81,349.33 390.54,349.39C391.27,349.46 389.81,347.49 390.54,347.81C391.27,348.12 394.45,351.21 394.99,351.3C395.53,351.4 393.5,348.7 393.72,348.44C393.94,348.19 395.78,349.62 396.26,349.71C396.74,349.81 396.26,348.92 396.58,349.08C396.89,349.24 398.23,351.84 398.16,350.67C398.1,349.49 395.94,342.88 396.26,342.09C396.58,341.29 399.91,346 400.07,345.9C400.23,345.8 397.59,342.31 397.21,341.45C396.83,340.59 397.43,340.56 397.85,340.82C398.26,341.07 400.01,344.15 399.75,343.04C399.5,341.93 396.8,335.73 396.26,334.15C395.72,332.56 396.1,333.26 396.58,333.51C397.05,333.76 399.5,336.69 399.12,335.73C398.74,334.78 395.08,329.22 394.35,327.79C393.62,326.36 394.42,327.09 394.67,327.16C394.92,327.22 397.78,331.06 395.94,328.11C394.1,325.16 391.4,319.91 383.55,309.37C375.7,298.82 359.09,276.96 348.92,264.89C338.76,252.82 330.88,244.78 322.56,236.94C314.23,229.09 306.61,223.18 299.05,217.88C291.49,212.57 282.75,208.03 277.13,205.17C271.51,202.31 268.87,201.77 265.37,200.72C261.88,199.67 259.08,199.2 256.16,198.81C253.24,198.43 250.86,198.18 247.9,198.5C244.95,198.81 240.85,199.86 238.37,200.72C235.89,201.58 235.29,201.93 232.97,203.58C230.65,205.23 226.68,209.04 224.39,210.57C222.11,212.09 220.74,212.41 219.31,212.79C217.88,213.17 216.93,213.01 215.82,212.79C214.7,212.57 213.66,212.38 212.64,211.52C211.62,210.66 210.26,209.04 209.78,207.71C209.3,206.38 209.53,204.85 209.78,203.58C210.03,202.31 210.57,201.2 211.37,200.08C212.16,198.97 213.34,197.8 214.55,196.91C215.75,196.02 216.93,195.32 218.68,194.68C220.42,194.05 221.28,193.41 225.03,193.1C228.78,192.78 237.1,193.1 241.23,192.78C245.36,192.46 246.89,192.14 249.81,191.19C252.73,190.24 256.23,188.81 258.7,187.06C261.18,185.31 263.31,183.09 264.74,180.71C266.17,178.32 267.06,175.56 267.28,172.76C267.5,169.97 267.03,166.82 266.01,163.87C264.99,160.92 263.72,158.31 261.24,154.97C258.77,151.64 249.08,145.51 251.08,143.86C253.08,142.2 265.44,144.33 273.32,145.13C281.2,145.92 290.85,147.25 298.41,148.62C305.97,149.99 311.6,151.32 318.74,153.39C325.89,155.45 341.36,161.11 341.3,161.01C341.24,160.92 325.48,154.97 318.43,152.75C311.37,150.53 307.09,149.26 299.05,147.67C291.01,146.08 278.4,144.24 270.14,143.22C261.88,142.2 253.3,142.04 249.49,141.63C245.68,141.22 244.73,140.9 247.27,140.68C249.81,140.46 254.41,139.82 264.74,140.36C275.06,140.9 297.78,142.68 309.21,143.86C320.65,145.03 326.85,146.17 333.36,147.35C339.87,148.53 348.99,151.07 348.29,150.84C347.59,150.62 335.36,147.41 329.23,146.08C323.1,144.75 319.79,144.01 311.44,142.9C303.08,141.79 290.63,140.3 279.03,139.41C267.44,138.52 248.54,138.07 241.87,137.5C235.2,136.93 238.59,136.87 239.01,135.91C239.42,134.96 242.41,132.96 244.41,131.78C246.41,130.61 247.33,129.78 251.08,128.92C254.83,128.07 264.52,135.34 266.96,126.7C269.41,118.06 265.79,87.69 265.69,77.14C265.6,66.6 265.79,66.28 266.33,63.48C266.87,60.69 268.23,60.85 268.87,60.31C269.5,59.77 269.76,59.99 270.14,60.31C270.52,60.62 270.52,62.05 271.09,62.21C271.66,62.37 272.78,62.28 273.63,61.26C274.49,60.24 275.86,57.67 276.18,56.18C276.49,54.68 276.02,53.48 275.54,52.36C275.06,51.25 274.27,50.24 273.32,49.5C272.36,48.77 271.16,48.17 269.82,47.92C268.49,47.66 267.28,47.28 265.37,47.92C263.47,48.55 260.36,49.89 258.39,51.73C256.42,53.57 254.8,56.33 253.62,59.04C252.45,61.74 252.1,61.58 251.4,67.93C250.7,74.28 250.22,88.83 249.49,97.16C248.76,105.48 247.81,112.66 246.95,117.81C246.09,122.95 245.46,126 244.41,127.97C243.36,129.94 240.6,133.75 240.6,129.56C240.6,125.37 243.23,115.96 244.41,102.87C245.58,89.79 246.85,60.46 247.58,51.09C248.32,41.72 248.06,48.33 248.86,46.65C249.65,44.96 252.13,43.69 252.35,40.93C252.57,38.16 251.14,32.6 250.13,30.13C249.11,27.65 247.74,26.25 246.31,26Z" + android:fillColor="#000000"/> diff --git a/composeApp/src/androidMain/res/drawable/ic_launcher_monochrome.xml b/composeApp/src/androidMain/res/drawable/ic_launcher_monochrome.xml index 949fd94c..48723580 100644 --- a/composeApp/src/androidMain/res/drawable/ic_launcher_monochrome.xml +++ b/composeApp/src/androidMain/res/drawable/ic_launcher_monochrome.xml @@ -1,113 +1,14 @@ - + android:viewportWidth="512" + android:viewportHeight="512"> + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + android:pathData="M246.31,26C244.88,25.74 243.39,26.79 241.55,28.54C239.71,30.28 236.15,33.14 235.2,36.48C234.24,39.82 237.67,41.82 235.83,48.55C233.99,55.29 227.25,68.63 224.08,76.83C220.9,85.02 218.77,91.18 216.77,97.79C214.77,104.4 213.21,110.56 212,116.54C210.8,122.51 209.94,131.37 209.46,133.69C208.99,136.01 209.62,131.47 209.15,130.51C208.67,129.56 207.02,130.04 206.6,127.97C206.19,125.91 206.38,121.3 206.6,118.12C206.83,114.95 206.99,113.2 207.87,108.91C208.76,104.62 209.37,99.95 212,92.39C214.64,84.83 221.63,69.74 223.76,63.48C225.89,57.22 224.97,57.29 224.71,54.91C224.46,52.52 223.06,50.52 222.17,49.19C221.28,47.85 220.36,47.5 219.31,46.96C218.26,46.42 217.31,45.95 215.82,46.01C214.32,46.07 211.91,46.33 210.42,47.28C208.92,48.23 207.49,50.24 206.92,51.73C206.35,53.22 206.7,55.16 206.92,56.18C207.14,57.19 207.49,57.76 208.19,57.76C208.89,57.76 210.42,55.86 211.05,56.18C211.69,56.49 213.59,55.92 212,59.67C210.42,63.42 204.63,72.54 201.52,78.73C198.41,84.93 195.23,92.07 193.26,96.84C191.29,101.6 191.04,102.33 189.77,107.32C188.5,112.31 186.18,123.3 185.64,126.7C185.1,130.1 184.11,127.43 186.59,127.65C189.07,127.88 197.71,127.65 200.57,127.97C203.43,128.29 202.57,128.67 203.74,129.56C204.92,130.45 206.6,132.1 207.56,133.37C208.51,134.64 209.78,136.14 209.46,137.18C209.15,138.23 207.08,138.3 205.65,139.73C204.22,141.16 213.12,143.7 200.89,145.76C188.65,147.83 147.13,150.46 132.27,152.12C117.4,153.77 99.16,154.43 111.62,155.61C124.07,156.79 190.5,158.21 206.92,159.1C223.35,159.99 208.29,160.37 210.1,161.01C211.91,161.65 212.39,162.54 217.72,162.92C223.06,163.3 237.26,162.82 242.18,163.23C247.11,163.65 245.84,164.25 247.27,165.46C248.7,166.67 250.28,168.89 250.76,170.54C251.24,172.19 251.17,173.72 250.13,175.31C249.08,176.89 246.16,179.05 244.41,180.07C242.66,181.09 244.63,181.09 239.64,181.34C234.66,181.6 219.79,181.28 214.55,181.66C209.3,182.04 210.42,182.61 208.19,183.57C205.97,184.52 203.49,185.69 201.2,187.38C198.92,189.06 196.34,191.44 194.53,193.73C192.72,196.02 191.36,198.88 190.4,201.04C189.45,203.2 189.13,204.53 188.81,206.76C188.5,208.98 188.27,211.84 188.5,214.38C188.72,216.92 189.07,219.3 190.08,222C191.1,224.71 190.5,225.56 194.53,230.58C198.57,235.6 208.29,244.56 214.23,252.18C220.17,259.81 224.97,269.5 230.11,276.33C235.26,283.16 240.98,287.7 245.04,293.17C249.11,298.63 249.87,302.38 254.57,309.05C259.28,315.72 270.14,328.59 273.32,333.19C276.49,337.8 273.86,334.4 273.63,336.69C273.41,338.97 275.64,334.08 272.05,346.85C268.46,359.62 257.05,397.14 252.03,413.25C247.01,429.35 244.63,436.06 241.87,443.43C239.1,450.8 237.2,454.45 235.51,457.41C233.83,460.36 233.51,460.11 231.7,461.22C229.89,462.33 227.09,463.54 224.71,464.08C222.33,464.62 219.47,464.55 217.41,464.39C215.34,464.24 214.13,463.35 212.32,463.12C210.51,462.9 208.03,462.87 206.6,463.12C205.17,463.38 204.48,464.08 203.74,464.71C203.01,465.35 203.81,466.36 202.16,466.94C200.5,467.51 196.03,467.19 193.9,468.21C191.77,469.22 189.35,472.59 189.45,472.97C189.54,473.35 193.1,470.84 194.53,470.43C195.96,470.02 197.55,470.05 198.03,470.43C198.5,470.81 197.33,472.11 197.39,472.65C197.45,473.19 197.71,473.45 198.34,473.61C198.98,473.77 200.41,473.83 201.2,473.61C202,473.39 200.73,472.65 203.11,472.34C205.49,472.02 213.97,471.07 215.5,471.7C217.02,472.34 212.96,474.66 212.32,476.15C211.69,477.64 210.99,480.69 211.69,480.6C212.39,480.5 214.93,476.21 216.45,475.51C217.98,474.81 219.79,476.63 220.9,476.47C222.01,476.31 220.17,475.58 223.12,474.56C226.08,473.54 233.45,470.91 238.69,470.43C243.93,469.95 251.56,471.29 254.57,471.7C257.59,472.11 256,472.75 256.8,472.97C257.59,473.19 258.64,473.19 259.34,472.97C260.04,472.75 260.67,472.18 260.93,471.7C261.18,471.22 260.45,470.37 260.93,470.11C261.4,469.86 262.67,469.64 263.79,470.11C264.9,470.59 267.22,473.23 267.6,472.97C267.98,472.72 266.71,469.64 266.01,468.52C265.31,467.41 264.64,466.71 263.47,466.3C262.29,465.89 259.97,466.24 259.02,465.98C258.07,465.73 258.39,464.78 257.75,464.71C257.12,464.65 256.54,465.67 255.21,465.67C253.87,465.67 251.3,465.19 249.81,464.71C248.32,464.24 247.2,463.6 246.31,462.81C245.42,462.01 244.57,461.76 244.41,459.95C244.25,458.14 243.84,457.88 245.36,452.01C246.89,446.13 248.12,441.59 253.62,424.68C259.12,407.78 273.54,364.71 278.4,350.67C283.26,336.62 282.15,343.2 282.85,340.5C283.55,337.8 283.07,336.31 282.53,334.46C281.99,332.62 280.94,332.88 279.67,329.38C278.4,325.89 276.72,317.56 274.91,313.5C273.09,309.43 270.24,307.24 268.87,304.92C267.5,302.6 264.1,297.04 266.65,299.52C269.19,302 278.34,313.66 284.12,319.85C289.9,326.05 298.35,332.81 301.27,336.69C304.2,340.56 301.18,341.07 301.59,343.04C302,345.01 302.64,342.79 303.81,348.44C304.99,354.1 306.13,359.81 308.58,377.03C311.03,394.25 317.06,437.77 318.43,451.69C319.79,465.6 317.7,458.52 316.84,460.58C315.98,462.65 315,463.22 313.34,464.08C311.69,464.93 309.53,465.57 306.99,465.67C304.45,465.76 300.26,464.65 298.1,464.71C295.94,464.78 295.01,465.41 293.97,465.98C292.92,466.55 293.39,467.79 291.74,468.21C290.09,468.62 286.12,467.95 284.12,468.52C282.12,469.1 280.72,470.49 279.67,471.7C278.62,472.91 277.54,475.67 277.76,475.83C277.99,475.99 279.61,473.39 280.94,472.65C282.28,471.92 284.85,471.29 285.71,471.38C286.56,471.48 285.61,472.88 286.02,473.29C286.44,473.7 288.41,473.13 288.25,473.93C288.09,474.72 285.64,476.69 285.07,478.05C284.5,479.42 284.5,482.12 284.75,482.18C285.01,482.25 285.77,479.39 286.66,478.37C287.55,477.36 289.2,476.24 290.15,476.15C291.11,476.05 291.65,477.48 292.38,477.74C293.11,477.99 292.38,478.44 294.6,477.74C296.83,477.04 302.23,474.56 305.72,473.61C309.21,472.65 313.92,472.11 315.57,472.02C317.22,471.92 315.95,472.65 315.57,472.97C315.19,473.29 314.08,473.04 313.34,473.93C312.61,474.81 311.53,476.4 311.12,478.37C310.71,480.34 310.42,485.3 310.8,485.68C311.18,486.06 312.45,481.39 313.34,480.6C314.23,479.8 314.62,481.61 316.2,480.91C317.79,480.22 321.13,477.17 322.87,476.47C324.62,475.77 325.51,476.15 326.69,476.78C327.86,477.42 328.97,479.64 329.86,480.28C330.75,480.91 331.45,479.8 332.09,480.6C332.72,481.39 333.29,485.04 333.68,485.04C334.06,485.04 334.37,482.41 334.31,480.6C334.25,478.79 334.06,475.77 333.36,474.24C332.66,472.72 329.48,471.7 330.18,471.38C330.88,471.07 335.96,472.27 337.49,472.34C339.01,472.4 338.85,472.24 339.39,471.7C339.93,471.16 340.03,469.41 340.66,469.16C341.3,468.91 342.41,469.54 343.21,470.11C344,470.68 345.21,472.91 345.43,472.65C345.65,472.4 345.27,469.73 344.48,468.52C343.68,467.32 341.68,465.89 340.66,465.35C339.65,464.81 339.01,465.57 338.44,465.35C337.87,465.13 337.96,464.14 337.17,464.08C336.38,464.01 334.79,465.09 333.68,465.03C332.56,464.97 331.52,464.55 330.5,463.76C329.48,462.97 328.5,462.01 327.64,460.26C326.78,458.52 327.58,467.03 325.42,453.28C323.26,439.52 316.93,394.98 314.62,377.67C312.3,360.35 312.01,355.97 311.44,349.39C310.87,342.82 311.37,340.82 311.12,338.28C310.87,335.73 310.58,335.48 309.85,334.15C309.12,332.81 308.01,332.46 306.67,330.33C305.34,328.21 298.32,321.5 301.91,321.44C305.5,321.38 319.22,327.95 328.28,330.02C337.33,332.08 351.21,333.03 356.23,333.83C361.25,334.62 356.8,333.35 358.45,334.78C360.11,336.21 363.95,340.56 366.08,342.41C368.21,344.25 370.37,345.74 371.16,345.9C371.96,346.06 370.05,343.1 370.84,343.36C371.64,343.61 375.13,347.11 375.93,347.49C376.72,347.87 375.04,345.42 375.61,345.58C376.18,345.74 378.88,348.35 379.42,348.44C379.96,348.54 378.25,346.15 378.79,346.22C379.33,346.28 382.12,348.51 382.6,348.76C383.08,349.01 381.71,348.03 381.65,347.81C381.58,347.58 381.11,347.08 382.28,347.49C383.46,347.9 388,350.35 388.63,350.35C389.27,350.35 385.78,347.65 386.09,347.49C386.41,347.33 389.81,349.33 390.54,349.39C391.27,349.46 389.81,347.49 390.54,347.81C391.27,348.12 394.45,351.21 394.99,351.3C395.53,351.4 393.5,348.7 393.72,348.44C393.94,348.19 395.78,349.62 396.26,349.71C396.74,349.81 396.26,348.92 396.58,349.08C396.89,349.24 398.23,351.84 398.16,350.67C398.1,349.49 395.94,342.88 396.26,342.09C396.58,341.29 399.91,346 400.07,345.9C400.23,345.8 397.59,342.31 397.21,341.45C396.83,340.59 397.43,340.56 397.85,340.82C398.26,341.07 400.01,344.15 399.75,343.04C399.5,341.93 396.8,335.73 396.26,334.15C395.72,332.56 396.1,333.26 396.58,333.51C397.05,333.76 399.5,336.69 399.12,335.73C398.74,334.78 395.08,329.22 394.35,327.79C393.62,326.36 394.42,327.09 394.67,327.16C394.92,327.22 397.78,331.06 395.94,328.11C394.1,325.16 391.4,319.91 383.55,309.37C375.7,298.82 359.09,276.96 348.92,264.89C338.76,252.82 330.88,244.78 322.56,236.94C314.23,229.09 306.61,223.18 299.05,217.88C291.49,212.57 282.75,208.03 277.13,205.17C271.51,202.31 268.87,201.77 265.37,200.72C261.88,199.67 259.08,199.2 256.16,198.81C253.24,198.43 250.86,198.18 247.9,198.5C244.95,198.81 240.85,199.86 238.37,200.72C235.89,201.58 235.29,201.93 232.97,203.58C230.65,205.23 226.68,209.04 224.39,210.57C222.11,212.09 220.74,212.41 219.31,212.79C217.88,213.17 216.93,213.01 215.82,212.79C214.7,212.57 213.66,212.38 212.64,211.52C211.62,210.66 210.26,209.04 209.78,207.71C209.3,206.38 209.53,204.85 209.78,203.58C210.03,202.31 210.57,201.2 211.37,200.08C212.16,198.97 213.34,197.8 214.55,196.91C215.75,196.02 216.93,195.32 218.68,194.68C220.42,194.05 221.28,193.41 225.03,193.1C228.78,192.78 237.1,193.1 241.23,192.78C245.36,192.46 246.89,192.14 249.81,191.19C252.73,190.24 256.23,188.81 258.7,187.06C261.18,185.31 263.31,183.09 264.74,180.71C266.17,178.32 267.06,175.56 267.28,172.76C267.5,169.97 267.03,166.82 266.01,163.87C264.99,160.92 263.72,158.31 261.24,154.97C258.77,151.64 249.08,145.51 251.08,143.86C253.08,142.2 265.44,144.33 273.32,145.13C281.2,145.92 290.85,147.25 298.41,148.62C305.97,149.99 311.6,151.32 318.74,153.39C325.89,155.45 341.36,161.11 341.3,161.01C341.24,160.92 325.48,154.97 318.43,152.75C311.37,150.53 307.09,149.26 299.05,147.67C291.01,146.08 278.4,144.24 270.14,143.22C261.88,142.2 253.3,142.04 249.49,141.63C245.68,141.22 244.73,140.9 247.27,140.68C249.81,140.46 254.41,139.82 264.74,140.36C275.06,140.9 297.78,142.68 309.21,143.86C320.65,145.03 326.85,146.17 333.36,147.35C339.87,148.53 348.99,151.07 348.29,150.84C347.59,150.62 335.36,147.41 329.23,146.08C323.1,144.75 319.79,144.01 311.44,142.9C303.08,141.79 290.63,140.3 279.03,139.41C267.44,138.52 248.54,138.07 241.87,137.5C235.2,136.93 238.59,136.87 239.01,135.91C239.42,134.96 242.41,132.96 244.41,131.78C246.41,130.61 247.33,129.78 251.08,128.92C254.83,128.07 264.52,135.34 266.96,126.7C269.41,118.06 265.79,87.69 265.69,77.14C265.6,66.6 265.79,66.28 266.33,63.48C266.87,60.69 268.23,60.85 268.87,60.31C269.5,59.77 269.76,59.99 270.14,60.31C270.52,60.62 270.52,62.05 271.09,62.21C271.66,62.37 272.78,62.28 273.63,61.26C274.49,60.24 275.86,57.67 276.18,56.18C276.49,54.68 276.02,53.48 275.54,52.36C275.06,51.25 274.27,50.24 273.32,49.5C272.36,48.77 271.16,48.17 269.82,47.92C268.49,47.66 267.28,47.28 265.37,47.92C263.47,48.55 260.36,49.89 258.39,51.73C256.42,53.57 254.8,56.33 253.62,59.04C252.45,61.74 252.1,61.58 251.4,67.93C250.7,74.28 250.22,88.83 249.49,97.16C248.76,105.48 247.81,112.66 246.95,117.81C246.09,122.95 245.46,126 244.41,127.97C243.36,129.94 240.6,133.75 240.6,129.56C240.6,125.37 243.23,115.96 244.41,102.87C245.58,89.79 246.85,60.46 247.58,51.09C248.32,41.72 248.06,48.33 248.86,46.65C249.65,44.96 252.13,43.69 252.35,40.93C252.57,38.16 251.14,32.6 250.13,30.13C249.11,27.65 247.74,26.25 246.31,26Z" + android:fillColor="#000000"/> diff --git a/composeApp/src/androidMain/res/mipmap-hdpi/ic_launcher.webp b/composeApp/src/androidMain/res/mipmap-hdpi/ic_launcher.webp index 50f7b95a..28c470f2 100644 Binary files a/composeApp/src/androidMain/res/mipmap-hdpi/ic_launcher.webp and b/composeApp/src/androidMain/res/mipmap-hdpi/ic_launcher.webp differ diff --git a/composeApp/src/androidMain/res/mipmap-hdpi/ic_launcher_round.webp b/composeApp/src/androidMain/res/mipmap-hdpi/ic_launcher_round.webp index d406dcc5..dedd71bd 100644 Binary files a/composeApp/src/androidMain/res/mipmap-hdpi/ic_launcher_round.webp and b/composeApp/src/androidMain/res/mipmap-hdpi/ic_launcher_round.webp differ diff --git a/composeApp/src/androidMain/res/mipmap-mdpi/ic_launcher.webp b/composeApp/src/androidMain/res/mipmap-mdpi/ic_launcher.webp index 209e6fdc..0e7bdb00 100644 Binary files a/composeApp/src/androidMain/res/mipmap-mdpi/ic_launcher.webp and b/composeApp/src/androidMain/res/mipmap-mdpi/ic_launcher.webp differ diff --git a/composeApp/src/androidMain/res/mipmap-mdpi/ic_launcher_round.webp b/composeApp/src/androidMain/res/mipmap-mdpi/ic_launcher_round.webp index e2d87969..08774edb 100644 Binary files a/composeApp/src/androidMain/res/mipmap-mdpi/ic_launcher_round.webp and b/composeApp/src/androidMain/res/mipmap-mdpi/ic_launcher_round.webp differ diff --git a/composeApp/src/androidMain/res/mipmap-xhdpi/ic_launcher.webp b/composeApp/src/androidMain/res/mipmap-xhdpi/ic_launcher.webp index ebfb4171..898aab28 100644 Binary files a/composeApp/src/androidMain/res/mipmap-xhdpi/ic_launcher.webp and b/composeApp/src/androidMain/res/mipmap-xhdpi/ic_launcher.webp differ diff --git a/composeApp/src/androidMain/res/mipmap-xhdpi/ic_launcher_round.webp b/composeApp/src/androidMain/res/mipmap-xhdpi/ic_launcher_round.webp index 0768dd65..a888423f 100644 Binary files a/composeApp/src/androidMain/res/mipmap-xhdpi/ic_launcher_round.webp and b/composeApp/src/androidMain/res/mipmap-xhdpi/ic_launcher_round.webp differ diff --git a/composeApp/src/androidMain/res/mipmap-xxhdpi/ic_launcher.webp b/composeApp/src/androidMain/res/mipmap-xxhdpi/ic_launcher.webp index 11284884..d503b560 100644 Binary files a/composeApp/src/androidMain/res/mipmap-xxhdpi/ic_launcher.webp and b/composeApp/src/androidMain/res/mipmap-xxhdpi/ic_launcher.webp differ diff --git a/composeApp/src/androidMain/res/mipmap-xxhdpi/ic_launcher_round.webp b/composeApp/src/androidMain/res/mipmap-xxhdpi/ic_launcher_round.webp index 7383e42f..331e6945 100644 Binary files a/composeApp/src/androidMain/res/mipmap-xxhdpi/ic_launcher_round.webp and b/composeApp/src/androidMain/res/mipmap-xxhdpi/ic_launcher_round.webp differ diff --git a/composeApp/src/androidMain/res/mipmap-xxxhdpi/ic_launcher.webp b/composeApp/src/androidMain/res/mipmap-xxxhdpi/ic_launcher.webp index 457bec74..227715a3 100644 Binary files a/composeApp/src/androidMain/res/mipmap-xxxhdpi/ic_launcher.webp and b/composeApp/src/androidMain/res/mipmap-xxxhdpi/ic_launcher.webp differ diff --git a/composeApp/src/androidMain/res/mipmap-xxxhdpi/ic_launcher_round.webp b/composeApp/src/androidMain/res/mipmap-xxxhdpi/ic_launcher_round.webp index 057b32d4..585292b7 100644 Binary files a/composeApp/src/androidMain/res/mipmap-xxxhdpi/ic_launcher_round.webp and b/composeApp/src/androidMain/res/mipmap-xxxhdpi/ic_launcher_round.webp differ diff --git a/composeApp/src/androidMain/res/values/ic_launcher_background.xml b/composeApp/src/androidMain/res/values/ic_launcher_background.xml index c5d5899f..e222c5d9 100644 --- a/composeApp/src/androidMain/res/values/ic_launcher_background.xml +++ b/composeApp/src/androidMain/res/values/ic_launcher_background.xml @@ -1,4 +1,4 @@ - #FFFFFF + #FF3A1A \ No newline at end of file diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 727f9cca..34a39c2d 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -500,129 +500,8 @@ Couldn't ask the group to sign this post. Posted %1$s A reply - Curated schemas - This group hasn't published a curated schema yet. A schema defines a list anyone can suggest entries to and only the group can curate. - - No schemas yet - 1 schema - %1$s schemas - Add schema - Edit schema - Propose schema - Fields: %1$s - - Start a list - A list is a schema: what an entry may contain, who may suggest one, and where it lives. The group signs it with its shared key, and only that key can put an entry on the list. - Pick a shape to start from. Everything in it can be changed before the group signs. - Links & text - Reddit’s default: a title with a link or some text, a picture if you like, and a flair. - Discussion - Text posts only: a title and a body, with a flair. - Catalogue - bitcoin.mov’s shape: things with a year, a type, an external id and links — one entry per thing however often it is suggested. - Custom - Just the two fields every list has — an identifier and a title — and whatever you add. - Public - Closed - Private - Anyone may suggest an entry, and anyone may read the list. - Only the group and the suggesters below may suggest. Anyone may read the list. - Only the group and the suggesters below may suggest, and clients show the list to them alone. Relays are open, so this is a convention rather than a secret. - What an entry in this list may contain, and who may suggest one - The group signs a curated schema, so it takes a quorum. Suggestions reply to it, and only the group can accept them into the list. - This group has no shared key, so it cannot sign a curated schema. Run a shared key ceremony first. - Couldn't ask the group to sign this schema. - Identifier - eg. bitcoin.mov - The identifier names this list in every reply to it, so it can't change. Add a schema to start another list. - Title - eg. bitcoin.mov suggestion - Description - eg. Fields for a bitcoin.mov entry: a film, with at least one link to watch it - Visibility - Domain - eg. example.com - A domain replaces the name wherever the list is shown. It's a claim rather than proof, so only set one the group controls. - Fields - Add field - Required - Optional - Derived - At least one of - Add rule - Pick two or more fields, at least one of which an entry must have. A rule with fewer than two is dropped. - Suggesters - Pubkeys besides the group that may suggest to this list. - npub or hex pubkey - Add suggester - That isn't a pubkey. Paste an npub or 64 hex characters. - That pubkey is already a suggester. - Where suggestions and entries are published to and read from. Signed into the schema, so a reply can't be sent anywhere else. - No relays named, so a client will pick its own. - New field - Edit field - Field name - eg. watchUrl - Label - eg. Watch / reference url - Placeholder - eg. https://youtube.com/watch?v=… - Type - An entry must have this field - Writes to tag - Defaults to the field name. "content" means the event's body. - Marker - eg. watch - The tag's third element, which tells fields sharing a tag apart. - Maximum characters - Maximum value - Minimum value - Options - One per line, or separated by commas. - https only - May appear more than once - Pattern - A regular expression the whole value must match. - Filled in by the app, never asked for - Hint - Helper text under the input. - Done - Remove field - A field needs a name. - A field name is one word, with no spaces. - A field named that already exists. - An identifier is required. - The identifier must be at most %1$s characters. - A title is required. - The title must be at most %1$s characters. - A name is required. - The name must be at most %1$s characters. - A description is required. - The description must be at most %1$s characters. - Say who may suggest to this list. - The picture must be an https url. - That isn't a domain name. - A schema needs at least one field. - One of the relays isn't a relay address. - eg. 2100 - eg. 200 - eg. 1900 - eg. movie, documentary, short - eg. [A-Za-z]{2,8} - Text - Long text - Token - Url - Image - One of a list - Year - Duration in seconds - Number - Date - Latest year - Earliest year Propose event - Paste an unsigned Nostr event for the group to sign. It is filed by kind: a profile (kind 0), a post (kind 1), a relay list, or a curated schema (kind 31889). + Paste an unsigned Nostr event for the group to sign. It is filed by kind: a profile (kind 0), a post (kind 1) or a relay list. The group signs it, so it takes a quorum. The author is the group and the time is now, whatever the paste says about either. This group has no shared key, so it cannot sign an event. Run a shared key ceremony first. Couldn't ask the group to sign this event. @@ -637,61 +516,7 @@ Tags must be a list of lists of strings. Content must be text. The content isn't a profile. A kind 0 carries a JSON object of profile fields. - This schema can't be signed as it is: - View suggestions - Suggestions - Everything anyone has suggested to this list, newest first. Only the group can take one up into the list. - 1 suggestion - %1$s suggestions - %1$s curated - Read from %1$s - Asking the list's relays… - Nobody has suggested anything to this list yet. Ask again - Curated - Suggested by %1$s on %2$s - Taken up by the group into the list. - Accept this suggestion - Revise the list's entry - - Take this suggestion into %1$s, edited as the group wants it. The entry keeps the suggestion's identifier and points back at it, so the suggester is credited. - The group signs an entry, so it takes a quorum. Nothing changes until one has. - This group has no shared key, so it cannot sign an entry. Run a shared key ceremony first. - The group already has an entry for this. Proposing again revises it in place rather than adding a second one. - Propose entry - Couldn't ask the group to sign this entry. Please try again. - This entry can't be signed as it is: - The entry can't be signed as it is. - Kept from the suggestion - Filled in by the suggester's app and kept as they came, the identifier among them, so that an entry accepted twice lands on the same coordinate. - Add another - This field is required. - Only one value for this field. - One word, without spaces. - That is not a web address. - That must be an https address. - Pick one of the options. - A whole number. - More than zero. - A date, as YYYY, YYYY-MM or YYYY-MM-DD. - At least %1$s. - At most %1$s. - %1$s or later. - %1$s or earlier. - This list uses a field type this app doesn't support (%1$s). - At most %1$s characters. - Must match %1$s. - At least one of these is needed: %1$s. - %1$s: %2$s - - Curated entries - This group hasn't accepted anything into a list yet. An entry a quorum signs is shown here, and reaches the list's readers once it is broadcast. - - No entries yet - 1 entry - %1$s entries - In %1$s - Suggested by %1$s Broadcast Sends the event to each relay below, exactly as the group signed it. Any member holding it can send it: the signature is the group's, not yours. @@ -706,12 +531,6 @@ Accepted by %1$s of %2$s relays. Copy raw JSON Copied the raw JSON - - Broadcast all - Sending entry %1$s of %2$s… - Accepted by every relay for %1$s of %2$s entries. - No relays to send it to: every relay the group named is blocked. - %1$s · %2$s A password-protected key (ncryptsec) is not supported yet. Decrypt it in the app it came from and paste the nsec. Enter a recovery phrase or an nsec to sign in. diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt index 47dae471..dcfc8dac 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt @@ -24,10 +24,7 @@ import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent -import com.machankura.bennu.compose.nostr.GroupCuratedSchema import com.machankura.bennu.compose.nostr.GroupNostrProfile -import com.machankura.bennu.compose.nostr.curated.CuratedEntryEvent -import com.machankura.bennu.compose.nostr.curated.CuratedSchemaEvent import com.machankura.bennu.compose.nostr.GroupRelaySet import com.vitorpamplona.quartz.nipC7Chats.ChatEvent import com.machankura.bennu.compose.nostr.dkg.DkgRitualEvents @@ -474,25 +471,14 @@ data class ChatMessage( const val TYPE_GROUP_POST_SIGNED = "groupPostSigned" /** - * The group signed the schema of a list it curates. - * - * A system line like the other three, and it names the list rather than - * describing the schema: what a reader of the room needs to know is that - * the group now curates -- or has changed the form for -- a list called - * so-and-so, and the schema itself is on the group's screen where its - * fields can be read. + * Lines the curated-lists feature wrote: the group signing a list's schema, + * and an entry into one. The feature is gone and nothing writes either any + * more, but rows already in a transcript still carry them, and a type + * missing from [GROUP_IDENTITY_TYPES] renders as a chat bubble -- so they + * stay, as names only, to keep those rows system lines. */ - const val TYPE_GROUP_SCHEMA_SIGNED = "groupSchemaSigned" - - /** - * The group signed an entry into a list it curates. - * - * A system line like the schema's, and it names the entry and the list - * rather than the fields: what a reader of the room needs to know is - * that the list now stands behind a title, and the entry itself is on - * the queue screen where its fields can be read. - */ - const val TYPE_GROUP_ENTRY_CURATED = "groupEntryCurated" + private const val TYPE_LEGACY_GROUP_SCHEMA_SIGNED = "groupSchemaSigned" + private const val TYPE_LEGACY_GROUP_ENTRY_CURATED = "groupEntryCurated" /** * The group opened a wallet. @@ -515,8 +501,8 @@ data class ChatMessage( TYPE_GROUP_PROFILE_SIGNED, TYPE_GROUP_RELAYS_SIGNED, TYPE_GROUP_POST_SIGNED, - TYPE_GROUP_SCHEMA_SIGNED, - TYPE_GROUP_ENTRY_CURATED, + TYPE_LEGACY_GROUP_SCHEMA_SIGNED, + TYPE_LEGACY_GROUP_ENTRY_CURATED, TYPE_GROUP_WALLET_OPENED, TYPE_GROUP_TRANSACTION_CONFIRMED, ) @@ -1717,79 +1703,6 @@ data class ChatMessage( ) } - // The group defining a list it curates: the kind 31889 that - // suggestions from anyone reply to and only the group's own key can - // accept into the list. - // - // Verified and parsed, and null on either failing, the way the - // profile arm is. A rumor of this kind from a member is not the - // group curating anything, and a schema the room signed but that no - // client could act on -- no visibility, no fields -- is not worth a - // line saying it did. `GroupCuratedSchema` refuses the same event - // on the group's screen, so the transcript and the screen agree. - CuratedSchemaEvent.KIND -> { - val curated = GroupCuratedSchema.of( - signedEvent = GroupSignedEvent.fromEvent(event, chatRoomId = groupId), - chatRoomId = groupId, - ) ?: return null - - ChatMessage( - giftWrapPayloadId = null, - messageType = TYPE_GROUP_SCHEMA_SIGNED, - marmotGroupEventId = marmotGroupEventId, - marmotInnerEventId = marmotInnerEventId, - senderPublicKey = senderPublicKey, - isUserMessage = isUserMessage, - chatRoomId = groupId, - createdAt = createdAt, - content = "The group signed the curated schema for " + - curated.schema.displayName() - ) - } - - // The group taking an entry into a list it curates: the kind - // 31890 that only its own key can publish, and the thing the - // queue screen marks a suggestion "curated" by once it is read - // back off a relay. - // - // Verified, for the reason the schema arm is: a rumor of this - // kind from a member is not the group curating anything. Named - // after the list where this device holds its schema -- looked - // up by the coordinate the entry replies to -- and after the - // entry alone where it does not, since the entry is what was - // signed either way. - CuratedEntryEvent.CANONICAL_KIND -> { - val signed = GroupSignedEvent.fromEvent(event, chatRoomId = groupId) - if (!signed.verifies()) return null - - val entry = CuratedEntryEvent.headline(event) - val title = entry.title.ifBlank { entry.identifier }.ifBlank { "an entry" } - - val list = runCatching { - GroupCuratedSchema.newestPerListAmong( - signedEvents = database.groupSignedEventDao() - .getByChatRoomIdAndKind(groupId, CuratedSchemaEvent.KIND), - chatRoomId = groupId, - ).firstOrNull { it.isRepliedToBy(event.tags) } - }.getOrNull() - - ChatMessage( - giftWrapPayloadId = null, - messageType = TYPE_GROUP_ENTRY_CURATED, - marmotGroupEventId = marmotGroupEventId, - marmotInnerEventId = marmotInnerEventId, - senderPublicKey = senderPublicKey, - isUserMessage = isUserMessage, - chatRoomId = groupId, - createdAt = createdAt, - content = if (list != null) { - "The group accepted $title into ${list.schema.displayName()}" - } else { - "The group accepted $title into a list it curates" - } - ) - } - // v2's two non-chat kinds. A kind:1210 that arrives is one member's // assertion about what the group's state became, and this device // derives that for itself from the commit it applied (see diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseChatRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseChatRepository.kt index 650e3379..67f0128e 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseChatRepository.kt @@ -20,11 +20,7 @@ import com.machankura.bennu.compose.managers.GroupKeyStateManager import com.machankura.bennu.compose.managers.MarmotGroupCreation import com.machankura.bennu.compose.managers.SubgroupManager import com.machankura.bennu.compose.nostr.GroupNostrProfile -import com.machankura.bennu.compose.nostr.GroupCuratedEntry -import com.machankura.bennu.compose.nostr.GroupCuratedSchema import com.machankura.bennu.compose.nostr.GroupPost -import com.machankura.bennu.compose.nostr.curated.CuratedEntryEvent -import com.machankura.bennu.compose.nostr.curated.CuratedSchemaEvent import com.machankura.bennu.compose.nostr.GroupRelayList import com.machankura.bennu.compose.nostr.GroupRelaySet import com.machankura.bennu.compose.database.model.ChatMessage @@ -191,31 +187,6 @@ class DatabaseChatRepository( emptyList() } - override suspend fun groupCuratedSchemas(chatRoomId: String): List = try { - GroupCuratedSchema.newestPerListAmong( - signedEvents = database.groupSignedEventDao() - .getByChatRoomIdAndKind(chatRoomId, CuratedSchemaEvent.KIND), - chatRoomId = chatRoomId, - ) - } catch (e: Throwable) { - logger.e("Error reading the curated schemas of $chatRoomId", e) - emptyList() - } - - override suspend fun groupCuratedEntries(chatRoomId: String): List = try { - // The schemas first, because an entry is read against the list it - // replies to and there is nothing to read one by without them. - GroupCuratedEntry.newestPerEntryAmong( - signedEvents = database.groupSignedEventDao() - .getByChatRoomIdAndKind(chatRoomId, CuratedEntryEvent.CANONICAL_KIND), - chatRoomId = chatRoomId, - schemas = groupCuratedSchemas(chatRoomId), - ) - } catch (e: Throwable) { - logger.e("Error reading the curated entries of $chatRoomId", e) - emptyList() - } - override suspend fun groupWallet(chatRoomId: String, chain: Chain): GroupWallet? = try { GroupWalletManager.walletFor(database, chatRoomId, chain) } catch (e: Throwable) { diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/CuratedSuggestion.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/CuratedSuggestion.kt deleted file mode 100644 index cfe3a422..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/CuratedSuggestion.kt +++ /dev/null @@ -1,115 +0,0 @@ -package com.machankura.bennu.compose.nostr - -import com.machankura.bennu.compose.database.GENESIS_AT -import com.machankura.bennu.compose.database.model.NostrEvent -import com.machankura.bennu.compose.database.model.Profile -import com.machankura.bennu.compose.database.model.intermdiate.LocalNostrEvent -import com.machankura.bennu.compose.extensions.shortened -import com.machankura.bennu.compose.nostr.curated.CuratedEntry -import com.machankura.bennu.compose.nostr.curated.CuratedEntryEvent -import kotlin.time.Instant - -/** - * One suggestion to a list the group curates, as somebody published it and as - * this device has read it. - * - * The schema is the group asking; these are the answers. Anyone may publish one - * -- that is the point of a list -- so unlike everything else on the group's - * screen a suggestion is not the group's word and was never signed in the room. - * It is a `NostrEvent` off a relay, signature-checked on the way in like every - * other, and then checked against the schema it replies to, because a relay is - * an untrusted place and an entry that does not satisfy the schema is not shown - * with the bad parts blanked out. See [CuratedEntryEvent]. - * - * ### The queue and the list - * - * The NIP's words: the canonical entries are the list, and the suggestions are - * its queue. This is the queue. A suggestion is marked [isCurated] when a - * canonical entry the *group* signed shares its identifier -- the coordinate - * both land on -- which is how a reader tells what the group has already taken - * up from what is still waiting. Only the group's own canonical entries count: - * curation is the one power a schema does not delegate, and a kind 31890 from - * anybody else is somebody else's list. - */ -data class CuratedSuggestion( - /** The entry, keyed by the schema's field names. */ - val entry: CuratedEntry, - /** The event as it was stored, for the id and the tags: what a canonical entry points back at. */ - val event: NostrEvent, - /** The suggester's profile where one has arrived, else null. */ - val suggester: Profile?, - /** Whether a canonical entry by the group shares this suggestion's identifier. */ - val isCurated: Boolean, -) { - val id: String get() = event.id - - val suggestedAt: Instant get() = event.createdAt - - /** - * What to call the suggester: their name where a profile has arrived and is - * a real one, else a short key. A placeholder profile is the one the indexer - * writes the moment a pubkey is first seen, and it is named "LOADING..." -- - * which is not a name. - */ - fun suggesterName(): String = - suggester?.takeUnless { it.createdAt == GENESIS_AT }?.humanReadableNameOrPubkey() - ?: entry.pubKey.shortened() - - companion object { - /** - * The queue of [schema], read off [events], newest first. - * - * Two readings over the same rows. Every kind 31888 that satisfies the - * schema and replies to its coordinate is a suggestion; every kind 31890 - * that does the same *and* is signed by the group is a canonical entry. - * Both kinds are addressable, so among events sharing a coordinate the - * newest is the entry and the rest are its history -- the client-side - * merge that realises an edit, since different relays hold different - * latest versions. Then the canonical identifiers mark the suggestions. - * - * Newest first because that is the order a queue is read in, and the id - * breaking every tie so two devices reading the same events in different - * orders show the same thing. - */ - fun queueOf(schema: GroupCuratedSchema, events: List): List { - val coordinate = schema.coordinate() - - val entries = events.mapNotNull { local -> - val event = local.nostrEvent.toEvent() - - when (event.kind) { - CuratedEntryEvent.SUGGESTION_KIND -> - CuratedEntryEvent.suggestion(event, schema.schema, coordinate) - CuratedEntryEvent.CANONICAL_KIND -> - CuratedEntryEvent.canonical(event, schema.schema, coordinate, curator = schema.publicKey) - else -> null - }?.let { entry -> local to entry } - } - .groupBy { (_, entry) -> entry.coordinate() } - .values - .map { versions -> - versions.maxWith(compareBy({ (_, entry) -> entry.createdAt }, { (_, entry) -> entry.id })) - } - - val curatedIdentifiers = entries - .filter { (_, entry) -> entry.isCanonical } - .map { (_, entry) -> entry.identifier } - .toSet() - - return entries - .filterNot { (_, entry) -> entry.isCanonical } - .map { (local, entry) -> - CuratedSuggestion( - entry = entry, - event = local.nostrEvent, - suggester = local.profile, - isCurated = entry.identifier in curatedIdentifiers, - ) - } - .sortedWith( - compareByDescending { it.entry.createdAt } - .thenByDescending { it.entry.id } - ) - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/GroupCuratedEntry.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/GroupCuratedEntry.kt deleted file mode 100644 index 6101b5ed..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/GroupCuratedEntry.kt +++ /dev/null @@ -1,135 +0,0 @@ -package com.machankura.bennu.compose.nostr - -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.machankura.bennu.compose.nostr.curated.CuratedEntry -import com.machankura.bennu.compose.nostr.curated.CuratedEntryEvent -import kotlin.time.Instant - -/** - * A canonical entry the group signed: a suggestion it accepted into one of - * the lists it curates, as the list's own word. - * - * Kind 31890 -- see [CuratedEntryEvent] -- authored by the room's own key, - * which is the one key a list's readers accept a canonical entry from. Where - * the schema is the group asking and the queue is what strangers answered, - * this is what the group *decided*: the entries the list stands behind, each - * one a quorum's signature over a suggestion, edited or not, with a pointer - * back at who suggested it. - * - * ### Read against the list it replies to - * - * An entry replies to a schema by coordinate, so the reading needs the - * group's schemas as well as its signed events: the one whose coordinate the - * entry's `a` root names is the list it belongs to, and the entry is then - * checked against that list's fields exactly as `CuratedSuggestion.queueOf` - * checks a copy that came back off a relay. The two readings agree by - * construction, so what this screen shows as accepted is what the queue will - * mark as curated once the entry has been broadcast and read back. - * - * An entry replying to a list this device holds no schema for is not shown: - * without the schema there are no fields to read it by, and no way to say - * which list it is in. - * - * ### One per coordinate - * - * The kind is addressable, so re-curating an entry -- to take in a - * suggester's edit, or to fix the group's own -- is a newer event under the - * same `d`, and the newest is the entry the way the newest schema is the - * list. The coordinate is `31890::` whatever list the entry replies - * to, so the same `d` accepted into two of the group's lists is one - * coordinate and the newer event replaces the older, on relays and here - * alike. An identifier is the entry's rather than the list's, which is the - * reference client's reading too: its `d` is an external id that names the - * same film in every list. - * - * ### Nothing here has reached a relay - * - * The same caveat as the schema, and here it is the one that matters: the - * queue screen marks a suggestion curated only from a copy read back off the - * list's relays, so until a member broadcasts an entry from this section the - * queue still shows it waiting. The broadcast button under each card is how - * it gets there, or the one at the bottom of the entries screen that sends - * all of them. - */ -data class GroupCuratedEntry( - /** The group's statement, whole, with the signature that makes it one. */ - val signedEvent: GroupSignedEvent, - /** The list the entry is in, as the group last signed its schema. */ - val list: GroupCuratedSchema, - /** What the statement says, keyed by the list's fields, and where it came from. */ - val entry: CuratedEntry, -) { - /** The group's nostr identity, which for a derived room is also its id. */ - val publicKey: HexKey get() = signedEvent.publicKey - - /** When the group signed it, which is the order entries are read in. */ - val signedAt: Instant get() = signedEvent.createdAt - - /** The entry's `d`, which with the group's key is its coordinate. */ - val identifier: String get() = entry.identifier - - val title: String get() = entry.title - - /** `31890::`. Two events sharing one are versions of one entry. */ - fun coordinate(): String = entry.coordinate() - - companion object { - /** - * The reading of one signed event against the group's [schemas], or - * null when it is not one of these. - * - * Four ways to be null and they are all the same refusal: the wrong - * kind, a signature that does not check out as [chatRoomId]'s, a root - * naming no list this device holds, or an entry the list's own fields - * refuse. A caller gets an entry the group really signed into a list it - * really curates, or gets nothing. - */ - fun of( - signedEvent: GroupSignedEvent, - chatRoomId: String, - schemas: List, - ): GroupCuratedEntry? { - if (signedEvent.kind != CuratedEntryEvent.CANONICAL_KIND) return null - if (!signedEvent.verifies()) return null - - val list = schemas.firstOrNull { it.isRepliedToBy(signedEvent.tags) } ?: return null - - val entry = CuratedEntryEvent.canonical( - event = signedEvent.toEvent(), - schema = list.schema, - coordinate = list.coordinate(), - curator = list.publicKey, - ) ?: return null - - return GroupCuratedEntry(signedEvent = signedEvent, list = list, entry = entry) - } - - /** - * The newest version of every entry [chatRoomId] signed among - * [signedEvents], most recently signed first. - * - * Newest per coordinate because the kind is addressable and a - * re-curation is a newer event under the same `d`; newest first so that - * what the group last decided is at the top, and the id breaking every - * tie so that two devices reading the same events in different orders - * show the same thing. - */ - fun newestPerEntryAmong( - signedEvents: List, - chatRoomId: String, - schemas: List, - ): List = - signedEvents - .mapNotNull { of(it, chatRoomId, schemas) } - .groupBy { it.coordinate() } - .values - .map { versions -> - versions.maxWith(compareBy({ it.signedAt }, { it.signedEvent.id })) - } - .sortedWith( - compareByDescending { it.signedAt } - .thenByDescending { it.signedEvent.id } - ) - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/GroupCuratedSchema.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/GroupCuratedSchema.kt deleted file mode 100644 index bca0ad8d..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/GroupCuratedSchema.kt +++ /dev/null @@ -1,209 +0,0 @@ -package com.machankura.bennu.compose.nostr - -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.machankura.bennu.compose.database.model.types.SynchronizationFilter -import com.machankura.bennu.compose.nostr.curated.CuratedEntryEvent -import com.machankura.bennu.compose.nostr.curated.CuratedEntryProblem -import com.machankura.bennu.compose.nostr.curated.CuratedSchema -import com.machankura.bennu.compose.nostr.curated.CuratedSchemaEvent -import com.machankura.bennu.compose.nostr.curated.CuratedSuggestionRef -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate -import kotlin.time.Instant - -/** - * A curated schema the group signed: a list it curates, as the group defined it. - * - * Kind 31889 -- see [CuratedSchemaEvent] -- authored by the room's own key. That - * makes the group the curator of the list the schema describes: anyone may reply - * to it with a suggestion, and only an event signed by the same key counts as the - * list itself. For a group that means the same thing everything else on its screen - * means: a quorum decides what goes in. - * - * ### Several per group, one per identifier - * - * Unlike a profile, of which a group has one, a group may curate several lists, - * and each is its own coordinate `31889::`. So the reading is per - * identifier: among the events sharing a `d` the newest wins, the way it does for - * a profile, because the kind is addressable and re-signing one is how a schema - * is edited. Two different identifiers are two lists and both are shown. - * - * Read off [GroupSignedEvent] and gated on [GroupSignedEvent.verifies], for the - * reasons `GroupNostrProfile` gives at length: a group-signed event is not a - * `NostrEvent`, and only an event the room itself signed is the group speaking. - * - * ### Nothing here has reached a relay - * - * The same caveat as the profile, the relay lists and the posts. A schema is the - * one statement here that exists to be *replied to* by strangers, so until it is - * published the list it defines has no queue -- the relays it names say where - * suggestions would go, and nothing yet puts the schema there for them to find. - * The queue is read all the same, by `CuratedSuggestion.queueOf` over whatever - * those relays hold for [coordinate], so a schema that reached a relay by some - * other road has its suggestions shown here. - */ -data class GroupCuratedSchema( - /** The group's statement, whole, with the signature that makes it one. */ - val signedEvent: GroupSignedEvent, - /** What the statement says, already checked and normalized. */ - val schema: CuratedSchema, -) { - /** The group's nostr identity, which for a derived room is also its id. */ - val publicKey: HexKey get() = signedEvent.publicKey - - /** When the group signed it, which is what decides the newest of two. */ - val signedAt: Instant get() = signedEvent.createdAt - - /** The schema's `d`, and the last part of its coordinate. */ - val identifier: String get() = schema.identifier - - /** What a suggestion's `a` root names to reply to this list. */ - fun coordinate(): String = CuratedSchemaEvent.coordinate(publicKey, identifier) - - /** - * Whether an entry carrying [tags] replies to this list: its `a` tags - * include this coordinate. How a reader holding several of the group's - * schemas tells which one an entry belongs to. - */ - fun isRepliedToBy(tags: Array>): Boolean = - tags.any { it.size > 1 && it[0] == COORDINATE_TAG && it[1] == coordinate() } - - /** - * What to ask a relay for to read this list's queue: the NIP's two queries, - * as one request. - * - * Everything suggested to the list is whatever anyone published in reply - * to the coordinate; the list itself is what the *group* published in reply - * to it. The `authors` on the second is redundant with the rule that only - * the curator's canonical entries count -- `CuratedSuggestion.queueOf` - * enforces that on the way in regardless -- and is there to spare the relay - * the work. Both land in the same table, and [queueReadFilter] is how they - * are read back. - */ - fun queueFilters(): Array = arrayOf( - SynchronizationFilter( - kinds = arrayOf(schema.suggestionKind), - tags = mapOf(COORDINATE_TAG to listOf(coordinate())), - limit = QUEUE_LIMIT, - ), - SynchronizationFilter( - kinds = arrayOf(CuratedSchemaEvent.CANONICAL_KIND), - authors = arrayOf(publicKey), - tags = mapOf(COORDINATE_TAG to listOf(coordinate())), - limit = QUEUE_LIMIT, - ), - ) - - /** - * What to watch locally for the same rows: both kinds, replying to the - * coordinate. One filter rather than two because the local store is a - * single table and the reading tells the kinds apart itself. - */ - fun queueReadFilter(): SynchronizationFilter = SynchronizationFilter( - kinds = arrayOf(schema.suggestionKind, CuratedSchemaEvent.CANONICAL_KIND), - tags = mapOf(COORDINATE_TAG to listOf(coordinate())), - ) - - /** - * The event to ask the group to sign to take an entry into the list: - * [values] as this schema lays them out, rooted at [coordinate], with the - * group as the curator and [source] as the suggestion it came from. - * - * The group is the curator, so its key is the `p` on the root and the only - * author [verifyCanonical] will accept. See [CuratedEntryEvent.canonicalTemplate] - * for what is and is not done to the values on the way through. - */ - fun canonicalTemplate( - values: Map>, - source: CuratedSuggestionRef?, - ): EventTemplate<*> = CuratedEntryEvent.canonicalTemplate( - schema = schema, - coordinate = coordinate(), - curator = publicKey, - values = values, - source = source, - ) - - /** - * Every reason this list's readers would refuse [template] as one of its - * own entries, or nothing. - * - * The same check `CuratedSuggestion.queueOf` makes on a kind 31890 off a - * relay, made before the group is asked to sign one: a signature is the - * most expensive thing this app does, and an entry the queue would then - * refuse to count is a quorum spent on nothing. And one check the queue - * does not make, first: a required field this app cannot write is one - * every other client's queue would refuse the entry for, see - * [CuratedEntryEvent.verifyWritable]. - */ - fun verifyCanonical(template: EventTemplate<*>): List = - CuratedEntryEvent.verifyWritable(schema) + CuratedEntryEvent.verifyCanonical( - event = CuratedEntryEvent.preview(template, publicKey), - schema = schema, - coordinate = coordinate(), - curator = publicKey, - ) - - companion object { - /** The tag a reply carries its schema's coordinate in. */ - private const val COORDINATE_TAG = "a" - - /** - * How much of a queue one request asks for: the reference client's - * window, and more than any list here is likely to have. NIP-01 scopes - * a limit to the stored events a relay sends before EOSE, so a longer - * queue is read on the next visit rather than never. - */ - private const val QUEUE_LIMIT = 500 - - /** - * The reading of one signed event, or null when it is not one of these. - * - * Three ways to be null and they are all the same refusal: the wrong - * kind, a signature that does not check out as [chatRoomId]'s, or tags - * that do not make a usable schema. A caller gets a schema the group - * really signed and a client could really act on, or gets nothing. - */ - fun of(signedEvent: GroupSignedEvent, chatRoomId: String): GroupCuratedSchema? { - if (signedEvent.kind != CuratedSchemaEvent.KIND) return null - if (!signedEvent.verifies()) return null - - val schema = CuratedSchemaEvent.parse(signedEvent.toEvent()) ?: return null - - return GroupCuratedSchema(signedEvent = signedEvent, schema = schema) - } - - /** - * The newest schema per identifier [chatRoomId] signed among - * [signedEvents], most recently signed list first. - * - * Newest per identifier because the kind is addressable and an edit is a - * newer event under the same `d`; newest list first so that an edit - * surfaces, and the id breaking every tie so that two devices reading the - * same events in different orders show the same thing. - */ - fun newestPerListAmong( - signedEvents: List, - chatRoomId: String, - ): List = - signedEvents - .mapNotNull { of(it, chatRoomId) } - .groupBy { it.identifier } - .values - .map { versions -> - versions.maxWith(compareBy({ it.signedAt }, { it.signedEvent.id })) - } - .sortedWith( - compareByDescending { it.signedAt } - .thenByDescending { it.signedEvent.id } - ) - - /** - * The event to ask the group to sign for [schema]. - * - * Built from the schema alone -- see [CuratedSchemaEvent.template] for - * why an edit does not carry the last event's tags forward. - */ - fun template(schema: CuratedSchema): EventTemplate<*> = CuratedSchemaEvent.template(schema) - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/GroupEventProposal.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/GroupEventProposal.kt index 148894a0..8d65a414 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/GroupEventProposal.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/GroupEventProposal.kt @@ -1,8 +1,6 @@ package com.machankura.bennu.compose.nostr import com.machankura.bennu.compose.network.serialization.CommonJson -import com.machankura.bennu.compose.nostr.curated.CuratedSchemaEvent -import com.machankura.bennu.compose.nostr.curated.CuratedSchemaProblem import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.Kind import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent @@ -18,15 +16,14 @@ import kotlinx.serialization.json.intOrNull * An unsigned event a member pasted for the group to sign, read and checked * before a quorum is asked for it. * - * The typed editors -- the profile form, the post composer, the relay and - * schema editors -- each build one kind of event and know what it needs. This - * is the untyped way in: the event as JSON, the way another tool prints it - * (`npm run schema:dry` in the bitcoin.mov repo prints exactly the schema event - * it would publish), pasted whole. What comes out is the same thing the editors + * The typed editors -- the profile form, the post composer, the relay + * editor -- each build one kind of event and know what it needs. This is the + * untyped way in: the event as JSON, the way another tool prints it, pasted + * whole. What comes out is the same thing the editors * produce, a kind, tags and content for `FrostSigningRepository.proposeSigning`, * and it is filed the same way when the quorum signs: `FrostSigningManager.complete` * records it as a `GroupSignedEvent` and the group's screen reads its profile, - * posts, relay lists and schemas straight off those by kind. + * posts and relay lists straight off those by kind. * * ### What is ignored * @@ -41,10 +38,9 @@ import kotlinx.serialization.json.intOrNull * * Only kinds the group's screen has a place for, and only events that place * would accept. A signature is the most expensive thing this app does, and the - * readers refuse rather than repair: a kind 0 whose content is not a profile, - * a blank post, a schema with no visibility would each be signed, filed and - * shown nowhere, with nothing to tell the member their quorum was spent on - * nothing. So every check a reader makes is made here first, on the paste. + * readers refuse rather than repair: a kind 0 whose content is not a profile + * or a blank post would each be signed, filed and shown nowhere, with nothing + * to tell the member their quorum was spent on nothing. So every check a reader makes is made here first, on the paste. */ object GroupEventProposal { /** @@ -57,7 +53,7 @@ object GroupEventProposal { * group's screen", because that is where a member goes to see it landed. */ val ACCEPTED_KINDS: Set = - setOf(MetadataEvent.KIND, TextNoteEvent.KIND, CuratedSchemaEvent.KIND) + GroupRelaySet.KINDS + setOf(MetadataEvent.KIND, TextNoteEvent.KIND) + GroupRelaySet.KINDS sealed interface Reading @@ -105,9 +101,6 @@ object GroupEventProposal { /** A kind 1 with nothing to say, which the posts reader would drop. */ data object PostBlank : Refused - - /** A kind 31889 the schema reader would refuse, with its reasons. */ - data class SchemaUnusable(val problems: List) : Refused } private const val KEY_KIND = "kind" @@ -156,10 +149,6 @@ object GroupEventProposal { Ready(kind, tags, content) } - CuratedSchemaEvent.KIND -> CuratedSchemaEvent.read(tags, content).problems().let { problems -> - if (problems.isEmpty()) Ready(kind, tags, content) else Refused.SchemaUnusable(problems) - } - // A relay list with no relay in it is a list the group has withdrawn, // which the relays card shows as "no relays" rather than as nothing. else -> Ready(kind, tags, content) diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/curated/CuratedEntryEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/curated/CuratedEntryEvent.kt deleted file mode 100644 index bea4cf30..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/curated/CuratedEntryEvent.kt +++ /dev/null @@ -1,677 +0,0 @@ -package com.machankura.bennu.compose.nostr.curated - -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.Kind -import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate -import kotlin.time.Clock - -/** - * Kinds 31888 and 31890: an entry in a curated list, as somebody suggested it and - * as the curator accepted it. - * - * The two are one shape. A suggestion is a reply to a schema carrying one tag - * per field the schema defines; a canonical entry is the same tags again, signed - * by the curator, with an optional pointer back at the suggestion it came from. - * They are read by one reader and checked by one verifier, and only the kind, - * the signer and the pointer tell them apart -- which is what lets the list - * stand on its own if a suggester deletes their entry. - * - * This is the other half of [CuratedSchemaEvent]: that is what a list *asks* - * for, this is what it *gets*. Ported from the reference module's `verifyEntry` - * rule for rule, so that an entry bitcoin.mov accepts is one this app accepts - * and an entry it refuses is refused here for the same reason. The write side, - * [canonicalTemplate], is the port of its `buildCuratedCanonicalTemplate`, and - * walks the same field list as [read] so the two cannot drift. - * - * ### Rejected, not repaired - * - * The NIP is explicit: a client MUST verify an entry against its schema and - * MUST reject one that does not satisfy it, rather than showing it with the - * offending parts blanked out. Relays carry malformed, partial and hostile - * events from other applications, and a half-parsed entry is worse than a - * missing one. So [suggestion] and [canonical] return the entry whole or return - * null, and [verifySuggestion] and [verifyCanonical] say why. - */ -object CuratedEntryEvent { - /** The kind anyone publishes a suggestion under. */ - const val SUGGESTION_KIND: Kind = CuratedSchemaEvent.SUGGESTION_KIND - - /** The kind the curator republishes an accepted suggestion as. */ - const val CANONICAL_KIND: Kind = CuratedSchemaEvent.CANONICAL_KIND - - private const val TAG_ADDRESS = "a" - private const val TAG_EVENT = "e" - private const val TAG_IDENTIFIER = "d" - private const val TAG_TITLE = "title" - private const val TAG_PUBKEY = "p" - private const val TAG_KIND = "k" - - /** NIP-10's markers: the schema being replied to, and the suggestion being credited. */ - private const val MARKER_ROOT = "root" - private const val MARKER_MENTION = "mention" - - /** What every schema coordinate starts with, which is how a root is told from a source. */ - private val SCHEMA_PREFIX = "${CuratedSchemaEvent.KIND}:" - - private val SUGGESTION_PREFIX = "$SUGGESTION_KIND:" - - /** - * The entry [event] carries, checked against [schema] as a suggestion to the - * list at [coordinate], or null when it is not one a client should show. - */ - fun suggestion(event: Event, schema: CuratedSchema, coordinate: String): CuratedEntry? = - if (verifySuggestion(event, schema, coordinate).isEmpty()) read(event, schema) else null - - /** - * The entry [event] carries, checked against [schema] as the list's own at - * [coordinate], or null. [curator] is the pubkey that signed the schema, and - * the only one this will accept an author of. - */ - fun canonical(event: Event, schema: CuratedSchema, coordinate: String, curator: HexKey): CuratedEntry? = - if (verifyCanonical(event, schema, coordinate, curator).isEmpty()) read(event, schema) else null - - /** - * The entry as the tags say it, whether or not it satisfies the schema. - * - * Split from [suggestion] and [canonical] for the same reason - * [CuratedSchemaEvent.read] is split from its parse: a reader that wants to - * show *why* -- a test, a form -- verifies separately. Everything here is - * keyed by the schema's field names rather than by tag, because a field is - * what a form and a screen know an entry by; the tag is where it was kept. - */ - fun read(event: Event, schema: CuratedSchema): CuratedEntry { - val values = schema.fields - .associate { field -> field.name to valuesOf(field, event.tags, event.content) } - .filterValues { it.isNotEmpty() } - - return CuratedEntry( - kind = event.kind, - id = event.id, - pubKey = event.pubKey, - createdAt = event.createdAt, - identifier = first(event.tags, TAG_IDENTIFIER)?.trim() ?: "", - title = first(event.tags, TAG_TITLE)?.trim() ?: "", - values = values, - source = if (event.kind == CANONICAL_KIND) source(event.tags) else null, - ) - } - - /** - * The parts of an entry that need no schema to read: its identifier, its - * title and, for a canonical entry, where it came from. - * - * For a reader that has the event and not the list -- the signing screen, - * the transcript -- and wants to say which entry this is rather than check - * it. [CuratedEntry.values] is empty, since without a schema there are no - * fields to key them by. - */ - fun headline(event: Event): CuratedEntry = read(event, NO_SCHEMA) - - /** A schema with no fields, for [headline]: the two lifted tags are read regardless. */ - private val NO_SCHEMA = CuratedSchema(identifier = "", title = "", name = "", description = "", visibility = null) - - /** - * Every reason [event] is not a suggestion to the list at [coordinate], or - * nothing. - * - * The NIP's seven rules in the NIP's order: the kind is the suggestion kind; - * every required field is present; no field without `repeat` appears twice; - * every value matches its field's type and config; every `require-any` group - * is met; the `a` root names the schema; and the author is somebody the - * schema's visibility lets suggest. - */ - fun verifySuggestion(event: Event, schema: CuratedSchema, coordinate: String): List = - verifyEntry(event, schema, coordinate, expectedKind = schema.suggestionKind) - - /** - * Every reason [event] is not the list's own entry at [coordinate], or nothing. - * - * Everything [verifySuggestion] checks, for kind 31890, and two rules on top. - * The author must be [curator]: curation is the one power a schema does not - * delegate, and `visibility` has no bearing on it. And a source reference, - * when there is one, must be a well-formed suggestion coordinate -- a - * malformed one is worse than none, since it credits the wrong person or - * points at an entry nobody suggested. - */ - fun verifyCanonical( - event: Event, - schema: CuratedSchema, - coordinate: String, - curator: HexKey, - ): List = buildList { - addAll(verifyEntry(event, schema, coordinate, expectedKind = CANONICAL_KIND)) - - if (event.pubKey != curator) { - add(CuratedEntryProblem(FIELD_CURATOR, CuratedEntryProblem.Reason.NotTheCurator)) - } - - val source = firstAddress(event.tags, SUGGESTION_PREFIX) - if (source != null && CuratedCoordinate.parse(source) == null) { - add(CuratedEntryProblem(FIELD_SOURCE, CuratedEntryProblem.Reason.SourceMalformed)) - } - } - - /** - * Every reason this app cannot compose an entry under [schema], or nothing: - * one problem per required field whose type it does not know. - * - * The reader's blind spot, seen from the write side. A field of a type this - * app does not know is left out of the reading -- an entry is checked - * against the fields a reader understands, and that tolerance is the NIP's - * -- but an entry *written* without one the schema requires is refused by - * every client that does know the type, for the field it lacks. So it is a - * reason to refuse before a quorum is spent, filed under the field and - * named for what it is, so the member knows it is the app and not the - * entry that falls short. An optional one is left out the way the reading - * leaves it out. - */ - fun verifyWritable(schema: CuratedSchema): List = - schema.unsupportedFields - .filter { it.isRequired } - .map { CuratedEntryProblem(it.name, CuratedEntryProblem.Reason.UnsupportedType) } - - /** - * The unsigned canonical entry for the curator to sign: [values] laid out as - * the schema's tags, rooted at the schema's [coordinate], and pointing back - * at [source] when it came from a suggestion. - * - * The reverse of [read], and the reason a canonical entry and the suggestion - * it came from are one shape: both walk the schema's one field list, so what - * this writes is what [canonical] reads back, field for field. Ported from - * the reference module's `buildCuratedCanonicalTemplate` tag for tag, so - * that an entry this app signs is one bitcoin.mov's list shows. - * - * [values] is keyed by field name the way [CuratedEntry.values] is, derived - * fields included. The reference client derives `d` and `t` for a suggestion - * it is composing; this app composes none, and a suggestion it accepts keeps - * what the suggester's client derived -- the `d` above all, which the NIP - * says a canonical entry SHOULD keep so that re-curating revises the entry - * in place rather than adding a second one. Nothing is clipped or repaired - * on the way through: a value the schema refuses is refused by - * [verifyCanonical] on the result, with the field named, which is what a - * form wants to show. A blank value is not a value and writes nothing, and a - * field without `repeat` writes its first value only. - * - * [relayHint] goes on the root, per NIP-10: where a reader who does not know - * the list can find the schema being replied to. The NIP says it SHOULD be - * the first of the schema's relays, and by default it is. - */ - fun canonicalTemplate( - schema: CuratedSchema, - coordinate: String, - curator: HexKey, - values: Map>, - source: CuratedSuggestionRef? = null, - relayHint: String? = schema.relays.firstOrNull(), - createdAt: Long = Clock.System.now().epochSeconds, - ): EventTemplate { - val (fieldTags, content) = fieldTags(schema, values) - - return EventTemplate( - createdAt = createdAt, - kind = CANONICAL_KIND, - tags = (fieldTags + replyTags(coordinate, curator, relayHint) + sourceTags(source)).toTypedArray(), - content = content, - ) - } - - /** - * [template] as an event the verifiers can read: the kind, the tags, the - * content and [pubKey], which is everything they look at, over a blank id - * and signature, which they do not. For checking what is about to be - * proposed before a quorum is spent on it. - */ - fun preview(template: EventTemplate<*>, pubKey: HexKey): Event = Event( - id = "", - pubKey = pubKey, - createdAt = template.createdAt, - kind = template.kind, - tags = template.tags, - content = template.content, - sig = "", - ) - - /** - * The tags that make an entry a reply to its schema, and nothing else. - * - * The root is the schema's coordinate rather than an event id, because the - * kind is addressable: revising the schema mints a new id and keeps the - * coordinate, and an entry pinned to an id would be orphaned by the first - * edit. `p` and `k` are the reply courtesies the NIP asks for and nothing - * verifies; `a` is what is verified and what relays are queried on. - */ - fun replyTags(coordinate: String, curator: HexKey, relayHint: String?): List> = listOf( - arrayOf(TAG_ADDRESS, coordinate, relayHint ?: "", MARKER_ROOT), - arrayOf(TAG_PUBKEY, curator), - arrayOf(TAG_KIND, CuratedSchemaEvent.KIND.toString()), - ) - - /** - * The values as the schema's tags: one per value at the field's tag, with - * its marker as the third element when it has one, or the body for the - * field that writes there. - */ - private fun fieldTags(schema: CuratedSchema, values: Map>): Pair>, String> { - val tags = mutableListOf>() - var content = "" - - for (field in schema.fields) { - val tag = field.tag() - val marker = field.config.marker - - for (value in values[field.name].orEmpty()) { - val trimmed = value.trim() - if (trimmed.isEmpty()) continue - - if (tag == CuratedFieldConfig.CONTENT_TAG) { - content = trimmed - } else { - tags.add(if (marker != null) arrayOf(tag, trimmed, marker) else arrayOf(tag, trimmed)) - } - - if (field.config.repeat != true) break - } - } - - return tags to content - } - - /** - * Both halves of the pointer back: the coordinate, which follows the - * suggester's later edits, and the id, which pins what the curator actually - * read. They answer different questions, which is why the NIP has both. The - * `p` credits the suggester. - */ - private fun sourceTags(source: CuratedSuggestionRef?): List> { - if (source == null) return emptyList() - - return buildList { - add(arrayOf(TAG_ADDRESS, source.coordinate, "", MARKER_MENTION)) - source.id?.let { add(arrayOf(TAG_EVENT, it, "", MARKER_MENTION)) } - add(arrayOf(TAG_PUBKEY, source.pubKey)) - } - } - - /** - * One value against its field's type and config, or the first thing wrong - * with it. - * - * `max` is a bound on numeric types -- and on the year of a date -- and a - * length on everything else, and a bounded field returns before the length - * check so the two never meet. A pattern the platform cannot compile counts - * as not matched: the schema asked for a check this reader cannot make, and - * an entry it cannot check is one it cannot vouch for. - */ - fun checkValue(field: CuratedField, value: String): CuratedEntryProblem.Reason? { - val trimmed = value.trim() - val config = field.config - - if (trimmed.isEmpty()) return CuratedEntryProblem.Reason.Empty - - when (field.type) { - CuratedFieldType.Text, CuratedFieldType.LongText -> Unit - - CuratedFieldType.Token -> - if (trimmed.any { it.isWhitespace() }) return CuratedEntryProblem.Reason.NotOneWord - - CuratedFieldType.Url -> - if (!isSafeUrl(trimmed, httpsOnly = config.https == true)) { - return if (config.https == true) { - CuratedEntryProblem.Reason.NotHttps - } else { - CuratedEntryProblem.Reason.NotAUrl - } - } - - CuratedFieldType.Image -> - if (!isSafeUrl(trimmed, httpsOnly = true)) return CuratedEntryProblem.Reason.NotHttps - - CuratedFieldType.Enum -> - if (config.options?.contains(trimmed) != true) return CuratedEntryProblem.Reason.NotAnOption - - CuratedFieldType.Year, CuratedFieldType.Duration, CuratedFieldType.Number -> { - val number = trimmed.toWholeNumberOrNull() ?: return CuratedEntryProblem.Reason.NotAWholeNumber - if (field.type == CuratedFieldType.Duration && number <= 0) return CuratedEntryProblem.Reason.NotPositive - config.min?.let { if (number < it) return CuratedEntryProblem.Reason.BelowMinimum } - config.max?.let { if (number > it) return CuratedEntryProblem.Reason.AboveMaximum } - // A numeric `max` is a bound, not a length cap. - return null - } - - CuratedFieldType.Date -> { - val date = CuratedDate.parse(trimmed) ?: return CuratedEntryProblem.Reason.NotADate - config.min?.let { if (date.year < it) return CuratedEntryProblem.Reason.BelowMinimum } - config.max?.let { if (date.year > it) return CuratedEntryProblem.Reason.AboveMaximum } - // A date's `max` bounds the year, not the length. - return null - } - } - - config.max?.let { if (trimmed.length > it) return CuratedEntryProblem.Reason.TooLong } - - config.pattern?.let { pattern -> - val whole = runCatching { Regex("^(?:$pattern)$") }.getOrNull() - if (whole == null || !whole.matches(trimmed)) return CuratedEntryProblem.Reason.PatternMismatch - } - - return null - } - - /** - * Every value [field] holds in an event: its tags, or the content body. - * - * A field with a marker matches only tags carrying that marker in third - * position; one without matches every tag of its name, whatever the third - * element says. Blank values are not values. - */ - fun valuesOf(field: CuratedField, tags: Array>, content: String): List { - val tag = field.tag() - if (tag == CuratedFieldConfig.CONTENT_TAG) { - return content.trim().takeIf { it.isNotEmpty() }?.let { listOf(it) } ?: emptyList() - } - - val marker = field.config.marker - return tags - .filter { it.size > 1 && it[0] == tag && it[1].isNotBlank() } - .filter { marker == null || it.getOrNull(2) == marker } - .map { it[1] } - } - - /** - * Where a canonical entry says it came from, or null for one nobody suggested. - * - * The coordinate is the `a` tag with the suggestion kind's prefix, which is - * what tells it from the schema root; the id is the first `e` tag, pinning - * the exact version the curator reviewed, and may be absent. - */ - fun source(tags: Array>): CuratedSuggestionRef? { - val address = firstAddress(tags, SUGGESTION_PREFIX) ?: return null - val coordinate = CuratedCoordinate.parse(address) ?: return null - - return CuratedSuggestionRef( - id = first(tags, TAG_EVENT)?.trim()?.ifEmpty { null }, - coordinate = address, - pubKey = coordinate.pubKey, - ) - } - - /** An http or https URL with a host, or with [httpsOnly] an https one. Nothing else reaches a link. */ - fun isSafeUrl(value: String, httpsOnly: Boolean = false): Boolean = - if (httpsOnly) CuratedSchemaEvent.isHttpsUrl(value) else HTTP_URL.matches(value.trim()) - - private val HTTP_URL = Regex("^https?://[^\\s/?#]+[^\\s]*$", RegexOption.IGNORE_CASE) - - /** The problems a suggestion and a canonical entry share. */ - private fun verifyEntry( - event: Event, - schema: CuratedSchema, - coordinate: String, - expectedKind: Kind, - ): List = buildList { - if (event.kind != expectedKind) { - add(CuratedEntryProblem(FIELD_KIND, CuratedEntryProblem.Reason.WrongKind)) - } - - // The root is required whenever the schema has a coordinate to reply to, - // which here is always: a group's schema is signed before anything can - // reply to it. Only schema coordinates count; an entry carries `a` tags - // for other reasons too, the source pointer among them. - val roots = event.tags - .filter { it.size > 1 && it[0] == TAG_ADDRESS && it[1].startsWith(SCHEMA_PREFIX) } - .map { it[1] } - if (roots.isEmpty()) { - add(CuratedEntryProblem(FIELD_SCHEMA, CuratedEntryProblem.Reason.NotAReply)) - } else if (coordinate !in roots) { - add(CuratedEntryProblem(FIELD_SCHEMA, CuratedEntryProblem.Reason.RepliesElsewhere)) - } - - for (field in schema.fields) { - val values = valuesOf(field, event.tags, event.content) - - if (values.isEmpty()) { - if (field.isRequired) add(CuratedEntryProblem(field.name, CuratedEntryProblem.Reason.Missing)) - continue - } - - if (values.size > 1 && field.config.repeat != true) { - add(CuratedEntryProblem(field.name, CuratedEntryProblem.Reason.Repeated)) - } - - // One problem per field is enough. - values.firstNotNullOfOrNull { checkValue(field, it) } - ?.let { add(CuratedEntryProblem(field.name, it)) } - } - - for (group in schema.requireAny) { - val satisfied = group.any { name -> - schema.fields.firstOrNull { it.name == name } - ?.let { valuesOf(it, event.tags, event.content).isNotEmpty() } - ?: false - } - if (!satisfied) { - add(CuratedEntryProblem(group.first(), CuratedEntryProblem.Reason.RequireAnyUnmet)) - } - } - - if (!schema.canSuggest(event.pubKey, coordinate)) { - add(CuratedEntryProblem(FIELD_VISIBILITY, CuratedEntryProblem.Reason.NotPermitted)) - } - } - - /** - * Whether [pubKey] may suggest to this list, at [coordinate]. - * - * Everyone on a public list; the curator and the `p` tags on the other two. - * The curator is read off the coordinate rather than passed, because a - * [CuratedSchema] does not know who signed it and the coordinate does. - */ - private fun CuratedSchema.canSuggest(pubKey: HexKey, coordinate: String): Boolean { - if (visibility == CuratedVisibility.Public) return true - if (CuratedCoordinate.parse(coordinate)?.pubKey == pubKey) return true - return pubKey in suggesters - } - - private fun first(tags: Array>, name: String): String? = - tags.firstOrNull { it.size > 1 && it[0] == name }?.get(1) - - private fun firstAddress(tags: Array>, prefix: String): String? = - tags.firstOrNull { it.size > 1 && it[0] == TAG_ADDRESS && it[1].startsWith(prefix) }?.get(1) - - /** An optionally signed run of digits and nothing else, as the reference reads one. */ - private fun String.toWholeNumberOrNull(): Long? = - takeIf { WHOLE_NUMBER.matches(it) }?.toLongOrNull() - - private val WHOLE_NUMBER = Regex("^-?\\d+$") - - /** The names problems are filed under when they are about the entry rather than a field. */ - const val FIELD_KIND = "kind" - const val FIELD_SCHEMA = "schema" - const val FIELD_VISIBILITY = "visibility" - const val FIELD_CURATOR = "curator" - const val FIELD_SOURCE = "source" -} - -/** - * One entry in a curated list, read off a kind 31888 or 31890 event. - * - * [values] is keyed by the schema's field names, each holding every value the - * entry carries for that field in tag order -- more than one only for a field - * the schema lets repeat. A field the entry has nothing for is absent rather - * than empty. [identifier] and [title] are also in there under whatever the - * schema calls those fields; they are lifted out because every list has them - * and every screen wants them. - */ -data class CuratedEntry( - val kind: Kind, - val id: HexKey, - val pubKey: HexKey, - /** Unix seconds, as the event carries it. */ - val createdAt: Long, - /** The `d` tag, which with [kind] and [pubKey] is the entry's coordinate. */ - val identifier: String, - val title: String, - val values: Map>, - /** For a canonical entry, the suggestion it came from, or null when nobody suggested it. */ - val source: CuratedSuggestionRef? = null, -) { - val isCanonical: Boolean get() = kind == CuratedEntryEvent.CANONICAL_KIND - - /** `kind:pubkey:d`. Two events sharing one are versions of one entry. */ - fun coordinate(): String = CuratedCoordinate(kind, pubKey, identifier).toValue() - - /** The first value of [fieldName], or null when the entry has none. */ - fun value(fieldName: String): String? = values[fieldName]?.firstOrNull() -} - -/** Where a canonical entry came from: the suggestion the curator accepted. */ -data class CuratedSuggestionRef( - /** The exact version curated, or null when the curator did not pin one. */ - val id: HexKey?, - /** `31888::`, which follows the suggester's later edits. */ - val coordinate: String, - /** The suggester, credited. */ - val pubKey: HexKey, -) { - companion object { - /** - * The pointer a canonical entry made from [entry] carries: its id, its - * coordinate and its author. Only a suggestion can be pointed at -- a - * canonical entry is the list's own word, and the list did not suggest - * anything to itself. - */ - fun of(entry: CuratedEntry): CuratedSuggestionRef { - require(!entry.isCanonical) { "A canonical entry is not the source of another" } - - return CuratedSuggestionRef( - id = entry.id, - coordinate = entry.coordinate(), - pubKey = entry.pubKey, - ) - } - } -} - -/** - * One reason an entry does not satisfy its schema: which field, and what about - * it. [field] is the field's name, or one of the [CuratedEntryEvent] `FIELD_` - * names for a rule about the entry as a whole; a `require-any` group is filed - * under its first field, so a form can show it inline. - */ -data class CuratedEntryProblem(val field: String, val reason: Reason) { - enum class Reason { - /** Not the kind the schema said suggestions come as, or not the canonical kind. */ - WrongKind, - - /** No `a` root naming any schema. */ - NotAReply, - - /** An `a` root naming some other schema. */ - RepliesElsewhere, - - /** A required field with no value. */ - Missing, - - /** A field without `repeat` with more than one. */ - Repeated, - - Empty, - NotOneWord, - NotAUrl, - NotHttps, - NotAnOption, - NotAWholeNumber, - NotPositive, - - /** Not `YYYY`, `YYYY-MM` or `YYYY-MM-DD`, or a day the calendar does not have. */ - NotADate, - - /** Under `min`: a number, or the year of a date. */ - BelowMinimum, - - /** Over `max`: a number, or the year of a date. */ - AboveMaximum, - TooLong, - PatternMismatch, - - /** A required field of a type this app cannot write. See [CuratedEntryEvent.verifyWritable]. */ - UnsupportedType, - - /** None of a `require-any` group's fields is present. */ - RequireAnyUnmet, - - /** The author may not suggest to a closed or private list. */ - NotPermitted, - - /** A canonical entry signed by somebody other than the schema's author. */ - NotTheCurator, - - /** A source pointer that is not a suggestion coordinate. */ - SourceMalformed, - } -} - -/** - * A `date` value: a calendar date at whatever precision the record allows. - * - * `YYYY`, `YYYY-MM` or `YYYY-MM-DD`, and the precision is whatever was - * written -- [month] and [day] are null when the value stops short of them, - * and nothing here turns a `2010-07` into the first of the month. The month - * has to be one and the day has to be on the calendar for that month and year, - * leap days included, so `2014-02-30` is not a date and `2016-02-29` is. The - * calendar is the proleptic Gregorian one, which is what ISO 8601 means. - * - * What a reader keeps is the string as written; this is the check on it, and - * [year] is what the schema's `min` and `max` bound. - */ -data class CuratedDate(val year: Int, val month: Int? = null, val day: Int? = null) { - companion object { - private val SHAPE = Regex("^(\\d{4})(?:-(\\d{2})(?:-(\\d{2}))?)?$") - - /** The three parts, or null for anything that is not a date at one of the three precisions. */ - fun parse(value: String): CuratedDate? { - val match = SHAPE.matchEntire(value.trim()) ?: return null - - val year = match.groupValues[1].toInt() - val month = match.groupValues[2].ifEmpty { null }?.toInt() - val day = match.groupValues[3].ifEmpty { null }?.toInt() - - if (month != null && month !in 1..12) return null - if (day != null && day !in 1..daysIn(year, month!!)) return null - - return CuratedDate(year, month, day) - } - - private fun daysIn(year: Int, month: Int): Int = when (month) { - 2 -> if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) 29 else 28 - 4, 6, 9, 11 -> 30 - else -> 31 - } - } -} - -/** - * An addressable coordinate, `::`, split the one way the NIP - * allows: on the first two colons only. A `d` may itself contain colons -- - * `imdb:tt2821314` does -- so splitting on every one mangles the identifier and - * miscounts the parts. - */ -data class CuratedCoordinate(val kind: Kind, val pubKey: HexKey, val identifier: String) { - fun toValue(): String = "$kind:$pubKey:$identifier" - - companion object { - private val SHAPE = Regex("^(\\d{1,5}):([0-9a-fA-F]{64}):(.+)$") - - /** The three parts, or null for anything that is not a coordinate with a non-empty `d`. */ - fun parse(value: String): CuratedCoordinate? { - val match = SHAPE.matchEntire(value.trim()) ?: return null - val (kind, pubKey, identifier) = match.destructured - - return CuratedCoordinate( - kind = kind.toInt(), - pubKey = pubKey.lowercase(), - identifier = identifier, - ) - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/curated/CuratedSchema.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/curated/CuratedSchema.kt deleted file mode 100644 index 63ea271b..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/curated/CuratedSchema.kt +++ /dev/null @@ -1,545 +0,0 @@ -package com.machankura.bennu.compose.nostr.curated - -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.Kind -import kotlinx.serialization.json.JsonArray -import kotlinx.serialization.json.JsonElement -import kotlinx.serialization.json.JsonObject -import kotlinx.serialization.json.JsonPrimitive -import kotlinx.serialization.json.booleanOrNull -import kotlinx.serialization.json.buildJsonObject -import kotlinx.serialization.json.contentOrNull -import kotlinx.serialization.json.jsonPrimitive -import kotlinx.serialization.json.longOrNull -import kotlinx.serialization.json.put -import com.machankura.bennu.compose.network.serialization.CommonJson - -/** - * The definition of a curated list: what an entry may contain, who may suggest - * one, and whose list it is. - * - * This is the document the other two curated kinds are checked against. A - * suggestion (kind 31888) is a reply to it that has to satisfy its fields; a - * canonical entry (kind 31890) is a suggestion its curator republished under - * their own key. The list is the set of canonical entries and the suggestions - * are its queue -- and this is the form both are filled in against, published - * so that another client can render the same form without shipping this code. - * - * The curator's pubkey is the namespace. `31889::` names - * one schema and no other, so nothing global is claimed and nothing can be - * squatted. Here the curator is a group: the schema is signed by the room's own - * key, like its profile and its posts, and it is the group -- by quorum -- that - * accepts a suggestion into the list. - * - * The protocol is written up in `bitcoin.mov/docs/NIP.md`, and the shape here - * follows its reference module tag for tag so that a schema this app signs is - * one that site's form can be driven by, and one it publishes reads here. - * - * ### What is checked, and where - * - * [problems] is the list of reasons a schema is unusable, and it is the same - * list whether the schema was typed into the editor or read off a relay: the - * NIP's rejection rules, no more. A reader rejects rather than repairs -- - * relays carry malformed and hostile events, and a half-parsed form is worse - * than a missing one -- and the editor refuses to propose what a reader would - * refuse to show. - * - * [normalized] is the one repair the NIP requires. Every list has a field - * writing to `d` and one writing to `title`, both required, and a schema that - * omits or relaxes either gets them put back -- so no schema, wherever it came - * from, can talk a client into accepting untitled or unaddressable entries. - */ -data class CuratedSchema( - /** The `d` tag: the schema's identifier, and the last part of its coordinate. */ - val identifier: String, - /** Labels the event -- "bitcoin.mov suggestion". */ - val title: String, - /** The list's identity, what people call it -- "bitcoin.mov". */ - val name: String, - /** What the list is for. Mirrored into the event's content for generic clients. */ - val description: String, - /** - * Who may suggest, or null when the schema does not say. - * - * Null is never defaulted away: a list that does not say who may suggest to - * it is not one a client should act on, so an absent or unrecognised - * visibility is a [CuratedSchemaProblem.VisibilityMissing] rather than a - * public list by accident. The editor always has one; only a schema read off - * a relay can be missing it. - */ - val visibility: CuratedVisibility?, - /** An https image for the list, or null. */ - val picture: String? = null, - /** - * A hostname the list publishes under, or null. Shown in place of [name] - * wherever the list is named, which is why it is a claim worth being careful - * with: anyone can put any domain in a tag. See [displayName]. - */ - val domain: String? = null, - /** The kind suggestions are published under. There is only one. */ - val suggestionKind: Kind = CuratedSchemaEvent.SUGGESTION_KIND, - val fields: List = emptyList(), - /** - * Fields of a type this app does not know, kept aside from [fields] so that - * a reader ignores them and a writer cannot. See [CuratedUnsupportedField]. - */ - val unsupportedFields: List = emptyList(), - /** - * Groups of field names of which at least one must be present on an entry. - * - * How a list says "a watch link or an IMDb link" without making either one - * required. A group of fewer than two names says nothing and is dropped. - */ - val requireAny: List> = emptyList(), - /** - * Pubkeys allowed to suggest on a closed or private list, besides the - * curator. The `p` tags. Meaningless on a public list, where anyone may. - */ - val suggesters: List = emptyList(), - /** - * Where the list lives: the relays suggestions and canonical entries are - * published to and read from. Signed into the event so a client that finds - * the schema anywhere knows where a reply belongs and cannot be sent - * elsewhere by an unsigned config file. - */ - val relays: List = emptyList(), -) { - /** - * What to call the list on screen: the domain when it has one, else the - * name. The domain is the stronger identity because it is the one part of - * this that can be checked against the outside world, NIP-05 style -- and - * nothing here does check it, so it is a label rather than a badge. - */ - fun displayName(): String = domain ?: name - - /** Fields a form should prompt for. Derived ones are filled in by the client. */ - fun formFields(): List = fields.filterNot { it.config.derived == true } - - /** - * The same schema with the two mandatory fields forced into place. - * - * A field writing to `d` and one writing to `title`, both required, in that - * order at the front when they were missing. A schema that already has them - * is unchanged apart from the requirement, so running this twice is running - * it once. - */ - fun normalized(): CuratedSchema { - val fields = fields.toMutableList() - - for ((tag, fallback) in CuratedField.MANDATORY) { - val index = fields.indexOfFirst { it.tag() == tag } - if (index == -1) { - fields.add(0, fallback) - } else if (!fields[index].isRequired) { - fields[index] = fields[index].copy(isRequired = true) - } - } - - return copy(fields = fields) - } - - /** - * Every reason this is not a usable schema, or nothing. - * - * The NIP's rejection rules and only those: a client MUST refuse a schema - * missing its identifier, title, name, description or visibility, one whose - * visibility is not one of the three words, one with no fields, and one - * whose picture is not https, whose domain is not a hostname, or whose relay - * is not a relay. The length caps are the reference module's, so a schema - * this app signs is one that site accepts. - * - * Checked on the schema as written, before [normalized] -- "no fields" is - * about what the publisher said, not about what a reader would put back. - */ - fun problems(): List = buildList { - fun text(value: String, cap: Int, missing: CuratedSchemaProblem, tooLong: CuratedSchemaProblem) { - if (value.isBlank()) add(missing) else if (value.length > cap) add(tooLong) - } - - text(identifier, CuratedSchemaEvent.MAX_IDENTIFIER, CuratedSchemaProblem.IdentifierMissing, CuratedSchemaProblem.IdentifierTooLong) - text(title, CuratedSchemaEvent.MAX_TITLE, CuratedSchemaProblem.TitleMissing, CuratedSchemaProblem.TitleTooLong) - text(name, CuratedSchemaEvent.MAX_NAME, CuratedSchemaProblem.NameMissing, CuratedSchemaProblem.NameTooLong) - text(description, CuratedSchemaEvent.MAX_DESCRIPTION, CuratedSchemaProblem.DescriptionMissing, CuratedSchemaProblem.DescriptionTooLong) - - if (visibility == null) add(CuratedSchemaProblem.VisibilityMissing) - - picture?.let { - if (!CuratedSchemaEvent.isHttpsUrl(it) || it.length > CuratedSchemaEvent.MAX_URL) { - add(CuratedSchemaProblem.PictureNotHttps) - } - } - - domain?.let { - if (!CuratedSchemaEvent.isDomain(it)) add(CuratedSchemaProblem.DomainInvalid) - } - - if (fields.isEmpty()) add(CuratedSchemaProblem.NoFields) - - if (relays.any { !CuratedSchemaEvent.isRelayUrl(it) }) add(CuratedSchemaProblem.RelayInvalid) - } - - fun isUsable(): Boolean = problems().isEmpty() -} - -/** A reason a [CuratedSchema] cannot be published or believed. See [CuratedSchema.problems]. */ -enum class CuratedSchemaProblem { - IdentifierMissing, - IdentifierTooLong, - TitleMissing, - TitleTooLong, - NameMissing, - NameTooLong, - DescriptionMissing, - DescriptionTooLong, - VisibilityMissing, - PictureNotHttps, - DomainInvalid, - NoFields, - RelayInvalid, -} - -/** - * Who may suggest to a list, and who it is meant for. - * - * Suggesting only. Curation is never delegated: a public list still has exactly - * one curator, and the `p` tags on a closed list name extra *suggesters*. - * - * Relays are open, so [Private] is a convention clients follow rather than an - * encryption anybody enforces. Nothing secret belongs in a private list. - */ -enum class CuratedVisibility(val value: String) { - /** Anyone may suggest; anyone may read. */ - Public("public"), - - /** The curator and the `p` tags may suggest; anyone may read. */ - Closed("closed"), - - /** The curator and the `p` tags may suggest; clients should show it only to them. */ - Private("private"), - ; - - companion object { - /** Case-insensitive, trimmed, and null for anything but the three words. */ - fun parse(value: String): CuratedVisibility? = - value.trim().lowercase().let { word -> entries.firstOrNull { it.value == word } } - } -} - -/** - * What kind of value a field takes. One validation rule each, in the NIP's - * table; a form picks its input from this. - * - * [isNumeric] says the value is a whole number. [isBounded] says what `max` - * means: a bound on the value -- the number itself, or the year of a date -- - * for these, and a maximum *length* for everything else. The double duty is - * safe because a field is one or the other, never both. - */ -enum class CuratedFieldType(val value: String, val isNumeric: Boolean = false) { - /** Single-line string, length-capped. */ - Text("text"), - - /** Multi-line string. */ - LongText("longtext"), - - /** One word, no whitespace -- `imdb:tt2821314`. */ - Token("token"), - - /** An http(s) URL; `https` in the config narrows it. */ - Url("url"), - - /** A URL that must be https, since browsers block insecure images. */ - Image("image"), - - /** One of the config's `options`. */ - Enum("enum"), - - /** An integer year, bounded by `min` and `max`. */ - Year("year", isNumeric = true), - - /** A positive integer number of seconds, bounded by `min` and `max`. */ - Duration("duration", isNumeric = true), - - /** An integer, bounded by `min` and `max`. */ - Number("number", isNumeric = true), - - /** - * An ISO 8601 calendar date at whatever precision the record allows -- - * `YYYY`, `YYYY-MM` or `YYYY-MM-DD` -- with `min` and `max` bounding the - * year. Not numeric: the value is kept as written, since `2010-07` is a - * month and not a day somebody left off. - */ - Date("date"), - ; - - /** - * Whether `min` and `max` bound the value rather than cap its length: the - * numeric types, and a date, whose bounds are years. What the NIP means by - * a date counting as numeric for `max`'s double duty. - */ - val isBounded: Boolean get() = isNumeric || this == Date - - companion object { - fun parse(value: String): CuratedFieldType? = entries.firstOrNull { it.value == value } - } -} - -/** - * Everything about a field beyond its name, type, optionality, placeholder and - * label -- the JSON object in the seventh position of a `field` tag. - * - * Null throughout means "not said", and a key that is not said is not written, - * so a config with nothing in it is `{}`. [others] carries keys this app does - * not know, so editing a field another client wrote does not silently strip - * what that client meant by it. - */ -data class CuratedFieldConfig( - /** The tag the field writes to. Defaults to the field's name; [CONTENT_TAG] means the body. */ - val tag: String? = null, - /** A marker written as the tag's third element -- `["r", url, "watch"]`. */ - val marker: String? = null, - /** Maximum characters for text-ish types, maximum value for numeric ones. */ - val max: Long? = null, - /** Minimum value. Numeric types only. */ - val min: Long? = null, - /** The allowed values of an enum. */ - val options: List? = null, - /** Require https on a url. */ - val https: Boolean? = null, - /** The tag may appear more than once. */ - val repeat: Boolean? = null, - /** A regular expression the trimmed value must match end to end. */ - val pattern: String? = null, - /** The client fills the value in and must not prompt for it. */ - val derived: Boolean? = null, - /** Helper text under the input. */ - val hint: String? = null, - /** Keys this app does not know, kept as they came. */ - val others: Map = emptyMap(), -) { - /** The blob as it goes into the tag. Known keys first, in the NIP's order, then [others]. */ - fun toJson(): String = buildJsonObject { - tag?.let { put(KEY_TAG, it) } - marker?.let { put(KEY_MARKER, it) } - max?.let { put(KEY_MAX, it) } - min?.let { put(KEY_MIN, it) } - options?.let { put(KEY_OPTIONS, JsonArray(it.map(::JsonPrimitive))) } - https?.let { put(KEY_HTTPS, it) } - repeat?.let { put(KEY_REPEAT, it) } - pattern?.let { put(KEY_PATTERN, it) } - derived?.let { put(KEY_DERIVED, it) } - hint?.let { put(KEY_HINT, it) } - others.forEach { (key, value) -> put(key, value) } - }.toString() - - companion object { - /** The `tag` value meaning the event's content rather than a tag. */ - const val CONTENT_TAG = "content" - - private const val KEY_TAG = "tag" - private const val KEY_MARKER = "marker" - private const val KEY_MAX = "max" - private const val KEY_MIN = "min" - private const val KEY_OPTIONS = "options" - private const val KEY_HTTPS = "https" - private const val KEY_REPEAT = "repeat" - private const val KEY_PATTERN = "pattern" - private const val KEY_DERIVED = "derived" - private const val KEY_HINT = "hint" - - private val KNOWN_KEYS = setOf( - KEY_TAG, KEY_MARKER, KEY_MAX, KEY_MIN, KEY_OPTIONS, - KEY_HTTPS, KEY_REPEAT, KEY_PATTERN, KEY_DERIVED, KEY_HINT, - ) - - /** - * The blob read back, leniently. - * - * A malformed blob costs the field its constraints and not its life: the - * NIP says a bad config must not invalidate the field, so anything that - * is not a JSON object reads as no config at all, and a known key of the - * wrong type is dropped rather than kept as something it is not. - */ - fun fromJson(json: String?): CuratedFieldConfig { - if (json.isNullOrBlank()) return CuratedFieldConfig() - - val obj = runCatching { CommonJson.parseToJsonElement(json) }.getOrNull() as? JsonObject - ?: return CuratedFieldConfig() - - fun string(key: String): String? = - (obj[key] as? JsonPrimitive)?.takeIf { it.isString }?.contentOrNull - - fun long(key: String): Long? = - (obj[key] as? JsonPrimitive)?.takeUnless { it.isString }?.longOrNull - - fun boolean(key: String): Boolean? = - (obj[key] as? JsonPrimitive)?.takeUnless { it.isString }?.booleanOrNull - - return CuratedFieldConfig( - tag = string(KEY_TAG), - marker = string(KEY_MARKER), - max = long(KEY_MAX), - min = long(KEY_MIN), - options = (obj[KEY_OPTIONS] as? JsonArray) - ?.mapNotNull { (it as? JsonPrimitive)?.takeIf { p -> p.isString }?.contentOrNull }, - https = boolean(KEY_HTTPS), - repeat = boolean(KEY_REPEAT), - pattern = string(KEY_PATTERN), - derived = boolean(KEY_DERIVED), - hint = string(KEY_HINT), - others = obj.filterKeys { it !in KNOWN_KEYS }, - ) - } - } -} - -/** - * One field an entry may -- or must -- carry. - * - * ``` - * ["field", name, type, "required" | "optional", placeholder, label, config] - * ``` - * - * The four things a form needs are positional and everything else is the JSON - * blob in the last position, which is [CuratedFieldConfig]. - */ -data class CuratedField( - /** Stable name; the key a form collects the value under. */ - val name: String, - val type: CuratedFieldType, - val isRequired: Boolean, - /** An example value shown in an empty input. May be empty. */ - val placeholder: String = "", - /** The human label for the input. Empty means [name]. */ - val label: String = "", - val config: CuratedFieldConfig = CuratedFieldConfig(), -) { - /** The tag this field writes to; [CuratedFieldConfig.CONTENT_TAG] means the body. */ - fun tag(): String = config.tag ?: name - - fun labelOrName(): String = label.ifBlank { name } - - fun toTagArray(): Array = arrayOf( - TAG_NAME, - name, - type.value, - if (isRequired) REQUIRED else OPTIONAL, - placeholder, - label, - config.toJson(), - ) - - companion object { - const val TAG_NAME = "field" - - private const val REQUIRED = "required" - private const val OPTIONAL = "optional" - - /** - * The tag read back, or null for one that is not a field. - * - * Null for a blank name or an unknown type, which are the two things a - * form cannot do anything with -- though the second is not forgotten: - * [parseUnsupported] reads the same tag as the field this app cannot - * use. Everything after them is optional: a missing placeholder is - * empty, a missing label falls back to the name, and a missing or - * malformed config is no config -- see [CuratedFieldConfig.fromJson]. - */ - fun parse(tag: Array): CuratedField? { - if (tag.size < 3 || tag[0] != TAG_NAME) return null - - val name = tag[1].trim() - if (name.isEmpty()) return null - - val type = CuratedFieldType.parse(tag[2]) ?: return null - - return CuratedField( - name = name, - type = type, - isRequired = tag.getOrNull(3) == REQUIRED, - placeholder = tag.getOrNull(4) ?: "", - label = tag.getOrNull(5) ?: "", - config = CuratedFieldConfig.fromJson(tag.getOrNull(6)), - ) - } - - /** - * The tag read back as a field this app cannot use, or null for - * anything else: the exact complement of [parse] over named fields, so - * that between the two every named `field` tag lands somewhere. - */ - fun parseUnsupported(tag: Array): CuratedUnsupportedField? { - if (tag.size < 3 || tag[0] != TAG_NAME) return null - - val name = tag[1].trim() - if (name.isEmpty()) return null - - if (CuratedFieldType.parse(tag[2]) != null) return null - - return CuratedUnsupportedField( - name = name, - type = tag[2].trim(), - isRequired = tag.getOrNull(3) == REQUIRED, - label = tag.getOrNull(5) ?: "", - tag = tag.toList(), - ) - } - - /** The `title` field a schema gets when it left its own out. */ - val TITLE = CuratedField( - name = "title", - type = CuratedFieldType.Text, - isRequired = true, - label = "Title", - config = CuratedFieldConfig(max = 200), - ) - - /** - * The `d` field a schema gets when it left its own out. Derived, so a - * form never asks for it: the client works an identifier out of the - * entry itself. - */ - val IDENTIFIER = CuratedField( - name = "identifier", - type = CuratedFieldType.Token, - isRequired = true, - label = "Identifier", - config = CuratedFieldConfig(tag = "d", max = 80, derived = true), - ) - - /** - * The two fields every list has, keyed by the tag each writes to and in - * the order [CuratedSchema.normalized] puts them back -- title first, so - * that `d` ends up in front of it. - */ - val MANDATORY: List> = listOf( - "title" to TITLE, - "d" to IDENTIFIER, - ) - } -} - -/** - * A `field` tag whose type this app does not know, kept rather than dropped. - * - * The NIP's tolerance for a field that will not parse is a reader's: an entry - * is checked against the fields a reader understands, and one it does not is - * left out of the reading. A writer cannot be so easy. An entry published - * without a field the schema requires is refused by every client that does - * know the type -- fourteen went out that way from a build that could not see - * a `date` -- and a schema re-signed without one has quietly changed the - * list's rules. So the tag is kept whole: [CuratedEntryEvent.verifyWritable] - * refuses to compose under a required one, naming [type], and - * [CuratedSchemaEvent.template] writes [tag] back as it came, the way - * [CuratedFieldConfig.others] keeps the config keys it does not know. - */ -data class CuratedUnsupportedField( - val name: String, - /** The type word as the tag has it: what a newer client would know it by. */ - val type: String, - val isRequired: Boolean, - val label: String = "", - /** The whole tag, for writing back unchanged. */ - val tag: List, -) { - fun labelOrName(): String = label.ifBlank { name } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/curated/CuratedSchemaEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/curated/CuratedSchemaEvent.kt deleted file mode 100644 index c9dca2a0..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/curated/CuratedSchemaEvent.kt +++ /dev/null @@ -1,213 +0,0 @@ -package com.machankura.bennu.compose.nostr.curated - -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.Kind -import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate -import kotlin.time.Clock - -/** - * Kind 31889: a curated schema event, and the two kinds it governs. - * - * ``` - * 31889 curated schema the definition of a list, by its curator - * 31888 curated suggestion an entry anyone proposes, in reply to the schema - * 31890 curated canonical a suggestion the curator republished as the list's own - * ``` - * - * All three are addressable, so `kind:pubkey:d` names one entry and republishing - * with the same `d` replaces it. That is what makes a schema revisable: editing - * one signs a new event under the same coordinate, and every suggestion that - * replied to the coordinate -- rather than to an event id -- stays attached. - * - * This object is the wire shape: tags in, tags out. [CuratedSchema] is what the - * tags mean, and `GroupCuratedSchema` is a group's own signed one. - */ -object CuratedSchemaEvent { - const val KIND: Kind = 31889 - - /** The kind a schema's suggestions are published under -- its `k` tag. */ - const val SUGGESTION_KIND: Kind = 31888 - - /** The kind the curator republishes an accepted suggestion as. */ - const val CANONICAL_KIND: Kind = 31890 - - /** Length caps on the identity tags, the reference module's. */ - const val MAX_IDENTIFIER = 100 - const val MAX_TITLE = 200 - const val MAX_NAME = 100 - const val MAX_DESCRIPTION = 500 - const val MAX_URL = 500 - const val MAX_DOMAIN = 253 - - private const val TAG_IDENTIFIER = "d" - private const val TAG_TITLE = "title" - private const val TAG_NAME = "name" - private const val TAG_DESCRIPTION = "description" - private const val TAG_KIND = "k" - private const val TAG_VISIBILITY = "visibility" - private const val TAG_PICTURE = "picture" - private const val TAG_DOMAIN = "domain" - private const val TAG_REQUIRE_ANY = "require-any" - private const val TAG_SUGGESTER = "p" - private const val TAG_RELAY = "relay" - - /** The addressable coordinate: what a suggestion's `a` root names. */ - fun coordinate(pubkey: HexKey, identifier: String): String = "$KIND:$pubkey:$identifier" - - /** - * The schema an event declares, or null when the event is not a usable one. - * - * Defensive in the way a relay demands. The wrong kind is null. Any of - * [CuratedSchema.problems] is null -- a schema that would be rejected on - * publish is rejected on read, and for the same reasons. A `field` tag that - * will not parse is dropped and the rest are kept, which is the one place - * the NIP asks for tolerance -- except that one of a type this app does not - * know is kept aside rather than lost, see [CuratedUnsupportedField]; a - * `require-any` naming fewer than two fields says nothing and is dropped. - * - * What comes back is [CuratedSchema.normalized]: the two mandatory fields - * forced in, whatever the event said. - */ - fun parse(event: Event): CuratedSchema? { - if (event.kind != KIND) return null - - return read(event.tags, event.content).takeIf { it.isUsable() }?.normalized() - } - - /** - * The tags as a schema, whether or not they make a usable one. - * - * Split from [parse] so that a reader wanting the reasons -- the editor, - * a test -- can ask [CuratedSchema.problems] of the result. The identity - * values are trimmed, and the description falls back to the content the way - * generic clients read it: the tag is authoritative and the content is the - * mirror. - */ - fun read(tags: Array>, content: String): CuratedSchema { - fun first(name: String): String? = - tags.firstOrNull { it.size > 1 && it[0] == name }?.get(1) - - fun all(name: String): List = - tags.filter { it.size > 1 && it[0] == name }.map { it[1] } - - return CuratedSchema( - identifier = first(TAG_IDENTIFIER)?.trim() ?: "", - title = first(TAG_TITLE)?.trim() ?: "", - name = first(TAG_NAME)?.trim() ?: "", - description = (first(TAG_DESCRIPTION)?.trim()?.ifEmpty { null } ?: content).trim(), - // Null for an absent or unrecognised word, and null stays null: see - // the field's own note on why it is never defaulted. - visibility = first(TAG_VISIBILITY)?.let(CuratedVisibility::parse), - picture = first(TAG_PICTURE)?.trim()?.ifEmpty { null }, - domain = first(TAG_DOMAIN)?.trim()?.ifEmpty { null }?.let(::normalizeDomain), - suggestionKind = first(TAG_KIND)?.trim()?.toIntOrNull() ?: SUGGESTION_KIND, - fields = tags.mapNotNull(CuratedField::parse), - unsupportedFields = tags.mapNotNull(CuratedField::parseUnsupported), - requireAny = tags - .filter { it.isNotEmpty() && it[0] == TAG_REQUIRE_ANY } - .map { group -> group.drop(1).map { it.trim() }.filter { it.isNotEmpty() } } - .filter { it.size > 1 }, - // Only what is a pubkey. A `p` tag holding anything else names nobody, - // and keeping it would have the editor render it as an npub it is not. - suggesters = all(TAG_SUGGESTER).map { it.trim().lowercase() }.filter(::isPubkey).distinct(), - relays = all(TAG_RELAY).map { it.trim() }.distinct(), - ) - } - - /** - * The unsigned event that publishes [schema], for the group to sign. - * - * Built from the schema alone rather than from the group's last event, the - * way a relay list is and for the same reason: a schema is one document - * whose whole point in being re-signed is to replace the last one, and - * carrying an old tag forward would make removing a field impossible. - * - * The content mirrors the description so that a client reading content - * rather than tags still shows something; the tag is the authoritative one. - * - * A field of a type this app does not know goes out as it came in, after - * the fields it does: the editor cannot show it, and a schema re-signed - * without it would have changed the list's rules behind the member's back. - */ - fun template( - schema: CuratedSchema, - createdAt: Long = Clock.System.now().epochSeconds, - ): EventTemplate { - val normalized = schema.normalized() - - val tags = buildList { - add(arrayOf(TAG_IDENTIFIER, normalized.identifier)) - add(arrayOf(TAG_TITLE, normalized.title)) - add(arrayOf(TAG_NAME, normalized.name)) - add(arrayOf(TAG_DESCRIPTION, normalized.description)) - add(arrayOf(TAG_KIND, normalized.suggestionKind.toString())) - // Absent rather than invented when the schema has none. Every reader, - // this one included, then refuses the event -- which is the right - // outcome for a schema that does not say who may suggest to it, and - // one the editor never produces. - normalized.visibility?.let { add(arrayOf(TAG_VISIBILITY, it.value)) } - - normalized.picture?.let { add(arrayOf(TAG_PICTURE, it)) } - normalized.domain?.let { add(arrayOf(TAG_DOMAIN, normalizeDomain(it))) } - - normalized.fields.forEach { add(it.toTagArray()) } - normalized.unsupportedFields.forEach { add(it.tag.toTypedArray()) } - normalized.requireAny.forEach { group -> add(arrayOf(TAG_REQUIRE_ANY, *group.toTypedArray())) } - normalized.suggesters.forEach { add(arrayOf(TAG_SUGGESTER, it)) } - normalized.relays.forEach { add(arrayOf(TAG_RELAY, it)) } - } - - return EventTemplate( - createdAt = createdAt, - kind = KIND, - tags = tags.toTypedArray(), - content = normalized.description, - ) - } - - /** - * A hostname and nothing else: at least two labels, each of letters, digits - * and inner hyphens, no scheme, port or path, 253 characters at most. What - * [normalizeDomain] leaves of a pasted URL is checked against this, so - * `https://Bitcoin.MOV/` is accepted and stored as `bitcoin.mov`. - */ - private val DOMAIN = Regex( - "^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$" - ) - - /** Trim the things people paste around a bare hostname. */ - fun normalizeDomain(value: String): String = value - .trim() - .lowercase() - .replace(Regex("^[a-z][a-z0-9+.-]*://"), "") - .removePrefix("@") - .replace(Regex("/.*$"), "") - .replace(Regex(":\\d+$"), "") - .removeSuffix(".") - - /** 64 lowercase hex characters: an x-only pubkey as nostr writes one. */ - fun isPubkey(value: String): Boolean = - value.length == 64 && value.all { it in '0'..'9' || it in 'a'..'f' } - - fun isDomain(value: String): Boolean = - normalizeDomain(value).let { it.length <= MAX_DOMAIN && DOMAIN.matches(it) } - - /** - * An https URL with a host: the only kind of picture a schema may carry, - * because it gets rendered and browsers block the rest on a secure page. - */ - fun isHttpsUrl(value: String): Boolean = HTTPS_URL.matches(value.trim()) - - private val HTTPS_URL = Regex("^https://[^\\s/?#]+[^\\s]*$", RegexOption.IGNORE_CASE) - - /** - * A `ws://` or `wss://` URL with a host, which is what the NIP accepts in a - * `relay` tag. The editor is stricter about what it will let a group sign -- - * see `GroupRelaySet.relayUrlOrNull` -- but a schema read off a relay is held - * to the NIP's rule and not to this app's. - */ - fun isRelayUrl(value: String): Boolean = RELAY_URL.matches(value.trim()) - - private val RELAY_URL = Regex("^wss?://[^\\s/?#]+[^\\s]*$", RegexOption.IGNORE_CASE) -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/curated/CuratedSchemaTemplate.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/curated/CuratedSchemaTemplate.kt deleted file mode 100644 index 9eaf3100..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/curated/CuratedSchemaTemplate.kt +++ /dev/null @@ -1,262 +0,0 @@ -package com.machankura.bennu.compose.nostr.curated - -/** - * How a client works an entry's `d` out of the entry itself. - * - * The NIP marks the identifier field `derived` and leaves the derivation to the - * publishing client, which is fine for a site with one list and one rule -- - * bitcoin.mov's -- and useless for a list started from a template, whose - * entries will be composed by clients that have never seen its code. So - * curare.to records the rule *in the schema*: a machine-readable mark, - * `[rule:]`, at the end of a human sentence in the identifier field's - * hint. A client that knows the rule applies it and one that does not can at - * least read what it is; one that finds no mark falls back to [Title]. - * - * This app composes no entries and applies none of these. It writes the mark - * so that a list the group starts here is one that site's form can post to - * with the right identifier -- the same link one post whoever submits it, - * say -- rather than with whatever its fallback happens to be. - * - * The keys, the wording and the shape of the hint are `lib/protocol/derive.ts` - * in the curare.to repository, byte for byte, so that a template started here - * and one started there produce the same schema. - */ -enum class CuratedDeriveRule( - /** The word in the mark. */ - val key: String, - /** The rule as the hint says it, after "Derived by the client — ". */ - private val phrase: String, -) { - /** - * A post with a link is identified by the link, so the same link is one - * post whoever submits it; a text post by its title and its author. - */ - LinkOrTitle("link-or-title", "the link, else the title and author"), - - /** Two people's same-titled posts are two posts; one person's is an edit. */ - TitleAuthor("title-author", "the title and author"), - - /** - * A catalogue entry with an external id (`imdb:tt…`) is one entry however - * often it is suggested; otherwise the title and year. - */ - ExternalOrTitleYear("external-or-title-year", "the external id, else the title and year"), - - /** The same title is the same post, whoever posts it. */ - Title("title", "the title"), - ; - - /** The hint that records this rule on an identifier field. */ - fun hint(): String = "Derived by the client — $phrase. [rule:$key]" -} - -/** - * The shapes a list can start from: curare.to's templates, the ones its - * "Start a list" page offers, so that a list started in this app and one - * started on that site are the same kind of thing. - * - * Every template carries the two fields every list has -- the identifier, - * derived and with its [rule] recorded in its hint, and the title -- and - * declares no derived `t` field: the hashtag rule is bitcoin.mov's own, and a - * list is its own topic. Flair is the sub-topic. - * - * The field names, labels, placeholders and configs are signed into the - * schema and read by other clients, which is why they are plain strings here - * rather than resources: they are protocol data, not this app's copy. What - * the picker *calls* a template is UI text and lives in the catalogue. - * - * The fields are `lib/protocol/templates.ts` in the curare.to repository, - * field for field. A template added there belongs here too. - */ -enum class CuratedSchemaTemplate( - /** The stable key, the one curare.to's editor takes as `?template=`. */ - val key: String, - val rule: CuratedDeriveRule, - val fields: List, - val requireAny: List> = emptyList(), -) { - /** Reddit's default: a title with a link or some text, a picture, and a flair. */ - Links( - key = "links", - rule = CuratedDeriveRule.LinkOrTitle, - fields = listOf( - identifier(CuratedDeriveRule.LinkOrTitle), - title(placeholder = "What is it?"), - CuratedField( - name = "link", - type = CuratedFieldType.Url, - isRequired = false, - placeholder = "https://…", - label = "Link", - config = CuratedFieldConfig(tag = "r", marker = "link", max = 500), - ), - CuratedField( - name = "body", - type = CuratedFieldType.LongText, - isRequired = false, - placeholder = "Say more, or nothing.", - label = "Text", - config = CuratedFieldConfig(tag = CuratedFieldConfig.CONTENT_TAG, max = 10_000), - ), - CuratedField( - name = "image", - type = CuratedFieldType.Image, - isRequired = false, - placeholder = "https://…/picture.jpg", - label = "Picture", - config = CuratedFieldConfig(max = 500, hint = "An https link to an image."), - ), - flair("discussion", "news", "question"), - ), - requireAny = listOf(listOf("link", "body")), - ), - - /** Text posts only: a title and a body, with a flair. */ - Discussion( - key = "discussion", - rule = CuratedDeriveRule.TitleAuthor, - fields = listOf( - identifier(CuratedDeriveRule.TitleAuthor), - title(placeholder = "What do you want to talk about?"), - CuratedField( - name = "body", - type = CuratedFieldType.LongText, - isRequired = true, - label = "Text", - config = CuratedFieldConfig(tag = CuratedFieldConfig.CONTENT_TAG, max = 10_000), - ), - flair("question", "meta"), - ), - ), - - /** - * bitcoin.mov's shape, generalised: things with a year, a type, an - * external id and links, one entry per thing however often it is suggested. - */ - Catalogue( - key = "catalogue", - rule = CuratedDeriveRule.ExternalOrTitleYear, - fields = listOf( - identifier(CuratedDeriveRule.ExternalOrTitleYear), - title(placeholder = "The thing’s name"), - CuratedField( - name = "year", - type = CuratedFieldType.Year, - isRequired = false, - placeholder = "2014", - label = "Year", - config = CuratedFieldConfig(min = 1900, max = 2100), - ), - CuratedField( - name = "type", - type = CuratedFieldType.Enum, - isRequired = true, - label = "Type", - config = CuratedFieldConfig( - options = listOf("movie", "documentary", "short", "series", "book", "other"), - ), - ), - CuratedField( - name = "externalId", - type = CuratedFieldType.Token, - isRequired = false, - placeholder = "imdb:tt2821314", - label = "External id", - config = CuratedFieldConfig( - tag = "i", - max = 60, - hint = "Helps dedupe, e.g. imdb:tt2821314 or isbn:…", - ), - ), - CuratedField( - name = "watchUrl", - type = CuratedFieldType.Url, - isRequired = false, - placeholder = "https://…", - label = "Where to see it", - config = CuratedFieldConfig(tag = "r", marker = "watch", max = 500, repeat = true), - ), - CuratedField( - name = "referenceUrl", - type = CuratedFieldType.Url, - isRequired = false, - placeholder = "https://…", - label = "Reference", - config = CuratedFieldConfig(tag = "r", marker = "reference", max = 500), - ), - CuratedField( - name = "image", - type = CuratedFieldType.Image, - isRequired = false, - placeholder = "https://…/poster.jpg", - label = "Picture", - config = CuratedFieldConfig(max = 500), - ), - CuratedField( - name = "lang", - type = CuratedFieldType.Token, - isRequired = false, - placeholder = "en", - label = "Language", - config = CuratedFieldConfig(max = 60, pattern = "[A-Za-z]{2,8}([-_][A-Za-z0-9]{2,8})*"), - ), - CuratedField( - name = "description", - type = CuratedFieldType.LongText, - isRequired = false, - placeholder = "Why is it worth a look?", - label = "Description", - config = CuratedFieldConfig(tag = CuratedFieldConfig.CONTENT_TAG, max = 4000), - ), - ), - requireAny = listOf(listOf("watchUrl", "referenceUrl")), - ), - - /** Just the two fields every list has, and whatever the group adds. */ - Custom( - key = "custom", - rule = CuratedDeriveRule.Title, - fields = listOf(identifier(CuratedDeriveRule.Title), title(placeholder = "")), - ), - ; - - companion object { - /** - * The template with [key], or [Custom] for null and for a key this build - * does not know. - * - * Custom rather than the first, which is what curare.to falls back to, - * because Custom is the two fields every list has and nothing else: the - * one shape that cannot presume anything about a list it was not asked - * for. Null is what an edit carries, where the template is meaningless, - * and what a screen handed a loaded state without one gets. - */ - fun byKey(key: String?): CuratedSchemaTemplate = entries.firstOrNull { it.key == key } ?: Custom - } -} - -// The fields the templates share, as functions of the file rather than of the -// companion: an enum's entries are built before its companion is, so they -// cannot call into it. - -/** - * The identifier field every template starts with: [CuratedField.IDENTIFIER] - * with the rule recorded in its hint. - */ -private fun identifier(rule: CuratedDeriveRule): CuratedField = - CuratedField.IDENTIFIER.copy( - config = CuratedField.IDENTIFIER.config.copy(hint = rule.hint()), - ) - -/** The title field every template starts with: [CuratedField.TITLE] with an example. */ -private fun title(placeholder: String): CuratedField = - CuratedField.TITLE.copy(placeholder = placeholder) - -/** A sub-topic an entry may pick one of. */ -private fun flair(vararg options: String): CuratedField = CuratedField( - name = "flair", - type = CuratedFieldType.Enum, - isRequired = false, - label = "Flair", - config = CuratedFieldConfig(options = options.toList()), -) diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/ChatRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/ChatRepository.kt index 8df157b6..5e2d8aaa 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/ChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/ChatRepository.kt @@ -14,8 +14,6 @@ import com.machankura.bennu.compose.managers.SharedKeyDerivation import com.machankura.bennu.compose.managers.MarmotGroupCreation import com.machankura.bennu.compose.managers.SubgroupManager import com.machankura.bennu.compose.nostr.GroupNostrProfile -import com.machankura.bennu.compose.nostr.GroupCuratedEntry -import com.machankura.bennu.compose.nostr.GroupCuratedSchema import com.machankura.bennu.compose.nostr.GroupPost import com.machankura.bennu.compose.nostr.GroupRelayList import com.machankura.bennu.compose.database.model.Participant @@ -131,30 +129,6 @@ interface ChatRepository { */ suspend fun groupPosts(chatRoomId: String): List - /** - * The curated schemas this group signed -- the lists it curates -- one per - * identifier, most recently signed first. - * - * Kind 31889 is addressable, so an edit is a newer event under the same - * identifier and the newest wins per list, the way the profile does; two - * identifiers are two lists and both come back. Empty in a group that - * curates nothing, which is every group until somebody proposes one. - */ - suspend fun groupCuratedSchemas(chatRoomId: String): List - - /** - * The canonical entries this group signed -- the suggestions it accepted - * into the lists it curates -- one per coordinate, most recently signed - * first. - * - * Kind 31890 is addressable, so a re-curation is a newer event under the - * same identifier and the newest wins, the way a schema's edit does. Each - * is read against the schema it replies to, and an entry whose list this - * device holds no schema for is left out. Empty in a group that has - * accepted nothing, which is every group until a quorum signs an entry. - */ - suspend fun groupCuratedEntries(chatRoomId: String): List - /** * One event the group signed, as the group signed it, or null when this * device does not hold it or it was signed in some other room. @@ -406,14 +380,6 @@ interface ChatRepository { override suspend fun groupPosts(chatRoomId: String): List = emptyList() - override suspend fun groupCuratedSchemas( - chatRoomId: String - ): List = emptyList() - - override suspend fun groupCuratedEntries( - chatRoomId: String - ): List = emptyList() - override suspend fun groupSignedEvent( chatRoomId: String, id: HexKey diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedEvent.kt index 7cfc2773..91a2dfc5 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedEvent.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedEvent.kt @@ -3,11 +3,8 @@ package com.machankura.bennu.compose.text import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent -import com.machankura.bennu.compose.extensions.shortened import com.machankura.bennu.compose.managers.SharedKeyDerivation import com.machankura.bennu.compose.nostr.GroupRelaySet -import com.machankura.bennu.compose.nostr.curated.CuratedEntryEvent -import com.machankura.bennu.compose.nostr.curated.CuratedSchemaEvent import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent @@ -195,37 +192,6 @@ object ProposedEvent { ) } - // A list the group would curate. A member signing this is agreeing to - // take suggestions from whoever the visibility admits and to be the one - // key that accepts them, so the summary is the list's name, who may - // suggest, and how much an entry asks for -- the content is only the - // description, which the detail screen shows whole. - CuratedSchemaEvent.KIND -> Summary( - label = "Curated schema", - detail = CuratedSchemaEvent.read(event.tags, event.content).let { schema -> - listOfNotNull( - schema.displayName().ifBlank { null }, - schema.visibility?.value, - schema.fields.size.let { "$it ${if (it == 1) "field" else "fields"}" } - ).joinToString(" · ") - } - ) - - // An entry the group would take into one of its lists. A member signing - // this is agreeing that the list stands behind this title, so the - // summary is the title and who suggested it -- the credit the entry - // carries -- and not its fields, which the form showed whole before the - // proposal was made and the queue shows again once it lands. - CuratedEntryEvent.CANONICAL_KIND -> Summary( - label = "Curated entry", - detail = CuratedEntryEvent.headline(event).let { entry -> - listOfNotNull( - entry.title.ifBlank { entry.identifier }.ifBlank { null }, - entry.source?.let { "suggested by ${it.pubKey.shortened()}" } - ).joinToString(" · ").ifEmpty { "An untitled entry" } - } - ) - // The group opening a wallet. What a member is agreeing to is that the // group keeps coins here, so the summary names the network -- the one // thing that changes what the coins are worth -- and the account, and diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/AcceptCuratedSuggestionScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/AcceptCuratedSuggestionScreen.kt deleted file mode 100644 index f7d44f1c..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/AcceptCuratedSuggestionScreen.kt +++ /dev/null @@ -1,832 +0,0 @@ -package com.machankura.bennu.compose.ui.composable - -import androidx.compose.foundation.background -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.ExperimentalLayoutApi -import androidx.compose.foundation.layout.FlowRow -import androidx.compose.foundation.layout.PaddingValues -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.imePadding -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.text.KeyboardOptions -import androidx.compose.foundation.text.input.TextFieldLineLimits -import androidx.compose.foundation.text.input.TextFieldState -import androidx.compose.foundation.text.input.setTextAndPlaceCursorAtEnd -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Add -import androidx.compose.material.icons.filled.CheckCircle -import androidx.compose.material.icons.filled.Delete -import androidx.compose.material.icons.filled.Draw -import androidx.compose.material3.BottomAppBar -import androidx.compose.material3.BottomAppBarDefaults -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi -import androidx.compose.material3.FilterChip -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedTextField -import androidx.compose.material3.OutlinedTextFieldDefaults -import androidx.compose.material3.Scaffold -import androidx.compose.material3.SnackbarHost -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.text.font.FontFamily -import androidx.compose.ui.text.input.KeyboardType -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.text.style.TextOverflow -import androidx.lifecycle.viewmodel.compose.viewModel -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import bennu.composeapp.generated.resources.Res -import bennu.composeapp.generated.resources.a_date_as_yyyy_yyyy_mm_or_yyyy_mm_dd -import bennu.composeapp.generated.resources.a_whole_number -import bennu.composeapp.generated.resources.add_another -import bennu.composeapp.generated.resources.at_least_n -import bennu.composeapp.generated.resources.at_least_one_of_these_is_needed -import bennu.composeapp.generated.resources.at_most_n -import bennu.composeapp.generated.resources.at_most_n_characters -import bennu.composeapp.generated.resources.could_not_ask_the_group_to_sign_this_entry -import bennu.composeapp.generated.resources.field_and_problem -import bennu.composeapp.generated.resources.filled_in_by_the_suggester_s_app_and_kept -import bennu.composeapp.generated.resources.kept_from_the_suggestion -import bennu.composeapp.generated.resources.more_than_zero -import bennu.composeapp.generated.resources.must_match_the_pattern -import bennu.composeapp.generated.resources.n_or_earlier -import bennu.composeapp.generated.resources.n_or_later -import bennu.composeapp.generated.resources.one_word_without_spaces -import bennu.composeapp.generated.resources.only_one_value_for_this_field -import bennu.composeapp.generated.resources.pick_one_of_the_options -import bennu.composeapp.generated.resources.propose_entry -import bennu.composeapp.generated.resources.suggested_by_on -import bennu.composeapp.generated.resources.take_this_suggestion_into_the_list -import bennu.composeapp.generated.resources.that_is_not_a_web_address -import bennu.composeapp.generated.resources.that_must_be_an_https_address -import bennu.composeapp.generated.resources.the_entry_cannot_be_signed_as_it_is -import bennu.composeapp.generated.resources.the_group_already_has_an_entry_for_this -import bennu.composeapp.generated.resources.the_group_signs_an_entry_so_it_takes_a_quorum -import bennu.composeapp.generated.resources.this_entry_cannot_be_signed_as_it_is -import bennu.composeapp.generated.resources.this_field_is_required -import bennu.composeapp.generated.resources.this_group_has_no_shared_key_to_sign_an_entry -import bennu.composeapp.generated.resources.this_list_uses_a_field_type_this_app_does_not_support -import org.jetbrains.compose.resources.stringResource -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.machankura.bennu.compose.database.model.NostrEvent -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.extensions.toFormattedTimeAndDateString -import com.machankura.bennu.compose.nostr.CuratedSuggestion -import com.machankura.bennu.compose.nostr.GroupCuratedSchema -import com.machankura.bennu.compose.nostr.curated.CuratedEntry -import com.machankura.bennu.compose.nostr.curated.CuratedEntryProblem -import com.machankura.bennu.compose.nostr.curated.CuratedField -import com.machankura.bennu.compose.nostr.curated.CuratedFieldConfig -import com.machankura.bennu.compose.nostr.curated.CuratedFieldType -import com.machankura.bennu.compose.nostr.curated.CuratedSchema -import com.machankura.bennu.compose.nostr.curated.CuratedSchemaEvent -import com.machankura.bennu.compose.nostr.curated.CuratedVisibility -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.repository.NostrRepository -import com.machankura.bennu.compose.ui.composable.navigation.routes.FrostSigningRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.widgets.Decorative -import com.machankura.bennu.compose.ui.composable.widgets.ErrorState -import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator -import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState -import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton -import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition -import com.machankura.bennu.compose.ui.composable.widgets.buttons.ExtendedFab -import com.machankura.bennu.compose.ui.composable.widgets.rememberNotifier -import com.machankura.bennu.compose.ui.theme.ConformancePreviews -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.theme.readableContent -import com.machankura.bennu.compose.ui.theme.spacing -import com.machankura.bennu.compose.ui.view.model.AcceptCuratedSuggestionViewModel -import com.machankura.bennu.compose.ui.view.state.AcceptCuratedSuggestionUIState -import kotlin.time.Instant - -/** - * The form for taking one suggestion into a list the group curates. - * - * The queue screen shows what was suggested; this is where the group decides - * what the list will say. Every field the schema's form asks for is an input - * seeded from the suggestion, because curation is editorial -- the NIP lets - * the curator fix a year or swap a poster on the way through, and a button - * that could only say yes would leave a typo in the list forever. What the - * form does not ask for it shows: the identifier, which the entry keeps so - * that accepting it twice revises one entry rather than making two, and the - * fields the suggester's app filled in, which this app has no way to fill in - * itself. - * - * **The button proposes rather than saves.** The entry goes out as one kind - * 31890 for the room's quorum to put its key to, pointing back at the - * suggestion it came from, and the screen hands over to the signing session it - * opened. Nothing about the list has changed by the time this screen closes. - * The form is driven by a schema this screen has never seen, so a value the - * schema refuses is named under its own input rather than found out after a - * quorum has signed. - */ -@OptIn( - ExperimentalMaterial3ExpressiveApi::class, - ExperimentalMaterial3Api::class, - ExperimentalLayoutApi::class -) -@Composable -fun AcceptCuratedSuggestionScreen( - activeUserPublicKey: HexKey, - chatRoomId: String, - relayHint: String?, - identifier: String, - suggestionId: String, - initialAcceptCuratedSuggestionUIState: AcceptCuratedSuggestionUIState = - AcceptCuratedSuggestionUIState.Loading, - nostrRepository: NostrRepository, - chatRepository: ChatRepository, - frostSigningRepository: FrostSigningRepository, - onNavigateBack: () -> Unit, - onNavigateToRouteAndPopUpInclusive: (Route) -> Unit, -) { - val acceptCuratedSuggestionViewModel: AcceptCuratedSuggestionViewModel = viewModel( - factory = AcceptCuratedSuggestionViewModel.factory( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint, - identifier = identifier, - suggestionId = suggestionId, - initialAcceptCuratedSuggestionUIState = initialAcceptCuratedSuggestionUIState, - nostrRepository = nostrRepository, - chatRepository = chatRepository, - frostSigningRepository = frostSigningRepository - ) - ) - - LaunchedEffect(true) { - if (initialAcceptCuratedSuggestionUIState == AcceptCuratedSuggestionUIState.Loading) { - acceptCuratedSuggestionViewModel.initiate() - } - } - - // Read out here rather than in a click handler: both are composable and an - // onClick lambda is not. The scope is the caller's so a message survives this - // screen being replaced by the signing session. - val notify = rememberNotifier(rememberCoroutineScope()) - val couldNotPropose = stringResource(Res.string.could_not_ask_the_group_to_sign_this_entry) - - ScreenStateTransition(acceptCuratedSuggestionViewModel.acceptCuratedSuggestionUIState) { uiState -> - when (val state = uiState) { - is AcceptCuratedSuggestionUIState.Error -> { - // Nothing to retry: the room, the schema and the suggestion came - // from navigation arguments, and reading them again with the - // same ones fails the same way. - ErrorState(message = state.message, onRetry = null) - } - - AcceptCuratedSuggestionUIState.Loading -> { - LoadingDataIndicator() - } - - is AcceptCuratedSuggestionUIState.Loaded -> { - val canSign = state.canSign - - // The inputs come from the state rather than from whatever loaded - // it, so a screen handed a loaded state -- a preview, a layout - // test -- fills in the same as the app does. Seeding runs once. - LaunchedEffect(state) { - acceptCuratedSuggestionViewModel.seedWorkingCopy(state) - } - - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - modifier = Modifier.imePadding(), - topBar = { - TopAppBar( - title = { state.localChatRoom.RenderChatRoomTitleText() }, - navigationIcon = { NavigateBackButton(onNavigateBack) } - ) - }, - bottomBar = { - BottomAppBar( - actions = {}, - floatingActionButton = { - ExtendedFab( - label = stringResource(Res.string.propose_entry), - icon = { Icon(Icons.Default.Draw, contentDescription = "Propose entry") }, - enabled = canSign, - onClick = { - acceptCuratedSuggestionViewModel.proposeEntry( - state = state, - onSuccess = { sessionId -> - // Onto the session rather than back - // to the queue. The entry is not in - // the list yet -- it goes in when a - // quorum signs -- so landing on a - // queue still showing the row as - // waiting would read as a failure. - onNavigateToRouteAndPopUpInclusive.invoke( - FrostSigningRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - sessionId = sessionId - ) - ) - }, - // The reasons are drawn on the form - // itself, under the inputs they are - // about; a snackbar would name a - // problem and scroll away from it. - onInvalid = {}, - // Stays on the form with the edits still - // in it: a failure to open a session is - // no reason to throw away the typing. - onFailure = { notify(couldNotPropose) } - ) - } - ) - } - ) - } - ) { innerPadding -> - AcceptCuratedSuggestionForm( - state = state, - viewModel = acceptCuratedSuggestionViewModel, - modifier = Modifier.padding(innerPadding).readableContent().fillMaxSize() - ) - } - } - } - } -} - -/** - * The form under the bars: what is being taken up and into what, the reasons - * it cannot be as it stands, an input per field the schema asks for, and the - * fields it keeps. - * - * A lazy list rather than a scrolling column, the way the schema editor is, - * because the number of inputs is the schema's to decide and a long form is - * still one screen. Split out so a layout test can render it without the bars. - */ -@OptIn(ExperimentalLayoutApi::class) -@Composable -internal fun AcceptCuratedSuggestionForm( - state: AcceptCuratedSuggestionUIState.Loaded, - viewModel: AcceptCuratedSuggestionViewModel, - modifier: Modifier = Modifier -) { - val schema = state.schema.schema - val suggestion = state.suggestion - val editable = AcceptCuratedSuggestionViewModel.editableFields(state) - val kept = AcceptCuratedSuggestionViewModel.keptFields(state) - val entryProblems = viewModel.problemsAboutTheEntry(state) - - LazyColumn( - modifier = modifier, - contentPadding = PaddingValues( - horizontal = MaterialTheme.spacing.screenMargin, - vertical = MaterialTheme.spacing.itemGap - ), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), - horizontalAlignment = Alignment.CenterHorizontally - ) { - item { - Text( - text = suggestion.entry.title, - style = MaterialTheme.typography.titleLarge, - textAlign = TextAlign.Center, - maxLines = 2, - overflow = TextOverflow.Ellipsis - ) - } - - item { - Text( - text = stringResource( - Res.string.suggested_by_on, - suggestion.suggesterName(), - suggestion.suggestedAt.toFormattedTimeAndDateString() - ), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - textAlign = TextAlign.Center - ) - } - - item { - Text( - text = stringResource(Res.string.take_this_suggestion_into_the_list, schema.displayName()), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - textAlign = TextAlign.Center - ) - } - - item { - Text( - text = stringResource(Res.string.the_group_signs_an_entry_so_it_takes_a_quorum), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - textAlign = TextAlign.Center - ) - } - - // Said up front rather than left to the queue's mark: a member who did - // not notice would propose what they took for a new entry and get a - // revision, which is the right outcome but a surprising one. - if (suggestion.isCurated) { - item { - Row(verticalAlignment = Alignment.CenterVertically) { - Icon( - Icons.Default.CheckCircle, - contentDescription = Decorative, - tint = MaterialTheme.colorScheme.primary - ) - - Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) - - Text( - text = stringResource(Res.string.the_group_already_has_an_entry_for_this), - style = MaterialTheme.typography.bodySmall - ) - } - } - } - - if (!state.canSign) { - item { - Text( - text = stringResource(Res.string.this_group_has_no_shared_key_to_sign_an_entry), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error, - textAlign = TextAlign.Center - ) - } - } - - // The problems no input can carry: about the entry as a whole, or about - // a field the form keeps rather than asks for. Named, and all at once, - // for the reason the schema editor gives -- a button that does nothing - // is indistinguishable from a missed tap. - if (entryProblems.isNotEmpty()) { - item { - Column( - modifier = Modifier.fillMaxWidth(), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap) - ) { - Text( - text = stringResource(Res.string.this_entry_cannot_be_signed_as_it_is), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error - ) - - entryProblems.forEach { problem -> - val field = schema.fields.firstOrNull { it.name == problem.field } - val unsupported = schema.unsupportedFields.firstOrNull { it.name == problem.field } - - Text( - text = stringResource( - Res.string.field_and_problem, - field?.labelOrName() ?: unsupported?.labelOrName() ?: problem.field, - problem.message(field, schema) - ), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error - ) - } - } - } - } - - editable.forEach { field -> - item(key = field.name) { - val inputs = viewModel.inputs[field.name].orEmpty() - val problem = viewModel.problemsFor(field.name).firstOrNull() - - EntryFieldEditor( - field = field, - schema = schema, - inputs = inputs, - problem = problem, - onAddValue = { viewModel.addValue(field.name) }, - onRemoveValue = { index -> viewModel.removeValue(field.name, index) } - ) - } - } - - if (kept.isNotEmpty()) { - item { - Column( - modifier = Modifier.fillMaxWidth(), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap) - ) { - Spacer(modifier = Modifier.height(MaterialTheme.spacing.itemGap)) - - Text( - modifier = Modifier.fillMaxWidth(), - text = stringResource(Res.string.kept_from_the_suggestion), - style = MaterialTheme.typography.titleSmall - ) - - Text( - text = stringResource(Res.string.filled_in_by_the_suggester_s_app_and_kept), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - } - } - - kept.forEach { field -> - item(key = "kept:${field.name}") { - KeptField(field = field, values = suggestion.entry.values[field.name].orEmpty()) - } - } - } - } -} - -/** - * The inputs for one field, in the shape its type asks for. - * - * An enum is its options as chips, one selected, because typing a word that - * has to be one of six is a way to misspell it; everything else is a text - * field with the keyboard its type wants. A field that repeats is one input - * per value with a way to drop each and a way to add one, since the - * suggestion may have carried two watch links and the list may want a third. - * The schema's hint sits under the input until a problem takes its place. - */ -@OptIn(ExperimentalLayoutApi::class) -@Composable -private fun EntryFieldEditor( - field: CuratedField, - schema: CuratedSchema, - inputs: List, - problem: CuratedEntryProblem?, - onAddValue: () -> Unit, - onRemoveValue: (index: Int) -> Unit -) { - val message = problem?.message(field, schema) - val options = field.config.options - - Column( - modifier = Modifier.fillMaxWidth(), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap) - ) { - if (field.type == CuratedFieldType.Enum && !options.isNullOrEmpty()) { - EnumInput(field = field, options = options, input = inputs.firstOrNull(), message = message) - } else { - inputs.forEachIndexed { index, input -> - Row(verticalAlignment = Alignment.CenterVertically) { - EntryTextField( - modifier = Modifier.weight(1f), - state = input, - field = field, - // A problem is about the field, and the field is every - // input; the first is where a reader's eye lands. - message = message.takeIf { index == 0 }, - isError = problem != null - ) - - if (field.config.repeat == true) { - IconButton(onClick = { onRemoveValue(index) }) { - Icon( - Icons.Default.Delete, - contentDescription = "Remove this value", - tint = MaterialTheme.colorScheme.error - ) - } - } - } - } - - if (field.config.repeat == true) { - TextButton(onClick = onAddValue) { - Icon(Icons.Default.Add, contentDescription = Decorative) - Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) - Text(stringResource(Res.string.add_another)) - } - } - } - } -} - -/** - * An enum as chips. The selection is written into the field's one input, so - * the draft reads an enum the way it reads everything else; a value the - * suggestion carried that is not among the options is shown as an unselected - * set with the problem under it, rather than quietly dropped. - */ -@OptIn(ExperimentalLayoutApi::class) -@Composable -private fun EnumInput( - field: CuratedField, - options: List, - input: TextFieldState?, - message: String? -) { - val selected = input?.text?.toString() - - Text( - text = field.labelOrName(), - style = MaterialTheme.typography.labelMedium, - color = if (message != null) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant - ) - - FlowRow( - horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap) - ) { - options.forEach { option -> - FilterChip( - selected = option == selected, - onClick = { input?.setTextAndPlaceCursorAtEnd(option) }, - label = { Text(option) } - ) - } - } - - (message ?: field.config.hint)?.let { - Text( - text = it, - style = MaterialTheme.typography.bodySmall, - color = if (message != null) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant - ) - } -} - -/** - * One text input of the form, in the shape the app's other forms use: the - * borderless outlined field over the bottom bar's tint, labelled as the - * schema labels it and placeholdered as the schema says. - * - * The keyboard follows the type -- digits for a year, a URL keyboard for a - * link, and the plain one for a date, whose `2010-07` needs a hyphen the - * number pad does not always have -- and a long text gets room to be one. The - * supporting line is the problem when there is one and the schema's hint when - * there is not. - */ -@Composable -private fun EntryTextField( - state: TextFieldState, - field: CuratedField, - message: String?, - isError: Boolean, - modifier: Modifier = Modifier -) { - val keyboardType = when (field.type) { - CuratedFieldType.Year, CuratedFieldType.Duration, CuratedFieldType.Number -> KeyboardType.Number - CuratedFieldType.Url, CuratedFieldType.Image -> KeyboardType.Uri - else -> KeyboardType.Text - } - - OutlinedTextField( - modifier = modifier.fillMaxWidth().background(BottomAppBarDefaults.containerColor), - state = state, - lineLimits = if (field.type == CuratedFieldType.LongText) { - TextFieldLineLimits.MultiLine(minHeightInLines = 3) - } else { - TextFieldLineLimits.SingleLine - }, - isError = isError, - keyboardOptions = KeyboardOptions(keyboardType = keyboardType), - colors = OutlinedTextFieldDefaults.colors( - focusedBorderColor = Color.Transparent, - unfocusedBorderColor = Color.Transparent, - disabledBorderColor = Color.Transparent - ), - label = { - Text(text = field.labelOrName()) - }, - placeholder = field.placeholder.takeIf { it.isNotBlank() }?.let { { Text(text = it) } }, - supportingText = (message ?: field.config.hint)?.let { { Text(text = it) } } - ) -} - -/** - * A field the form keeps rather than asks for: the schema's label over the - * values as the suggestion carried them, the way the queue's sheet shows an - * entry. Monospaced where the value is a thing rather than prose. - */ -@Composable -private fun KeptField(field: CuratedField, values: List) { - val isMonospaced = when (field.type) { - CuratedFieldType.Token, CuratedFieldType.Url, CuratedFieldType.Image -> true - else -> false - } - - Column(modifier = Modifier.fillMaxWidth()) { - Text( - text = field.labelOrName(), - style = MaterialTheme.typography.labelMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - - Text( - text = values.joinToString("\n"), - style = MaterialTheme.typography.bodyMedium, - fontFamily = if (isMonospaced) FontFamily.Monospace else null, - color = MaterialTheme.colorScheme.onSurface, - modifier = Modifier.fillMaxWidth() - ) - } -} - -/** - * One problem in words, for the input it is about. - * - * The bounds are read off the field's config, since "at most 500" says - * something and "too long" does not; a `require-any` rule names the other - * fields it could have been satisfied by, as the schema labels them. - */ -@Composable -internal fun CuratedEntryProblem.message(field: CuratedField?, schema: CuratedSchema): String = when (reason) { - CuratedEntryProblem.Reason.Missing, - CuratedEntryProblem.Reason.Empty -> stringResource(Res.string.this_field_is_required) - - CuratedEntryProblem.Reason.Repeated -> stringResource(Res.string.only_one_value_for_this_field) - CuratedEntryProblem.Reason.NotOneWord -> stringResource(Res.string.one_word_without_spaces) - CuratedEntryProblem.Reason.NotAUrl -> stringResource(Res.string.that_is_not_a_web_address) - CuratedEntryProblem.Reason.NotHttps -> stringResource(Res.string.that_must_be_an_https_address) - CuratedEntryProblem.Reason.NotAnOption -> stringResource(Res.string.pick_one_of_the_options) - CuratedEntryProblem.Reason.NotAWholeNumber -> stringResource(Res.string.a_whole_number) - CuratedEntryProblem.Reason.NotPositive -> stringResource(Res.string.more_than_zero) - CuratedEntryProblem.Reason.NotADate -> stringResource(Res.string.a_date_as_yyyy_yyyy_mm_or_yyyy_mm_dd) - - // A date's bounds are years, and "at least 2009" is not how anyone says it. - CuratedEntryProblem.Reason.BelowMinimum -> stringResource( - if (field?.type == CuratedFieldType.Date) Res.string.n_or_later else Res.string.at_least_n, - field?.config?.min?.toString() ?: "" - ) - - CuratedEntryProblem.Reason.AboveMaximum -> stringResource( - if (field?.type == CuratedFieldType.Date) Res.string.n_or_earlier else Res.string.at_most_n, - field?.config?.max?.toString() ?: "" - ) - - CuratedEntryProblem.Reason.TooLong -> - stringResource(Res.string.at_most_n_characters, field?.config?.max?.toString() ?: "") - - CuratedEntryProblem.Reason.PatternMismatch -> - stringResource(Res.string.must_match_the_pattern, field?.config?.pattern ?: "") - - CuratedEntryProblem.Reason.RequireAnyUnmet -> stringResource( - Res.string.at_least_one_of_these_is_needed, - schema.requireAny.firstOrNull { it.firstOrNull() == this.field } - .orEmpty() - .joinToString { name -> schema.fields.firstOrNull { it.name == name }?.labelOrName() ?: name } - ) - - // The one problem the schema has and the entry does not: a required field - // is of a type this build cannot write, named so the member knows which. - CuratedEntryProblem.Reason.UnsupportedType -> stringResource( - Res.string.this_list_uses_a_field_type_this_app_does_not_support, - schema.unsupportedFields.firstOrNull { it.name == this.field }?.type ?: "" - ) - - // None of these can come out of the form: the builder writes the kind, the - // root and the source, and the group is the curator. Named all the same, - // since a check that cannot fail is the one that does. - CuratedEntryProblem.Reason.WrongKind, - CuratedEntryProblem.Reason.NotAReply, - CuratedEntryProblem.Reason.RepliesElsewhere, - CuratedEntryProblem.Reason.NotPermitted, - CuratedEntryProblem.Reason.NotTheCurator, - CuratedEntryProblem.Reason.SourceMalformed -> stringResource(Res.string.the_entry_cannot_be_signed_as_it_is) -} - -@ConformancePreviews -@Composable -private fun AcceptCuratedSuggestionScreenPreview() { - val chatRoomId = "d4c3b2a1".repeat(8) - val suggester = "eebb74ab6bfb8485722ab1d4acee856eee96f17a9e1721f9c7cc63376c40b860" - - val schema = GroupCuratedSchema( - signedEvent = GroupSignedEvent( - id = "c".repeat(64), - chatRoomId = chatRoomId, - publicKey = chatRoomId, - kind = CuratedSchemaEvent.KIND, - tags = emptyArray(), - content = "", - signature = "f".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_000) - ), - schema = CuratedSchema( - identifier = "films", - title = "Film suggestion", - name = "Films worth translating", - description = "Films the group would subtitle.", - visibility = CuratedVisibility.Public, - fields = listOf( - CuratedField.IDENTIFIER, - CuratedField.TITLE, - CuratedField("year", CuratedFieldType.Year, isRequired = false, label = "Year"), - CuratedField( - "type", - CuratedFieldType.Enum, - isRequired = true, - label = "Type", - config = CuratedFieldConfig(options = listOf("movie", "documentary", "short")) - ), - CuratedField( - "watchUrl", - CuratedFieldType.Url, - isRequired = false, - label = "Watch URL", - config = CuratedFieldConfig(tag = "r", marker = "watch", repeat = true) - ), - CuratedField( - "description", - CuratedFieldType.LongText, - isRequired = false, - label = "Why", - config = CuratedFieldConfig(tag = CuratedFieldConfig.CONTENT_TAG) - ), - CuratedField( - "hashtags", - CuratedFieldType.Token, - isRequired = false, - label = "Hashtags", - config = CuratedFieldConfig(tag = "t", repeat = true, derived = true) - ), - ), - relays = listOf("wss://relay.one.example") - ) - ) - - val suggestion = CuratedSuggestion( - entry = CuratedEntry( - kind = CuratedSchemaEvent.SUGGESTION_KIND, - id = "a".repeat(64), - pubKey = suggester, - createdAt = 1_700_000_900, - identifier = "the-rise-and-rise-of-bitcoin-2014", - title = "The Rise and Rise of Bitcoin", - values = mapOf( - "identifier" to listOf("the-rise-and-rise-of-bitcoin-2014"), - "title" to listOf("The Rise and Rise of Bitcoin"), - "year" to listOf("2014"), - "type" to listOf("documentary"), - "watchUrl" to listOf("http://bitcoindoc.com/"), - "description" to listOf("Follows the early Bitcoin community from 2011 onward."), - "hashtags" to listOf("bitcoin", "documentary"), - ) - ), - event = NostrEvent( - id = "a".repeat(64), - pubKey = suggester, - kind = CuratedSchemaEvent.SUGGESTION_KIND, - tags = emptyArray(), - content = "", - sig = "b".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_900) - ), - suggester = null, - isCurated = false - ) - - BennuTheme { - Surface(modifier = Modifier.fillMaxSize()) { - AcceptCuratedSuggestionScreen( - activeUserPublicKey = "u".repeat(64), - chatRoomId = chatRoomId, - relayHint = null, - identifier = "films", - suggestionId = suggestion.id, - initialAcceptCuratedSuggestionUIState = AcceptCuratedSuggestionUIState.Loaded( - localChatRoom = LocalChatRoom( - chatRoom = ChatRoom( - id = chatRoomId, - userPublicKey = "u".repeat(64), - subject = "Translation room", - description = null, - initialGiftWrapPayloadId = "sdfaer", - mlsGroupState = "state" - ) - ), - schema = schema, - suggestion = suggestion, - canSign = true - ), - nostrRepository = NostrRepository.NO_OP_NOSTR_REPOSITORY, - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, - onNavigateBack = {}, - onNavigateToRouteAndPopUpInclusive = {} - ) - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/BroadcastGroupSignedEventScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/BroadcastGroupSignedEventScreen.kt index b75242e5..07d356e5 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/BroadcastGroupSignedEventScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/BroadcastGroupSignedEventScreen.kt @@ -176,9 +176,6 @@ fun BroadcastGroupSignedEventScreen( broadcastGroupSignedEventViewModel.seedRelays( relayLists = broadcastGroupSignedEventUIState.relayLists, kind = signedEvent.kind, - tags = signedEvent.tags, - content = signedEvent.content, - schemas = broadcastGroupSignedEventUIState.schemas, ) } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ChatRoomDetailScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ChatRoomDetailScreen.kt index b7bc0cb5..a2ef8fdf 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ChatRoomDetailScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ChatRoomDetailScreen.kt @@ -23,13 +23,11 @@ import androidx.compose.material.icons.filled.Key import androidx.compose.material.icons.filled.AccountTree import androidx.compose.material.icons.filled.Autorenew import androidx.compose.material.icons.filled.ChevronRight -import androidx.compose.material.icons.filled.Checklist import androidx.compose.material.icons.filled.ContentCopy import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.DeleteForever import androidx.compose.material.icons.filled.PersonRemove import androidx.compose.material.icons.filled.Badge -import androidx.compose.material.icons.filled.Ballot import androidx.compose.material.icons.filled.Campaign import androidx.compose.material.icons.filled.DataObject import androidx.compose.material.icons.filled.Dns @@ -87,8 +85,6 @@ import com.machankura.bennu.compose.ui.composable.navigation.routes.ProposeGroup import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupNostrProfileRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupRelaysRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupPostsRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupCuratedSchemasRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupCuratedEntriesRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.ProposalListRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.SearchMemberToAddToChatRoomRoute import com.machankura.bennu.compose.extensions.inComparableGroups @@ -109,19 +105,11 @@ import bennu.composeapp.generated.resources.run_by_members import bennu.composeapp.generated.resources.nostr_profile import bennu.composeapp.generated.resources.relays import bennu.composeapp.generated.resources.posts -import bennu.composeapp.generated.resources.curated_entries -import bennu.composeapp.generated.resources.curated_schemas import bennu.composeapp.generated.resources.not_described_yet import bennu.composeapp.generated.resources.n_of_m_relay_lists_agreed import bennu.composeapp.generated.resources.no_posts_yet import bennu.composeapp.generated.resources.one_post import bennu.composeapp.generated.resources.n_posts -import bennu.composeapp.generated.resources.no_schemas_yet -import bennu.composeapp.generated.resources.one_schema -import bennu.composeapp.generated.resources.n_schemas -import bennu.composeapp.generated.resources.no_entries_yet -import bennu.composeapp.generated.resources.one_entry -import bennu.composeapp.generated.resources.n_entries import bennu.composeapp.generated.resources.propose_event import bennu.composeapp.generated.resources.no_name_on_this_profile import bennu.composeapp.generated.resources.parent_group @@ -466,62 +454,6 @@ fun ChatRoomDetailScreen( ) } - // Under the posts, because a schema is the other - // thing a group publishes for strangers to answer: - // a post is the group speaking, a schema is the - // group asking -- for entries to a list it will - // then curate, by quorum, under the same key. What - // it curated follows, in the row below. - item { - SignedWorkRow( - icon = Icons.Default.Ballot, - headline = stringResource(Res.string.curated_schemas), - supporting = when (val count = chatRoomDetailUIState.groupCuratedSchemas.size) { - 0 -> stringResource(Res.string.no_schemas_yet) - 1 -> stringResource(Res.string.one_schema) - else -> stringResource(Res.string.n_schemas, count) - }, - onOpen = { - onNavigateToRoute.invoke( - GroupCuratedSchemasRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint - ) - ) - } - ) - } - - // Under the schemas, because these are what a - // schema is *for*: the schema asks, strangers - // answer on the queue, and these are the answers - // the group put its key to. They close the - // identity block because everything in it is - // signed by that key and read by people who were - // never in the room, and an accepted entry is the - // last thing in that chain. - item { - SignedWorkRow( - icon = Icons.Default.Checklist, - headline = stringResource(Res.string.curated_entries), - supporting = when (val count = chatRoomDetailUIState.groupCuratedEntries.size) { - 0 -> stringResource(Res.string.no_entries_yet) - 1 -> stringResource(Res.string.one_entry) - else -> stringResource(Res.string.n_entries, count) - }, - onOpen = { - onNavigateToRoute.invoke( - GroupCuratedEntriesRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint - ) - ) - } - ) - } - // The group's coins. After the identity block's // last signed row and before the paste, because it // is signed by the same key and read by nobody diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/CuratedSuggestionListScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/CuratedSuggestionListScreen.kt deleted file mode 100644 index 099cf666..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/CuratedSuggestionListScreen.kt +++ /dev/null @@ -1,675 +0,0 @@ -package com.machankura.bennu.compose.ui.composable - -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.CheckCircle -import androidx.compose.material.icons.filled.Draw -import androidx.compose.material3.Button -import androidx.compose.material3.Card -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi -import androidx.compose.material3.Icon -import androidx.compose.material3.ListItem -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Scaffold -import androidx.compose.material3.SnackbarHost -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.text.font.FontFamily -import androidx.compose.ui.text.style.TextOverflow -import androidx.lifecycle.viewmodel.compose.viewModel -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.displayUrl -import bennu.composeapp.generated.resources.Res -import bennu.composeapp.generated.resources.accept_this_suggestion -import bennu.composeapp.generated.resources.ask_again -import bennu.composeapp.generated.resources.asking_the_list_s_relays -import bennu.composeapp.generated.resources.curated -import bennu.composeapp.generated.resources.everything_anyone_has_suggested_to_this_list -import bennu.composeapp.generated.resources.n_curated -import bennu.composeapp.generated.resources.n_suggestions -import bennu.composeapp.generated.resources.nobody_has_suggested_anything_to_this_list_yet -import bennu.composeapp.generated.resources.one_suggestion -import bennu.composeapp.generated.resources.read_from_relays -import bennu.composeapp.generated.resources.revise_the_list_s_entry -import bennu.composeapp.generated.resources.suggested_by_on -import bennu.composeapp.generated.resources.suggestions -import bennu.composeapp.generated.resources.taken_up_by_the_group_into_the_list -import org.jetbrains.compose.resources.stringResource -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.machankura.bennu.compose.database.model.NostrEvent -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.extensions.toFormattedTimeAndDateString -import com.machankura.bennu.compose.nostr.CuratedSuggestion -import com.machankura.bennu.compose.nostr.GroupCuratedSchema -import com.machankura.bennu.compose.nostr.curated.CuratedEntry -import com.machankura.bennu.compose.nostr.curated.CuratedField -import com.machankura.bennu.compose.nostr.curated.CuratedFieldConfig -import com.machankura.bennu.compose.nostr.curated.CuratedFieldType -import com.machankura.bennu.compose.nostr.curated.CuratedSchema -import com.machankura.bennu.compose.nostr.curated.CuratedSchemaEvent -import com.machankura.bennu.compose.nostr.curated.CuratedVisibility -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.NostrRepository -import com.machankura.bennu.compose.ui.composable.navigation.routes.AcceptCuratedSuggestionRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.widgets.Decorative -import com.machankura.bennu.compose.ui.composable.widgets.EmptyState -import com.machankura.bennu.compose.ui.composable.widgets.ErrorState -import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator -import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState -import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition -import com.machankura.bennu.compose.ui.composable.widgets.dialogs.ModalBottomSheet -import com.machankura.bennu.compose.ui.composable.widgets.profile.ProfileAvatar -import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton -import com.machankura.bennu.compose.ui.theme.ConformancePreviews -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.theme.readableContent -import com.machankura.bennu.compose.ui.theme.spacing -import com.machankura.bennu.compose.ui.view.model.CuratedSuggestionListViewModel -import com.machankura.bennu.compose.ui.view.state.CuratedSuggestionListUIState -import kotlin.time.Instant - -/** - * Everything anyone has suggested to one list the group curates. - * - * The group's screen shows the schema: what the list asks for. This is what it - * has been answered with -- one row per suggestion, newest first, whoever - * signed it -- which is the view a member wants before the group takes - * anything up: to see what is waiting, and what has already been taken. - * - * Read from the relays the schema names, and the header says which, because a - * queue read from the wrong relays and a list nobody has written to look the - * same from here. A suggestion that does not satisfy the schema is not on this - * screen at all; see `CuratedSuggestion`. - * - * A row opens a sheet with the whole entry, field by field, and the one thing - * a member can do about it from here: take it into the list, which opens the - * form that proposes the canonical entry for the group to sign. - */ -@OptIn(ExperimentalMaterial3Api::class, ExperimentalMaterial3ExpressiveApi::class) -@Composable -fun CuratedSuggestionListScreen( - activeUserPublicKey: HexKey, - chatRoomId: String, - relayHint: String?, - identifier: String, - initialCuratedSuggestionListUIState: CuratedSuggestionListUIState = - CuratedSuggestionListUIState.Loading, - nostrRepository: NostrRepository, - chatRepository: ChatRepository, - onNavigateBack: () -> Unit, - onNavigateToRoute: (Route) -> Unit, -) { - val curatedSuggestionListViewModel: CuratedSuggestionListViewModel = viewModel( - factory = CuratedSuggestionListViewModel.factory( - chatRoomId = chatRoomId, - activeUserPublicKey = activeUserPublicKey, - relayHint = relayHint, - identifier = identifier, - initialCuratedSuggestionListUIState = initialCuratedSuggestionListUIState, - nostrRepository = nostrRepository, - chatRepository = chatRepository, - ) - ) - - LaunchedEffect(true) { - if (initialCuratedSuggestionListUIState == CuratedSuggestionListUIState.Loading) { - curatedSuggestionListViewModel.initiate() - } - } - - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - topBar = { - TopAppBar( - title = { - Text( - text = stringResource(Res.string.suggestions), - maxLines = 1, - overflow = TextOverflow.Ellipsis - ) - }, - navigationIcon = { NavigateBackButton(onNavigateBack) } - ) - } - ) { padding -> - ScreenStateTransition(curatedSuggestionListViewModel.curatedSuggestionListUIState) { uiState -> - when (val state = uiState) { - is CuratedSuggestionListUIState.Error -> { - // Nothing to retry: the room and the identifier came from a - // navigation argument, and reading them again with the same - // ones fails the same way. - ErrorState( - modifier = Modifier.padding(padding), - message = state.message, - onRetry = null - ) - } - - CuratedSuggestionListUIState.Loading -> { - Column( - modifier = Modifier.fillMaxWidth().padding(padding).padding(MaterialTheme.spacing.screenMargin), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.sectionGap) - ) { - Spacer(modifier = Modifier.height(MaterialTheme.spacing.emphasisGap)) - - LoadingDataIndicator(fillScreen = false) - } - } - - is CuratedSuggestionListUIState.Loaded -> { - // The id rather than the row, so the sheet follows an edit - // that replaces the row under it, and survives a rotation. - var openSuggestionId by rememberSaveable { mutableStateOf(null) } - - LazyColumn( - modifier = Modifier.padding(padding).readableContent().fillMaxSize() - .padding(MaterialTheme.spacing.space250), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space125) - ) { - item { - CuratedQueueHeader(state = state) - } - - if (state.suggestions.isEmpty()) { - item { - if (state.isAsking) { - LoadingDataIndicator( - fillScreen = false, - text = stringResource(Res.string.asking_the_list_s_relays) - ) - } else { - // Empty is a fact about the relays that were - // asked, and asking again is the one thing a - // member can do about it from here. - EmptyState( - message = stringResource( - Res.string.nobody_has_suggested_anything_to_this_list_yet - ), - action = { - TextButton( - onClick = { curatedSuggestionListViewModel.askAgain() } - ) { - Text(stringResource(Res.string.ask_again)) - } - } - ) - } - } - } else { - items( - items = state.suggestions, - key = { suggestion -> suggestion.id } - ) { suggestion -> - CuratedSuggestionCard( - suggestion = suggestion, - schema = state.schema.schema, - onOpen = { openSuggestionId = suggestion.id } - ) - } - } - } - - openSuggestionId - ?.let { id -> state.suggestions.firstOrNull { it.id == id } } - ?.let { suggestion -> - CuratedSuggestionSheet( - suggestion = suggestion, - schema = state.schema.schema, - onAccept = { - openSuggestionId = null - onNavigateToRoute( - AcceptCuratedSuggestionRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint, - identifier = identifier, - suggestionId = suggestion.id - ) - ) - }, - onDismiss = { openSuggestionId = null } - ) - } - } - } - } - } -} - -/** - * What the queue is, in numbers, and where it was read from. - * - * The list is named the way its card on the group's screen names it -- the - * domain where it claims one, else the name -- so a member arriving from that - * card finds the same word. The counts are the reference client's line: how - * many are waiting, and how many of those the group has already taken up. - */ -@Composable -private fun CuratedQueueHeader(state: CuratedSuggestionListUIState.Loaded) { - Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) { - Text( - text = state.schema.schema.displayName(), - style = MaterialTheme.typography.titleLarge, - maxLines = 1, - overflow = TextOverflow.Ellipsis - ) - - Text( - text = stringResource(Res.string.everything_anyone_has_suggested_to_this_list), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - - Text( - text = listOfNotNull( - when (state.suggestions.size) { - 1 -> stringResource(Res.string.one_suggestion) - else -> stringResource(Res.string.n_suggestions, state.suggestions.size) - }, - state.curatedCount.takeIf { it > 0 }?.let { stringResource(Res.string.n_curated, it) } - ).joinToString(" · "), - style = MaterialTheme.typography.labelMedium - ) - - if (state.relays.isNotEmpty()) { - Text( - text = stringResource( - Res.string.read_from_relays, - state.relays.joinToString { relay -> - RelayUrlNormalizer.normalizeOrNull(relay)?.displayUrl() ?: relay - } - ), - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - } - } -} - -/** - * One suggestion, as a row somebody is scanning. - * - * The title, because every list has one; a glance at the fields that say what - * the entry *is* -- the type, the year, the director -- and not the ones that - * say where to find it, since a URL on a row is a line of noise and the sheet - * has them; the body where the list has one; and who suggested it, when. The - * avatar is the suggester's, tinted from their key like every avatar here, so - * two suggestions by one stranger read as one stranger. - * - * "Curated" on the row is the one thing on it a member might act on: it says - * the group already took this up, and re-curating it would revise the entry - * rather than add one. - */ -@Composable -private fun CuratedSuggestionCard( - suggestion: CuratedSuggestion, - schema: CuratedSchema, - onOpen: () -> Unit -) { - val entry = suggestion.entry - - Card(modifier = Modifier.fillMaxWidth(), onClick = onOpen) { - ListItem( - leadingContent = { - ProfileAvatar(publicKey = entry.pubKey, profile = suggestion.suggester) - }, - trailingContent = if (suggestion.isCurated) { - { CuratedMark() } - } else { - null - }, - headlineContent = { - Text( - text = entry.title, - maxLines = 2, - overflow = TextOverflow.Ellipsis - ) - }, - supportingContent = { - Column( - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap) - ) { - glanceOf(entry, schema)?.let { - Text( - text = it, - style = MaterialTheme.typography.bodySmall, - maxLines = 2, - overflow = TextOverflow.Ellipsis - ) - } - - bodyOf(entry, schema)?.let { - Text( - text = it, - maxLines = 2, - overflow = TextOverflow.Ellipsis - ) - } - - Text( - text = stringResource( - Res.string.suggested_by_on, - suggestion.suggesterName(), - suggestion.suggestedAt.toFormattedTimeAndDateString() - ), - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - } - } - ) - } -} - -@Composable -private fun CuratedMark() { - Row(verticalAlignment = Alignment.CenterVertically) { - // The word beside it says it, so the icon says nothing twice. - Icon( - Icons.Default.CheckCircle, - contentDescription = Decorative, - tint = MaterialTheme.colorScheme.primary - ) - - Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) - - Text( - text = stringResource(Res.string.curated), - style = MaterialTheme.typography.labelLarge, - color = MaterialTheme.colorScheme.primary - ) - } -} - -/** - * The fields worth a glance on a row, as `Label: value`, or null when the entry - * has none of them. - * - * The fields a form prompts for, less the title (the headline), the body (its - * own line) and anything that is a link (the sheet). Labelled because a bare - * "2014 · en" says nothing to somebody who does not know the list's fields, - * and this screen is driven by a schema it has never seen before. Shared with - * the group's screen, so an entry is described the same way on both. - */ -internal fun glanceOf(entry: CuratedEntry, schema: CuratedSchema): String? = - schema.formFields() - .filterNot { it.tag() == TITLE_TAG || it.tag() == CuratedFieldConfig.CONTENT_TAG } - .filterNot { it.type == CuratedFieldType.Url || it.type == CuratedFieldType.Image } - .mapNotNull { field -> - entry.values[field.name]?.let { values -> "${field.labelOrName()}: ${values.joinToString()}" } - } - .takeIf { it.isNotEmpty() } - ?.joinToString(" · ") - -/** The value of the field that writes to the body, or null. */ -internal fun bodyOf(entry: CuratedEntry, schema: CuratedSchema): String? = - schema.fields.firstOrNull { it.tag() == CuratedFieldConfig.CONTENT_TAG }?.let { entry.value(it.name) } - -private const val TITLE_TAG = "title" - -/** - * The whole of one suggestion, and the way to take it into the list. - * - * Every field the entry has a value for, labelled as the schema labels it, so - * the sheet reads as the form would have -- and then the button, which is the - * one thing a member can do about a suggestion: open the form that proposes it - * as the list's own, for the group to sign. The event itself is not shown; it - * is what the form is built from, and the form shows it as fields rather than - * as JSON, which is how a member reads it and how the group will sign it. - */ -@Composable -private fun CuratedSuggestionSheet( - suggestion: CuratedSuggestion, - schema: CuratedSchema, - onAccept: () -> Unit, - onDismiss: () -> Unit -) { - ModalBottomSheet(onDismiss = onDismiss) { - CuratedSuggestionSheetContent(suggestion = suggestion, schema = schema, onAccept = onAccept) - } -} - -/** - * The sheet's body, apart from the sheet. Split out so it can be rendered and - * measured on its own, since a bottom sheet is a popup a layout test cannot - * reach into. - */ -@Composable -internal fun CuratedSuggestionSheetContent( - suggestion: CuratedSuggestion, - schema: CuratedSchema, - onAccept: () -> Unit -) { - val entry = suggestion.entry - - Column(modifier = Modifier.fillMaxWidth()) { - Text( - text = entry.title, - style = MaterialTheme.typography.titleMedium - ) - - Spacer(modifier = Modifier.height(MaterialTheme.spacing.relatedGap)) - - Text( - text = stringResource( - Res.string.suggested_by_on, - suggestion.suggesterName(), - suggestion.suggestedAt.toFormattedTimeAndDateString() - ), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - - if (suggestion.isCurated) { - Spacer(modifier = Modifier.height(MaterialTheme.spacing.relatedGap)) - - Row(verticalAlignment = Alignment.CenterVertically) { - Icon( - Icons.Default.CheckCircle, - contentDescription = Decorative, - tint = MaterialTheme.colorScheme.primary - ) - - Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) - - Text( - text = stringResource(Res.string.taken_up_by_the_group_into_the_list), - style = MaterialTheme.typography.bodyMedium - ) - } - } - - Spacer(modifier = Modifier.height(MaterialTheme.spacing.sectionGap)) - - // In the schema's order, which is the order the form asked in, and - // only the fields the entry answered: a form's empty inputs are not - // worth a line each here. The title is the heading and is not said twice. - schema.fields.filterNot { it.tag() == TITLE_TAG }.forEach { field -> - entry.values[field.name]?.let { values -> - CuratedSuggestionField(field = field, values = values) - } - } - - Spacer(modifier = Modifier.height(MaterialTheme.spacing.itemGap)) - - // The same button either way, worded for what it will do: a suggestion - // the group already took up is revised in place, since the canonical - // entry keeps its identifier, and a member should not have to find that - // out from the queue afterwards. - Button( - onClick = onAccept, - modifier = Modifier.fillMaxWidth() - ) { - Icon(Icons.Default.Draw, contentDescription = Decorative) - Spacer(modifier = Modifier.width(MaterialTheme.spacing.space100)) - Text( - text = stringResource( - if (suggestion.isCurated) { - Res.string.revise_the_list_s_entry - } else { - Res.string.accept_this_suggestion - } - ) - ) - } - } -} - -/** - * One field of an entry: the schema's label over the value, or the values one - * under another for a field that repeats. Monospaced where the value is a - * thing rather than prose -- a token, a link -- because those are compared and - * copied rather than read. - */ -@Composable -private fun CuratedSuggestionField(field: CuratedField, values: List) { - val isMonospaced = when (field.type) { - CuratedFieldType.Token, CuratedFieldType.Url, CuratedFieldType.Image -> true - else -> false - } - - Text( - text = field.labelOrName(), - style = MaterialTheme.typography.labelMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - - Text( - text = values.joinToString("\n"), - style = MaterialTheme.typography.bodyMedium, - fontFamily = if (isMonospaced) FontFamily.Monospace else null, - // Stated rather than inherited: the label above is deliberately quieter, - // and the value is the thing that was come for. - color = MaterialTheme.colorScheme.onSurface, - modifier = Modifier.fillMaxWidth() - ) - - Spacer(modifier = Modifier.height(MaterialTheme.spacing.itemGap)) -} - -@ConformancePreviews -@Composable -private fun CuratedSuggestionListScreenPreview() { - val chatRoomId = "d4c3b2a1".repeat(8) - val suggester = "eebb74ab6bfb8485722ab1d4acee856eee96f17a9e1721f9c7cc63376c40b860" - - val schema = GroupCuratedSchema( - signedEvent = GroupSignedEvent( - id = "c".repeat(64), - chatRoomId = chatRoomId, - publicKey = chatRoomId, - kind = CuratedSchemaEvent.KIND, - tags = emptyArray(), - content = "", - signature = "f".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_000) - ), - schema = CuratedSchema( - identifier = "films", - title = "Film suggestion", - name = "Films worth translating", - description = "Films the group would subtitle.", - visibility = CuratedVisibility.Public, - fields = listOf( - CuratedField.IDENTIFIER, - CuratedField.TITLE, - CuratedField("year", CuratedFieldType.Year, isRequired = false, label = "Year"), - CuratedField("type", CuratedFieldType.Enum, isRequired = true, label = "Type"), - CuratedField( - "description", - CuratedFieldType.LongText, - isRequired = false, - label = "Why", - config = CuratedFieldConfig(tag = CuratedFieldConfig.CONTENT_TAG) - ), - ), - relays = listOf("wss://relay.one.example") - ) - ) - - fun suggestion(title: String, createdAt: Long, isCurated: Boolean) = CuratedSuggestion( - entry = CuratedEntry( - kind = CuratedSchemaEvent.SUGGESTION_KIND, - id = createdAt.toString().padStart(64, 'a'), - pubKey = suggester, - createdAt = createdAt, - identifier = title.lowercase().replace(' ', '-'), - title = title, - values = mapOf( - "title" to listOf(title), - "year" to listOf("2014"), - "type" to listOf("documentary"), - "description" to listOf("Follows the early Bitcoin community from 2011 onward."), - ) - ), - event = NostrEvent( - id = createdAt.toString().padStart(64, 'a'), - pubKey = suggester, - kind = CuratedSchemaEvent.SUGGESTION_KIND, - tags = emptyArray(), - content = "", - sig = "b".repeat(128), - createdAt = Instant.fromEpochSeconds(createdAt) - ), - suggester = null, - isCurated = isCurated - ) - - BennuTheme { - Surface(modifier = Modifier.fillMaxSize()) { - CuratedSuggestionListScreen( - activeUserPublicKey = "u".repeat(64), - chatRoomId = chatRoomId, - relayHint = null, - identifier = "films", - initialCuratedSuggestionListUIState = CuratedSuggestionListUIState.Loaded( - localChatRoom = LocalChatRoom( - chatRoom = ChatRoom( - id = chatRoomId, - userPublicKey = "u".repeat(64), - subject = "Translation room", - description = null, - initialGiftWrapPayloadId = "sdfaer", - mlsGroupState = "state" - ) - ), - schema = schema, - relays = listOf("wss://relay.one.example"), - suggestions = listOf( - suggestion("The Rise and Rise of Bitcoin", 1_700_000_900, isCurated = true), - suggestion("Magic Money", 1_700_000_000, isCurated = false), - ) - ), - nostrRepository = NostrRepository.NO_OP_NOSTR_REPOSITORY, - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - onNavigateBack = {}, - onNavigateToRoute = {} - ) - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/EditGroupCuratedSchemaScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/EditGroupCuratedSchemaScreen.kt deleted file mode 100644 index 174b046f..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/EditGroupCuratedSchemaScreen.kt +++ /dev/null @@ -1,1525 +0,0 @@ -package com.machankura.bennu.compose.ui.composable - -import androidx.compose.foundation.background -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.ExperimentalLayoutApi -import androidx.compose.foundation.layout.FlowRow -import androidx.compose.foundation.layout.PaddingValues -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.imePadding -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -import androidx.compose.foundation.lazy.itemsIndexed -import androidx.compose.foundation.text.input.TextFieldLineLimits -import androidx.compose.foundation.text.input.TextFieldState -import androidx.compose.foundation.text.input.clearText -import androidx.compose.foundation.text.input.rememberTextFieldState -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.automirrored.filled.Label -import androidx.compose.material.icons.automirrored.filled.Notes -import androidx.compose.material.icons.automirrored.filled.Rule -import androidx.compose.material.icons.automirrored.filled.ShortText -import androidx.compose.material.icons.filled.Add -import androidx.compose.material.icons.filled.Ballot -import androidx.compose.material.icons.filled.Bookmark -import androidx.compose.material.icons.filled.Checklist -import androidx.compose.material.icons.filled.Delete -import androidx.compose.material.icons.filled.Dns -import androidx.compose.material.icons.filled.Draw -import androidx.compose.material.icons.filled.Image -import androidx.compose.material.icons.filled.Language -import androidx.compose.material.icons.filled.Lightbulb -import androidx.compose.material.icons.filled.Numbers -import androidx.compose.material.icons.filled.PersonAdd -import androidx.compose.material.icons.filled.Sell -import androidx.compose.material.icons.filled.Tag -import androidx.compose.material.icons.filled.Title -import androidx.compose.material3.BottomAppBar -import androidx.compose.material3.BottomAppBarDefaults -import androidx.compose.material3.Button -import androidx.compose.material3.ButtonDefaults -import androidx.compose.material3.Card -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi -import androidx.compose.material3.FilterChip -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton -import androidx.compose.material3.ListItem -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedTextField -import androidx.compose.material3.OutlinedTextFieldDefaults -import androidx.compose.material3.Scaffold -import androidx.compose.material3.SegmentedButton -import androidx.compose.material3.SegmentedButtonDefaults -import androidx.compose.material3.SingleChoiceSegmentedButtonRow -import androidx.compose.material3.SnackbarHost -import androidx.compose.material3.Surface -import androidx.compose.material3.Switch -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue -import androidx.compose.runtime.snapshotFlow -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.graphics.vector.ImageVector -import androidx.compose.ui.semantics.contentDescription -import androidx.compose.ui.semantics.disabled -import androidx.compose.ui.semantics.semantics -import androidx.compose.ui.text.font.FontFamily -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.text.style.TextOverflow -import androidx.lifecycle.viewmodel.compose.viewModel -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.extensions.hexToNpubHrp -import com.machankura.bennu.compose.nostr.curated.CuratedField -import com.machankura.bennu.compose.nostr.curated.CuratedFieldType -import com.machankura.bennu.compose.nostr.curated.CuratedSchemaEvent -import com.machankura.bennu.compose.nostr.curated.CuratedSchemaProblem -import com.machankura.bennu.compose.nostr.curated.CuratedSchemaTemplate -import com.machankura.bennu.compose.nostr.curated.CuratedVisibility -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.ui.composable.navigation.routes.FrostSigningRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.widgets.Decorative -import com.machankura.bennu.compose.ui.composable.widgets.ErrorState -import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator -import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState -import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton -import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition -import com.machankura.bennu.compose.ui.composable.widgets.buttons.ExtendedFab -import com.machankura.bennu.compose.ui.composable.widgets.dialogs.ModalBottomSheet -import com.machankura.bennu.compose.ui.composable.widgets.rememberNotifier -import com.machankura.bennu.compose.ui.theme.ConformancePreviews -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.theme.readableContent -import com.machankura.bennu.compose.ui.theme.spacing -import com.machankura.bennu.compose.ui.view.model.EditGroupCuratedSchemaViewModel -import com.machankura.bennu.compose.ui.view.model.EditGroupCuratedSchemaViewModel.AddRelayFailure -import com.machankura.bennu.compose.ui.view.model.EditGroupCuratedSchemaViewModel.AddSuggesterFailure -import com.machankura.bennu.compose.ui.view.model.EditGroupCuratedSchemaViewModel.FieldEdit -import com.machankura.bennu.compose.ui.view.model.EditGroupCuratedSchemaViewModel.FieldProblem -import com.machankura.bennu.compose.ui.view.state.EditGroupCuratedSchemaUIState -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import bennu.composeapp.generated.resources.Res -import bennu.composeapp.generated.resources.a_description_is_required -import bennu.composeapp.generated.resources.a_domain_replaces_the_name_wherever_the_list_is_shown -import bennu.composeapp.generated.resources.a_field_name_is_one_word -import bennu.composeapp.generated.resources.a_field_named_that_already_exists -import bennu.composeapp.generated.resources.a_field_needs_a_name -import bennu.composeapp.generated.resources.a_name_is_required -import bennu.composeapp.generated.resources.a_regular_expression_the_whole_value_must_match -import bennu.composeapp.generated.resources.a_schema_needs_at_least_one_field -import bennu.composeapp.generated.resources.a_title_is_required -import bennu.composeapp.generated.resources.add_field -import bennu.composeapp.generated.resources.add_rule -import bennu.composeapp.generated.resources.add_schema -import bennu.composeapp.generated.resources.an_entry_must_have_this_field -import bennu.composeapp.generated.resources.an_identifier_is_required -import bennu.composeapp.generated.resources.at_least_one_of -import bennu.composeapp.generated.resources.could_not_ask_the_group_to_sign_this_schema -import bennu.composeapp.generated.resources.defaults_to_the_field_name_content_means_the_body -import bennu.composeapp.generated.resources.derived -import bennu.composeapp.generated.resources.description -import bennu.composeapp.generated.resources.domain -import bennu.composeapp.generated.resources.done -import bennu.composeapp.generated.resources.edit_field -import bennu.composeapp.generated.resources.edit_schema -import bennu.composeapp.generated.resources.earliest_year -import bennu.composeapp.generated.resources.eg_1900 -import bennu.composeapp.generated.resources.eg_200 -import bennu.composeapp.generated.resources.eg_2100 -import bennu.composeapp.generated.resources.eg_a_za_z_2_8 -import bennu.composeapp.generated.resources.eg_bitcoin_mov -import bennu.composeapp.generated.resources.eg_movie_documentary_short -import bennu.composeapp.generated.resources.eg_bitcoin_mov_suggestion -import bennu.composeapp.generated.resources.eg_example_com -import bennu.composeapp.generated.resources.eg_fields_for_a_bitcoin_mov_entry -import bennu.composeapp.generated.resources.eg_https_example_com_group_png -import bennu.composeapp.generated.resources.eg_https_youtube_com_watch -import bennu.composeapp.generated.resources.eg_watch -import bennu.composeapp.generated.resources.eg_watch_reference_url -import bennu.composeapp.generated.resources.eg_watchurl -import bennu.composeapp.generated.resources.eg_wss_relay_example_com -import bennu.composeapp.generated.resources.field_name -import bennu.composeapp.generated.resources.field_type_date -import bennu.composeapp.generated.resources.field_type_duration -import bennu.composeapp.generated.resources.field_type_enum -import bennu.composeapp.generated.resources.field_type_image -import bennu.composeapp.generated.resources.field_type_longtext -import bennu.composeapp.generated.resources.field_type_number -import bennu.composeapp.generated.resources.field_type_text -import bennu.composeapp.generated.resources.field_type_token -import bennu.composeapp.generated.resources.field_type_url -import bennu.composeapp.generated.resources.field_type_year -import bennu.composeapp.generated.resources.fields -import bennu.composeapp.generated.resources.filled_in_by_the_app_never_asked_for -import bennu.composeapp.generated.resources.helper_text_under_the_input -import bennu.composeapp.generated.resources.hint -import bennu.composeapp.generated.resources.https_only -import bennu.composeapp.generated.resources.identifier -import bennu.composeapp.generated.resources.label -import bennu.composeapp.generated.resources.latest_year -import bennu.composeapp.generated.resources.marker -import bennu.composeapp.generated.resources.maximum_characters -import bennu.composeapp.generated.resources.maximum_value -import bennu.composeapp.generated.resources.may_appear_more_than_once -import bennu.composeapp.generated.resources.minimum_value -import bennu.composeapp.generated.resources.name -import bennu.composeapp.generated.resources.new_field -import bennu.composeapp.generated.resources.no_relays_named_so_a_client_will_pick_its_own -import bennu.composeapp.generated.resources.nothing_has_changed_to_propose -import bennu.composeapp.generated.resources.npub_or_hex_pubkey -import bennu.composeapp.generated.resources.one_of_the_relays_is_not_a_relay_address -import bennu.composeapp.generated.resources.one_per_line_or_separated_by_commas -import bennu.composeapp.generated.resources.optional -import bennu.composeapp.generated.resources.options -import bennu.composeapp.generated.resources.pattern -import bennu.composeapp.generated.resources.pick_two_or_more_fields_at_least_one_of_which_an_entry_must_have -import bennu.composeapp.generated.resources.picture_url -import bennu.composeapp.generated.resources.placeholder -import bennu.composeapp.generated.resources.propose_schema -import bennu.composeapp.generated.resources.pubkeys_besides_the_group_that_may_suggest_to_this_list -import bennu.composeapp.generated.resources.relay_url -import bennu.composeapp.generated.resources.relays -import bennu.composeapp.generated.resources.remove_field -import bennu.composeapp.generated.resources.required -import bennu.composeapp.generated.resources.say_who_may_suggest_to_this_list -import bennu.composeapp.generated.resources.suggesters -import bennu.composeapp.generated.resources.that_is_not_a_domain_name -import bennu.composeapp.generated.resources.that_is_not_a_pubkey -import bennu.composeapp.generated.resources.that_is_not_a_relay_address -import bennu.composeapp.generated.resources.that_pubkey_is_already_a_suggester -import bennu.composeapp.generated.resources.that_relay_is_already_in_this_list -import bennu.composeapp.generated.resources.the_description_must_be_at_most_n_characters -import bennu.composeapp.generated.resources.the_group_signs_a_schema_so_it_takes_a_quorum -import bennu.composeapp.generated.resources.the_identifier_must_be_at_most_n_characters -import bennu.composeapp.generated.resources.the_identifier_names_this_list_in_every_reply -import bennu.composeapp.generated.resources.the_name_must_be_at_most_n_characters -import bennu.composeapp.generated.resources.the_picture_must_be_an_https_url -import bennu.composeapp.generated.resources.the_tag_s_third_element_which_tells_fields_sharing_a_tag_apart -import bennu.composeapp.generated.resources.the_title_must_be_at_most_n_characters -import bennu.composeapp.generated.resources.this_group_has_no_shared_key_to_sign_a_schema -import bennu.composeapp.generated.resources.title -import bennu.composeapp.generated.resources.type -import bennu.composeapp.generated.resources.visibility -import bennu.composeapp.generated.resources.visibility_closed -import bennu.composeapp.generated.resources.visibility_closed_purpose -import bennu.composeapp.generated.resources.visibility_private -import bennu.composeapp.generated.resources.visibility_private_purpose -import bennu.composeapp.generated.resources.visibility_public -import bennu.composeapp.generated.resources.visibility_public_purpose -import bennu.composeapp.generated.resources.what_an_entry_in_this_list_may_contain -import bennu.composeapp.generated.resources.where_suggestions_to_this_list_are_published -import bennu.composeapp.generated.resources.writes_to_tag -import org.jetbrains.compose.resources.StringResource -import org.jetbrains.compose.resources.stringResource - -/** - * The form for a list the group curates: what an entry may contain, who may - * suggest one, and where suggestions go. - * - * One screen for the whole schema, because the schema is one event and one - * signature. The identity -- identifier, title, name, description, visibility, - * picture, domain -- is text fields like every other editor's. Under it are the - * four things a schema has several of: fields, rules saying at least one of some - * fields must be present, extra suggesters on a closed list, and relays. Each - * is a list with a row per entry and a way to add one, and a field is edited on - * a sheet of its own, since a field has a dozen settings and thirteen of them - * inline would be a screen nobody could find anything on. - * - * **The button proposes rather than saves.** The schema goes out as one event - * for the room's quorum to put its key to, and the screen hands over to the - * signing session it opened. Nothing about the list has changed by the time this - * screen closes -- and until a quorum signs, suggesters have nothing to reply to. - * - * **An edit keeps the identifier.** The identifier is the coordinate every - * suggestion to the list replies to, so changing it would not edit the list but - * start a second one and orphan the first's queue. The field is read-only on an - * edit and says why; a new list is "Add schema" on the group's screen. - * - * **A new list starts from a template.** "Add schema" opens - * `SelectCuratedSchemaTemplateScreen` first, and the shape chosen there arrives - * as [template] -- the fields and rules the form is seeded with, in place of the - * bare two every list has. The form is the same either way: a template is a - * starting point, and everything in it can be changed before the group signs. - */ -@OptIn( - ExperimentalMaterial3ExpressiveApi::class, - ExperimentalMaterial3Api::class, - ExperimentalLayoutApi::class -) -@Composable -fun EditGroupCuratedSchemaScreen( - activeUserPublicKey: HexKey, - chatRoomId: String, - relayHint: String?, - identifier: String?, - /** The key of the `CuratedSchemaTemplate` a new schema starts from. Ignored on an edit. */ - template: String? = null, - initialEditGroupCuratedSchemaUIState: EditGroupCuratedSchemaUIState = - EditGroupCuratedSchemaUIState.Loading, - chatRepository: ChatRepository, - frostSigningRepository: FrostSigningRepository, - onNavigateToRouteAndPopUpInclusive: (Route) -> Unit, - onNavigateBack: () -> Unit, -) { - val editGroupCuratedSchemaViewModel: EditGroupCuratedSchemaViewModel = viewModel( - factory = EditGroupCuratedSchemaViewModel.factory( - chatRoomId = chatRoomId, - relayHint = relayHint, - identifier = identifier, - template = template, - initialEditGroupCuratedSchemaUIState = initialEditGroupCuratedSchemaUIState, - activeUserPublicKey = activeUserPublicKey, - chatRepository = chatRepository, - frostSigningRepository = frostSigningRepository - ) - ) - - // Read out here rather than in a click handler: both are composable and an - // onClick lambda is not. The scope is the caller's so a message survives this - // screen being replaced by the signing session. - val notify = rememberNotifier(rememberCoroutineScope()) - val couldNotPropose = stringResource(Res.string.could_not_ask_the_group_to_sign_this_schema) - val nothingChanged = stringResource(Res.string.nothing_has_changed_to_propose) - - ScreenStateTransition(editGroupCuratedSchemaViewModel.editGroupCuratedSchemaUIState) { uiState -> - when (val editGroupCuratedSchemaUIState = uiState) { - is EditGroupCuratedSchemaUIState.Error -> { - // Nothing to retry: the room and the identifier came from a - // navigation argument, and reading them again with the same ones - // fails the same way. - ErrorState(message = editGroupCuratedSchemaUIState.message, onRetry = null) - } - - is EditGroupCuratedSchemaUIState.Loaded -> { - val existing = editGroupCuratedSchemaUIState.existing - val schema = existing?.schema - val canSign = editGroupCuratedSchemaUIState.canSign - - // Seeded from the schema the group already signed, so the form is - // an edit of it. `rememberTextFieldState` saves what is typed, which - // is what survives a rotation with the edits intact. - val identifierFieldState = rememberTextFieldState(schema?.identifier ?: "") - val titleFieldState = rememberTextFieldState(schema?.title ?: "") - val nameFieldState = rememberTextFieldState(schema?.name ?: "") - val descriptionFieldState = rememberTextFieldState(schema?.description ?: "") - val pictureFieldState = rememberTextFieldState(schema?.picture ?: "") - val domainFieldState = rememberTextFieldState(schema?.domain ?: "") - val relayFieldState = rememberTextFieldState() - val suggesterFieldState = rememberTextFieldState() - - // The lists come from the state rather than from whatever loaded - // it, so a screen handed a loaded state -- a preview, a layout - // test -- fills in the same as the app does. Seeding runs once. - LaunchedEffect(editGroupCuratedSchemaUIState) { - editGroupCuratedSchemaViewModel.seedWorkingCopy(editGroupCuratedSchemaUIState) - } - - // A refusal is about what is in the field, so it goes the moment - // the field changes rather than sitting under a value that has - // since been corrected. - LaunchedEffect(relayFieldState) { - snapshotFlow { relayFieldState.text.toString() } - .collect { editGroupCuratedSchemaViewModel.clearAddRelayFailure() } - } - LaunchedEffect(suggesterFieldState) { - snapshotFlow { suggesterFieldState.text.toString() } - .collect { editGroupCuratedSchemaViewModel.clearAddSuggesterFailure() } - } - - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - modifier = Modifier.imePadding(), - topBar = { - TopAppBar( - title = { - editGroupCuratedSchemaUIState.localChatRoom.RenderChatRoomTitleText() - }, - navigationIcon = { NavigateBackButton(onNavigateBack) }, - ) - }, - bottomBar = { - BottomAppBar( - actions = {}, - floatingActionButton = { - ExtendedFab( - label = stringResource(Res.string.propose_schema), - icon = { Icon(Icons.Default.Draw, contentDescription = "Propose schema") }, - enabled = canSign, - onClick = { - editGroupCuratedSchemaViewModel.proposeSchema( - localChatRoom = - editGroupCuratedSchemaUIState.localChatRoom, - existing = existing, - identifier = identifierFieldState.text.toString(), - title = titleFieldState.text.toString(), - name = nameFieldState.text.toString(), - description = descriptionFieldState.text.toString(), - picture = pictureFieldState.text.toString(), - domain = domainFieldState.text.toString(), - onSuccess = { sessionId -> - // Onto the session rather than back - // to the group. The schema has not - // changed yet -- it changes when a - // quorum signs -- so landing on a - // group still showing the old one - // would read as a failure. - onNavigateToRouteAndPopUpInclusive.invoke( - FrostSigningRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - sessionId = sessionId - ) - ) - }, - // The reasons are drawn on the form - // itself, where the fields they are - // about are; a snackbar would name a - // problem and scroll away from it. - onInvalid = {}, - // Both stay on the form with the edits - // still in it. One is a question and - // one is a failure, and neither is a - // reason to throw away the typing. - onNothingToPropose = { notify(nothingChanged) }, - onFailure = { notify(couldNotPropose) } - ) - } - ) - } - ) - } - ) { innerPadding -> - // One lazy list for the whole form rather than a scrolling - // column, because the form has four lists in it and a lazy - // list cannot sit inside a scrolling column. The text fields - // are declared above so that scrolling one off the screen does - // not lose what was typed into it. - LazyColumn( - modifier = Modifier.padding(innerPadding).readableContent().fillMaxSize(), - contentPadding = PaddingValues( - horizontal = MaterialTheme.spacing.screenMargin, - vertical = MaterialTheme.spacing.itemGap - ), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), - horizontalAlignment = Alignment.CenterHorizontally - ) { - item { - Text( - text = stringResource(Res.string.what_an_entry_in_this_list_may_contain), - style = MaterialTheme.typography.titleSmall, - textAlign = TextAlign.Center - ) - } - - item { - Text( - text = stringResource( - Res.string.the_group_signs_a_schema_so_it_takes_a_quorum - ), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - textAlign = TextAlign.Center - ) - } - - if (!canSign) { - item { - Text( - text = stringResource( - Res.string.this_group_has_no_shared_key_to_sign_a_schema - ), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error, - textAlign = TextAlign.Center - ) - } - } - - // Named rather than silent, and all of them at once: a - // button that does nothing for a schema it refuses is - // indistinguishable from a missed tap, and one reason per - // press would be a conversation. - if (editGroupCuratedSchemaViewModel.problems.isNotEmpty()) { - item { - Column( - modifier = Modifier.fillMaxWidth(), - verticalArrangement = Arrangement.spacedBy( - MaterialTheme.spacing.relatedGap - ) - ) { - editGroupCuratedSchemaViewModel.problems.forEach { problem -> - Text( - text = problem.message(), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error - ) - } - } - } - } - - item { - SchemaTextField( - state = identifierFieldState, - icon = Icons.Default.Tag, - iconDescription = "Identifier of the list", - label = stringResource(Res.string.identifier), - placeholder = stringResource(Res.string.eg_bitcoin_mov), - // Locked on an edit: see the screen's own note. - readOnly = existing != null, - supportingText = if (existing != null) { - stringResource(Res.string.the_identifier_names_this_list_in_every_reply) - } else { - null - }, - isError = editGroupCuratedSchemaViewModel.problems.containsAny( - CuratedSchemaProblem.IdentifierMissing, - CuratedSchemaProblem.IdentifierTooLong - ) - ) - } - - item { - SchemaTextField( - state = titleFieldState, - icon = Icons.Default.Title, - iconDescription = "Title of the schema", - label = stringResource(Res.string.title), - placeholder = stringResource(Res.string.eg_bitcoin_mov_suggestion), - isError = editGroupCuratedSchemaViewModel.problems.containsAny( - CuratedSchemaProblem.TitleMissing, - CuratedSchemaProblem.TitleTooLong - ) - ) - } - - item { - SchemaTextField( - state = nameFieldState, - icon = Icons.AutoMirrored.Filled.Label, - iconDescription = "Name of the list", - label = stringResource(Res.string.name), - placeholder = stringResource(Res.string.eg_bitcoin_mov), - isError = editGroupCuratedSchemaViewModel.problems.containsAny( - CuratedSchemaProblem.NameMissing, - CuratedSchemaProblem.NameTooLong - ) - ) - } - - item { - SchemaTextField( - state = descriptionFieldState, - icon = Icons.AutoMirrored.Filled.Notes, - iconDescription = "What the list is for", - label = stringResource(Res.string.description), - placeholder = stringResource( - Res.string.eg_fields_for_a_bitcoin_mov_entry - ), - // The one identity field with prose in it, and the - // only one a single line would truncate while it - // was being typed. - lineLimits = TextFieldLineLimits.MultiLine(maxHeightInLines = 4), - isError = editGroupCuratedSchemaViewModel.problems.containsAny( - CuratedSchemaProblem.DescriptionMissing, - CuratedSchemaProblem.DescriptionTooLong - ) - ) - } - - item { - Column( - modifier = Modifier.fillMaxWidth(), - verticalArrangement = Arrangement.spacedBy( - MaterialTheme.spacing.relatedGap - ) - ) { - SectionHeading(stringResource(Res.string.visibility)) - - SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) { - CuratedVisibility.entries.forEachIndexed { index, option -> - SegmentedButton( - selected = option == editGroupCuratedSchemaViewModel.visibility, - onClick = { - editGroupCuratedSchemaViewModel.selectVisibility(option) - }, - shape = SegmentedButtonDefaults.itemShape( - index = index, - count = CuratedVisibility.entries.size - ), - label = { Text(stringResource(option.label())) } - ) - } - } - - // What the chosen word actually decides. Three - // words is three questions nobody can be expected - // to hold apart from the words alone. - Text( - text = stringResource( - editGroupCuratedSchemaViewModel.visibility.purpose() - ), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - } - } - - item { - SchemaTextField( - state = pictureFieldState, - icon = Icons.Default.Image, - iconDescription = "Picture of the list", - label = stringResource(Res.string.picture_url), - placeholder = stringResource(Res.string.eg_https_example_com_group_png), - isError = editGroupCuratedSchemaViewModel.problems.containsAny(CuratedSchemaProblem.PictureNotHttps) - ) - } - - item { - SchemaTextField( - state = domainFieldState, - icon = Icons.Default.Language, - iconDescription = "Domain of the list", - label = stringResource(Res.string.domain), - placeholder = stringResource(Res.string.eg_example_com), - supportingText = stringResource( - Res.string.a_domain_replaces_the_name_wherever_the_list_is_shown - ), - isError = editGroupCuratedSchemaViewModel.problems.containsAny(CuratedSchemaProblem.DomainInvalid) - ) - } - - item { - SectionHeading(stringResource(Res.string.fields)) - } - - itemsIndexed(editGroupCuratedSchemaViewModel.fields) { index, field -> - SchemaFieldRow( - field = field, - isMandatory = editGroupCuratedSchemaViewModel.isMandatory(field), - onOpen = { editGroupCuratedSchemaViewModel.startEditingField(index) } - ) - } - - item { - TextButton(onClick = { editGroupCuratedSchemaViewModel.startAddingField() }) { - Icon(Icons.Default.Add, contentDescription = Decorative) - - Spacer(modifier = Modifier.width(MaterialTheme.spacing.space125)) - - Text(stringResource(Res.string.add_field)) - } - } - - item { - Column( - modifier = Modifier.fillMaxWidth(), - verticalArrangement = Arrangement.spacedBy( - MaterialTheme.spacing.relatedGap - ) - ) { - SectionHeading(stringResource(Res.string.at_least_one_of)) - - Text( - text = stringResource( - Res.string.pick_two_or_more_fields_at_least_one_of_which_an_entry_must_have - ), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - } - } - - itemsIndexed(editGroupCuratedSchemaViewModel.requireAny) { index, group -> - RequireAnyRow( - fieldNames = editGroupCuratedSchemaViewModel.fields.map { it.name }, - selected = group, - onToggle = { fieldName -> - editGroupCuratedSchemaViewModel.toggleRequireAny(index, fieldName) - }, - onRemove = { editGroupCuratedSchemaViewModel.removeRequireAnyGroup(index) } - ) - } - - item { - TextButton( - onClick = { editGroupCuratedSchemaViewModel.addRequireAnyGroup() } - ) { - Icon(Icons.AutoMirrored.Filled.Rule, contentDescription = Decorative) - - Spacer(modifier = Modifier.width(MaterialTheme.spacing.space125)) - - Text(stringResource(Res.string.add_rule)) - } - } - - // Only where the visibility gives them something to be: on - // a public list anyone may suggest, and a list of people - // who may would say the opposite of what the word does. - if (editGroupCuratedSchemaViewModel.visibility != CuratedVisibility.Public) { - item { - Column( - modifier = Modifier.fillMaxWidth(), - verticalArrangement = Arrangement.spacedBy( - MaterialTheme.spacing.relatedGap - ) - ) { - SectionHeading(stringResource(Res.string.suggesters)) - - Text( - text = stringResource( - Res.string.pubkeys_besides_the_group_that_may_suggest_to_this_list - ), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - } - } - - items(editGroupCuratedSchemaViewModel.suggesters) { pubkey -> - RemovableRow( - // The npub, because that is the form a member - // pasted it in and the form they would compare - // it against; whole and monospaced, so it can be. - text = pubkey.hexToNpubHrp(), - isMonospaced = true, - removeDescription = "Remove suggester", - onRemove = { editGroupCuratedSchemaViewModel.removeSuggester(pubkey) } - ) - } - - item { - AddRow( - state = suggesterFieldState, - icon = Icons.Default.PersonAdd, - label = stringResource(Res.string.npub_or_hex_pubkey), - placeholder = null, - addDescription = "Add suggester", - failure = when (editGroupCuratedSchemaViewModel.addSuggesterFailure) { - AddSuggesterFailure.NotAPubkey -> - stringResource(Res.string.that_is_not_a_pubkey) - AddSuggesterFailure.AlreadyListed -> - stringResource(Res.string.that_pubkey_is_already_a_suggester) - null -> null - }, - onAdd = { input -> editGroupCuratedSchemaViewModel.addSuggester(input) } - ) - } - } - - item { - Column( - modifier = Modifier.fillMaxWidth(), - verticalArrangement = Arrangement.spacedBy( - MaterialTheme.spacing.relatedGap - ) - ) { - SectionHeading(stringResource(Res.string.relays)) - - Text( - text = stringResource( - Res.string.where_suggestions_to_this_list_are_published - ), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - - if (editGroupCuratedSchemaViewModel.relays.isEmpty()) { - Text( - text = stringResource( - Res.string.no_relays_named_so_a_client_will_pick_its_own - ), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error - ) - } - } - } - - items(editGroupCuratedSchemaViewModel.relays) { url -> - RemovableRow( - text = url, - isMonospaced = false, - removeDescription = "Remove relay", - onRemove = { editGroupCuratedSchemaViewModel.removeRelay(url) } - ) - } - - item { - AddRow( - state = relayFieldState, - icon = Icons.Default.Dns, - label = stringResource(Res.string.relay_url), - placeholder = stringResource(Res.string.eg_wss_relay_example_com), - addDescription = "Add relay", - failure = when (editGroupCuratedSchemaViewModel.addRelayFailure) { - AddRelayFailure.NotARelay -> - stringResource(Res.string.that_is_not_a_relay_address) - AddRelayFailure.AlreadyListed -> - stringResource(Res.string.that_relay_is_already_in_this_list) - null -> null - }, - onAdd = { input -> editGroupCuratedSchemaViewModel.addRelay(input) } - ) - } - } - } - - editGroupCuratedSchemaViewModel.editingField?.let { edit -> - FieldEditorSheet( - edit = edit, - isMandatory = editGroupCuratedSchemaViewModel.isMandatory(edit.field), - onCommit = { field -> editGroupCuratedSchemaViewModel.commitField(field) }, - onRemove = { edit.index?.let(editGroupCuratedSchemaViewModel::removeField) }, - onDismiss = { editGroupCuratedSchemaViewModel.dismissFieldEditor() } - ) - } - } - - EditGroupCuratedSchemaUIState.Loading -> { - Column( - modifier = Modifier.fillMaxWidth().padding(MaterialTheme.spacing.screenMargin), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.sectionGap) - ) { - Spacer(modifier = Modifier.height(MaterialTheme.spacing.emphasisGap)) - - Text( - text = stringResource( - if (identifier == null) Res.string.add_schema else Res.string.edit_schema - ), - style = MaterialTheme.typography.bodyLarge, - textAlign = TextAlign.Center - ) - - LoadingDataIndicator(fillScreen = false) - } - } - } - } - - LaunchedEffect(true) { - if (initialEditGroupCuratedSchemaUIState == EditGroupCuratedSchemaUIState.Loading) { - editGroupCuratedSchemaViewModel.initiateEditGroupCuratedSchema() - } - } -} - -/** The word for who may suggest, for the group's screen and the editor alike. */ -internal fun CuratedVisibility.label(): StringResource = when (this) { - CuratedVisibility.Public -> Res.string.visibility_public - CuratedVisibility.Closed -> Res.string.visibility_closed - CuratedVisibility.Private -> Res.string.visibility_private -} - -/** The sentence saying what the word decides. */ -private fun CuratedVisibility.purpose(): StringResource = when (this) { - CuratedVisibility.Public -> Res.string.visibility_public_purpose - CuratedVisibility.Closed -> Res.string.visibility_closed_purpose - CuratedVisibility.Private -> Res.string.visibility_private_purpose -} - -/** - * The name of a field type, for the chips and the rows. - * - * A `when` rather than a field on each entry so that the enum stays what it is - * -- the NIP's ten words and their one rule each -- with no catalogue behind - * it, and so that an eleventh type is a compile error here rather than a chip - * with no name. - */ -private fun CuratedFieldType.label(): StringResource = when (this) { - CuratedFieldType.Text -> Res.string.field_type_text - CuratedFieldType.LongText -> Res.string.field_type_longtext - CuratedFieldType.Token -> Res.string.field_type_token - CuratedFieldType.Url -> Res.string.field_type_url - CuratedFieldType.Image -> Res.string.field_type_image - CuratedFieldType.Enum -> Res.string.field_type_enum - CuratedFieldType.Year -> Res.string.field_type_year - CuratedFieldType.Duration -> Res.string.field_type_duration - CuratedFieldType.Number -> Res.string.field_type_number - CuratedFieldType.Date -> Res.string.field_type_date -} - -/** - * Why a schema cannot be proposed, said to the member. - * - * The caps are quoted from `CuratedSchemaEvent` rather than repeated, so the - * sentence and the check cannot disagree about the number. - */ -@Composable -internal fun CuratedSchemaProblem.message(): String = when (this) { - CuratedSchemaProblem.IdentifierMissing -> stringResource(Res.string.an_identifier_is_required) - CuratedSchemaProblem.IdentifierTooLong -> stringResource( - Res.string.the_identifier_must_be_at_most_n_characters, - CuratedSchemaEvent.MAX_IDENTIFIER.toString() - ) - CuratedSchemaProblem.TitleMissing -> stringResource(Res.string.a_title_is_required) - CuratedSchemaProblem.TitleTooLong -> stringResource( - Res.string.the_title_must_be_at_most_n_characters, - CuratedSchemaEvent.MAX_TITLE.toString() - ) - CuratedSchemaProblem.NameMissing -> stringResource(Res.string.a_name_is_required) - CuratedSchemaProblem.NameTooLong -> stringResource( - Res.string.the_name_must_be_at_most_n_characters, - CuratedSchemaEvent.MAX_NAME.toString() - ) - CuratedSchemaProblem.DescriptionMissing -> stringResource(Res.string.a_description_is_required) - CuratedSchemaProblem.DescriptionTooLong -> stringResource( - Res.string.the_description_must_be_at_most_n_characters, - CuratedSchemaEvent.MAX_DESCRIPTION.toString() - ) - CuratedSchemaProblem.VisibilityMissing -> stringResource(Res.string.say_who_may_suggest_to_this_list) - CuratedSchemaProblem.PictureNotHttps -> stringResource(Res.string.the_picture_must_be_an_https_url) - CuratedSchemaProblem.DomainInvalid -> stringResource(Res.string.that_is_not_a_domain_name) - CuratedSchemaProblem.NoFields -> stringResource(Res.string.a_schema_needs_at_least_one_field) - CuratedSchemaProblem.RelayInvalid -> stringResource(Res.string.one_of_the_relays_is_not_a_relay_address) -} - -/** Whether any of [problems] is about the field asking, for its error state. */ -private fun List.containsAny(vararg problems: CuratedSchemaProblem): Boolean = - problems.any { it in this } - -/** A heading over one part of the form, at the leading edge like the rows under it. */ -@Composable -private fun SectionHeading(text: String) { - Text( - modifier = Modifier.fillMaxWidth(), - text = text, - style = MaterialTheme.typography.titleSmall - ) -} - -/** - * One text field of the form, in the shape the app's other forms use. - * - * The borderless outlined field over the bottom bar's tint is four lines of - * colours apiece, and this screen has more of them than any other -- so the - * function, and the three things this one adds over `NostrProfileField`: a - * read-only state for the locked identifier, an error state for a field a - * problem is about, and a line of supporting text for a field that needs one. - */ -@Composable -private fun SchemaTextField( - state: TextFieldState, - icon: ImageVector, - iconDescription: String, - label: String, - placeholder: String, - lineLimits: TextFieldLineLimits = TextFieldLineLimits.SingleLine, - readOnly: Boolean = false, - isError: Boolean = false, - supportingText: String? = null -) { - OutlinedTextField( - modifier = Modifier.fillMaxWidth().background(BottomAppBarDefaults.containerColor), - state = state, - lineLimits = lineLimits, - readOnly = readOnly, - isError = isError, - colors = OutlinedTextFieldDefaults.colors( - focusedBorderColor = Color.Transparent, - unfocusedBorderColor = Color.Transparent, - disabledBorderColor = Color.Transparent - ), - leadingIcon = { - Icon(icon, contentDescription = iconDescription) - }, - label = { - Text(text = label) - }, - placeholder = { - Text(text = placeholder) - }, - supportingText = supportingText?.let { { Text(text = it) } } - ) -} - -/** - * One field of the schema, as a row that opens the sheet. - * - * The label is what a suggester will see over the input, so it is the headline; - * the name, type and requirement are what the schema says about it. A - * mandatory field is marked as required whatever its own flag says, since that - * is what will be signed. - */ -@Composable -private fun SchemaFieldRow( - field: CuratedField, - isMandatory: Boolean, - onOpen: () -> Unit -) { - Card(modifier = Modifier.fillMaxWidth(), onClick = onOpen) { - ListItem( - leadingContent = { - Icon(Icons.Default.Ballot, contentDescription = Decorative) - }, - headlineContent = { - Text( - text = field.labelOrName(), - maxLines = 1, - overflow = TextOverflow.Ellipsis - ) - }, - supportingContent = { - Text( - text = listOfNotNull( - field.name, - stringResource(field.type.label()), - stringResource( - if (field.isRequired || isMandatory) Res.string.required else Res.string.optional - ), - stringResource(Res.string.derived).takeIf { field.config.derived == true } - ).joinToString(" · "), - maxLines = 2, - overflow = TextOverflow.Ellipsis - ) - } - ) - } -} - -/** - * One `require-any` rule: a chip per field, selected for the ones in the rule. - * - * Chips over a picker because the whole point of a rule is which fields are in - * it, and a chip row shows that at a glance where a picker would show a count. - */ -@OptIn(ExperimentalLayoutApi::class) -@Composable -private fun RequireAnyRow( - fieldNames: List, - selected: List, - onToggle: (String) -> Unit, - onRemove: () -> Unit -) { - Card(modifier = Modifier.fillMaxWidth()) { - Row( - modifier = Modifier.fillMaxWidth().padding(MaterialTheme.spacing.compactPadding), - verticalAlignment = Alignment.CenterVertically - ) { - FlowRow( - modifier = Modifier.weight(1f), - horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap) - ) { - fieldNames.forEach { fieldName -> - FilterChip( - selected = fieldName in selected, - onClick = { onToggle(fieldName) }, - label = { Text(fieldName) } - ) - } - } - - IconButton(onClick = onRemove) { - Icon( - Icons.Default.Delete, - contentDescription = "Remove rule", - tint = MaterialTheme.colorScheme.error - ) - } - } - } -} - -/** One entry of a plain list -- a relay, a suggester -- with the way to drop it. */ -@Composable -private fun RemovableRow( - text: String, - isMonospaced: Boolean, - removeDescription: String, - onRemove: () -> Unit -) { - Row( - modifier = Modifier.fillMaxWidth(), - verticalAlignment = Alignment.CenterVertically - ) { - Text( - modifier = Modifier.weight(1f), - text = text, - style = MaterialTheme.typography.bodyMedium, - fontFamily = if (isMonospaced) FontFamily.Monospace else null - ) - - IconButton(onClick = onRemove) { - Icon( - Icons.Default.Delete, - contentDescription = removeDescription, - tint = MaterialTheme.colorScheme.error - ) - } - } -} - -/** - * A field and a button that adds what is in it to a list, and the reason when - * it would not. - * - * [onAdd] answers whether the row appeared, which is the cue to clear the field - * -- a refused value stays where it can be corrected. - */ -@Composable -private fun AddRow( - state: TextFieldState, - icon: ImageVector, - label: String, - placeholder: String?, - addDescription: String, - failure: String?, - onAdd: (String) -> Boolean -) { - Column( - modifier = Modifier.fillMaxWidth(), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap) - ) { - Row( - modifier = Modifier.fillMaxWidth(), - verticalAlignment = Alignment.CenterVertically - ) { - OutlinedTextField( - modifier = Modifier.weight(1f).background(BottomAppBarDefaults.containerColor), - state = state, - lineLimits = TextFieldLineLimits.SingleLine, - colors = OutlinedTextFieldDefaults.colors( - focusedBorderColor = Color.Transparent, - unfocusedBorderColor = Color.Transparent, - disabledBorderColor = Color.Transparent - ), - leadingIcon = { - Icon(icon, contentDescription = Decorative) - }, - label = { Text(label) }, - placeholder = placeholder?.let { { Text(it) } }, - isError = failure != null - ) - - Spacer(modifier = Modifier.width(MaterialTheme.spacing.itemGap)) - - IconButton( - onClick = { - if (onAdd(state.text.toString())) { - state.clearText() - } - } - ) { - Icon(Icons.Default.Add, contentDescription = addDescription) - } - } - - failure?.let { - Text( - text = it, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error - ) - } - } -} - -/** - * The sheet a field is edited on. - * - * Split into the sheet and its content the way `GroupKeyStateSheet` is, so the - * content can be rendered and measured on its own -- a bottom sheet is a popup - * with its own window, which a layout test cannot reach into. - */ -@Composable -private fun FieldEditorSheet( - edit: FieldEdit, - isMandatory: Boolean, - onCommit: (CuratedField) -> FieldProblem?, - onRemove: () -> Unit, - onDismiss: () -> Unit -) { - ModalBottomSheet(onDismiss = onDismiss, skipPartiallyExpanded = true) { - FieldEditorSheetContent( - edit = edit, - isMandatory = isMandatory, - onCommit = onCommit, - onRemove = onRemove - ) - } -} - -/** - * Everything a field can say about itself, and a button that puts it in the - * schema. - * - * The positional parts of the tag first -- name, label, placeholder, type, - * required -- because they are what a form needs; the config keys after, and - * only the ones the chosen type gives a meaning to. A minimum on a text field or - * options on a year would be written into the event and mean nothing, so they - * are not offered and, when the type changes away from them, not kept. - * - * **A mandatory field cannot stop being one.** Its tag is read-only and its - * requirement is on and disabled, because `CuratedSchema.normalized` would only - * put a field writing to `d` or `title` back if this let it be taken away -- so - * offering the change would offer something the event will not carry. - */ -@OptIn(ExperimentalLayoutApi::class) -@Composable -internal fun FieldEditorSheetContent( - edit: FieldEdit, - isMandatory: Boolean, - onCommit: (CuratedField) -> FieldProblem?, - onRemove: () -> Unit -) { - val field = edit.field - - val nameFieldState = rememberTextFieldState(field.name) - val labelFieldState = rememberTextFieldState(field.label) - val placeholderFieldState = rememberTextFieldState(field.placeholder) - val tagFieldState = rememberTextFieldState(field.config.tag ?: "") - val markerFieldState = rememberTextFieldState(field.config.marker ?: "") - val maxFieldState = rememberTextFieldState(field.config.max?.toString() ?: "") - val minFieldState = rememberTextFieldState(field.config.min?.toString() ?: "") - val optionsFieldState = rememberTextFieldState(field.config.options?.joinToString("\n") ?: "") - val patternFieldState = rememberTextFieldState(field.config.pattern ?: "") - val hintFieldState = rememberTextFieldState(field.config.hint ?: "") - - var type by rememberSaveable { mutableStateOf(field.type) } - var isRequired by rememberSaveable { mutableStateOf(field.isRequired || isMandatory) } - var mayRepeat by rememberSaveable { mutableStateOf(field.config.repeat == true) } - var isHttpsOnly by rememberSaveable { mutableStateOf(field.config.https == true) } - var isDerived by rememberSaveable { mutableStateOf(field.config.derived == true) } - - var problem: FieldProblem? by remember { mutableStateOf(null) } - - Column( - modifier = Modifier.fillMaxWidth(), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap) - ) { - Text( - text = stringResource( - if (edit.index == null) Res.string.new_field else Res.string.edit_field - ), - style = MaterialTheme.typography.titleMedium - ) - - SchemaTextField( - state = nameFieldState, - icon = Icons.Default.Tag, - iconDescription = "Name of the field", - label = stringResource(Res.string.field_name), - placeholder = stringResource(Res.string.eg_watchurl), - isError = problem != null - ) - - // Named rather than silent, under the field it is about. - problem?.let { - Text( - text = when (it) { - FieldProblem.NameMissing -> stringResource(Res.string.a_field_needs_a_name) - FieldProblem.NameHasSpaces -> stringResource(Res.string.a_field_name_is_one_word) - FieldProblem.NameTaken -> stringResource(Res.string.a_field_named_that_already_exists) - }, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error - ) - } - - SchemaTextField( - state = labelFieldState, - icon = Icons.AutoMirrored.Filled.Label, - iconDescription = "Label over the input", - label = stringResource(Res.string.label), - placeholder = stringResource(Res.string.eg_watch_reference_url) - ) - - SchemaTextField( - state = placeholderFieldState, - icon = Icons.AutoMirrored.Filled.ShortText, - iconDescription = "Example shown in an empty input", - label = stringResource(Res.string.placeholder), - placeholder = stringResource(Res.string.eg_https_youtube_com_watch) - ) - - Text( - text = stringResource(Res.string.type), - style = MaterialTheme.typography.labelMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - - FlowRow( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap) - ) { - CuratedFieldType.entries.forEach { option -> - FilterChip( - selected = option == type, - onClick = { type = option }, - label = { Text(stringResource(option.label())) } - ) - } - } - - SwitchRow( - label = stringResource(Res.string.an_entry_must_have_this_field), - checked = isRequired, - enabled = !isMandatory, - onCheckedChange = { isRequired = it } - ) - - SchemaTextField( - state = tagFieldState, - icon = Icons.Default.Sell, - iconDescription = "Tag the field writes to", - label = stringResource(Res.string.writes_to_tag), - placeholder = nameFieldState.text.toString().ifBlank { stringResource(Res.string.eg_watchurl) }, - readOnly = isMandatory, - supportingText = stringResource( - Res.string.defaults_to_the_field_name_content_means_the_body - ) - ) - - SchemaTextField( - state = markerFieldState, - icon = Icons.Default.Bookmark, - iconDescription = "Marker on the tag", - label = stringResource(Res.string.marker), - placeholder = stringResource(Res.string.eg_watch), - supportingText = stringResource( - Res.string.the_tag_s_third_element_which_tells_fields_sharing_a_tag_apart - ) - ) - - // What `max` means follows the type: a cap on the characters, a bound - // on the number, or the latest year of a date. `min` only exists for - // the last two. - SchemaTextField( - state = maxFieldState, - icon = Icons.Default.Numbers, - iconDescription = "Maximum", - label = stringResource( - when { - type.isNumeric -> Res.string.maximum_value - type.isBounded -> Res.string.latest_year - else -> Res.string.maximum_characters - } - ), - placeholder = stringResource(if (type.isBounded) Res.string.eg_2100 else Res.string.eg_200) - ) - - if (type.isBounded) { - SchemaTextField( - state = minFieldState, - icon = Icons.Default.Numbers, - iconDescription = "Minimum", - label = stringResource(if (type.isNumeric) Res.string.minimum_value else Res.string.earliest_year), - placeholder = stringResource(Res.string.eg_1900) - ) - } - - if (type == CuratedFieldType.Enum) { - SchemaTextField( - state = optionsFieldState, - icon = Icons.Default.Checklist, - iconDescription = "Allowed values", - label = stringResource(Res.string.options), - placeholder = stringResource(Res.string.eg_movie_documentary_short), - lineLimits = TextFieldLineLimits.MultiLine(maxHeightInLines = 6), - supportingText = stringResource(Res.string.one_per_line_or_separated_by_commas) - ) - } - - if (type == CuratedFieldType.Url) { - SwitchRow( - label = stringResource(Res.string.https_only), - checked = isHttpsOnly, - enabled = true, - onCheckedChange = { isHttpsOnly = it } - ) - } - - SwitchRow( - label = stringResource(Res.string.may_appear_more_than_once), - checked = mayRepeat, - enabled = true, - onCheckedChange = { mayRepeat = it } - ) - - SchemaTextField( - state = patternFieldState, - icon = Icons.AutoMirrored.Filled.Rule, - iconDescription = "Pattern the value must match", - label = stringResource(Res.string.pattern), - placeholder = stringResource(Res.string.eg_a_za_z_2_8), - supportingText = stringResource( - Res.string.a_regular_expression_the_whole_value_must_match - ) - ) - - SwitchRow( - label = stringResource(Res.string.filled_in_by_the_app_never_asked_for), - checked = isDerived, - enabled = true, - onCheckedChange = { isDerived = it } - ) - - SchemaTextField( - state = hintFieldState, - icon = Icons.Default.Lightbulb, - iconDescription = "Helper text", - label = stringResource(Res.string.hint), - placeholder = stringResource(Res.string.helper_text_under_the_input) - ) - - Row( - modifier = Modifier.fillMaxWidth(), - verticalAlignment = Alignment.CenterVertically - ) { - if (!isMandatory && edit.index != null) { - TextButton( - onClick = onRemove, - colors = ButtonDefaults.textButtonColors( - contentColor = MaterialTheme.colorScheme.error - ) - ) { - Text(stringResource(Res.string.remove_field)) - } - } - - Spacer(modifier = Modifier.weight(1f)) - - Button( - onClick = { - problem = onCommit( - CuratedField( - name = nameFieldState.text.toString().trim(), - type = type, - isRequired = isRequired || isMandatory, - placeholder = placeholderFieldState.text.toString().trim(), - label = labelFieldState.text.toString().trim(), - config = field.config.copy( - // Pinned for a mandatory field, so that renaming it - // cannot move it off the tag that makes it one. - tag = if (isMandatory) { - field.tag() - } else { - tagFieldState.text.toString().trim().ifEmpty { null } - }, - marker = markerFieldState.text.toString().trim().ifEmpty { null }, - max = maxFieldState.text.toString().trim().toLongOrNull(), - min = if (type.isBounded) { - minFieldState.text.toString().trim().toLongOrNull() - } else { - null - }, - options = if (type == CuratedFieldType.Enum) { - optionsFieldState.text.toString() - .split('\n', ',') - .map { it.trim() } - .filter { it.isNotEmpty() } - .ifEmpty { null } - } else { - null - }, - https = if (type == CuratedFieldType.Url && isHttpsOnly) true else null, - repeat = if (mayRepeat) true else null, - pattern = patternFieldState.text.toString().trim().ifEmpty { null }, - derived = if (isDerived) true else null, - hint = hintFieldState.text.toString().trim().ifEmpty { null }, - ) - ) - ) - } - ) { - Text(stringResource(Res.string.done)) - } - } - } -} - -/** - * A labelled switch, the label taking the width and the switch its own target. - * - * The label is also the switch's description, so a screen reader announces what - * is being turned on rather than "switch, off" beside a sentence it has already - * read past. - */ -@Composable -private fun SwitchRow( - label: String, - checked: Boolean, - enabled: Boolean, - onCheckedChange: (Boolean) -> Unit -) { - Row( - modifier = Modifier.fillMaxWidth(), - verticalAlignment = Alignment.CenterVertically - ) { - Text( - modifier = Modifier.weight(1f), - text = label, - style = MaterialTheme.typography.bodyMedium - ) - - Switch( - modifier = Modifier.semantics { contentDescription = label }, - checked = checked, - enabled = enabled, - onCheckedChange = onCheckedChange - ) - } -} - -@ConformancePreviews -@Composable -private fun EditGroupCuratedSchemaScreenPreview() { - BennuTheme { - Surface(modifier = Modifier.fillMaxSize()) { - EditGroupCuratedSchemaScreen( - activeUserPublicKey = "", - chatRoomId = "publicKey", - relayHint = null, - identifier = null, - // The shape a new list most often starts from, so the preview - // shows a templated form rather than the bare two fields. - template = CuratedSchemaTemplate.Links.key, - initialEditGroupCuratedSchemaUIState = EditGroupCuratedSchemaUIState.Loaded( - localChatRoom = LocalChatRoom( - chatRoom = ChatRoom( - id = "publicKey", - userPublicKey = "", - subject = "Translation room", - description = "A group translating hard books.", - initialGiftWrapPayloadId = "sdfaer", - mlsGroupState = "state" - ), - ), - // A new schema, so the editor seeds the template's fields and - // the preview shows what a group actually starts from rather - // than an empty form. - defaultRelays = listOf("wss://relay.example.com"), - // A group that can sign, so the form renders in the state a - // member actually meets it in rather than greyed out. - canSign = true - ), - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, - onNavigateToRouteAndPopUpInclusive = {}, - onNavigateBack = {}, - ) - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupCuratedEntriesScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupCuratedEntriesScreen.kt deleted file mode 100644 index fa125470..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupCuratedEntriesScreen.kt +++ /dev/null @@ -1,544 +0,0 @@ -package com.machankura.bennu.compose.ui.composable - -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.CellTower -import androidx.compose.material.icons.filled.CheckCircle -import androidx.compose.material3.BottomAppBar -import androidx.compose.material3.Card -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.Icon -import androidx.compose.material3.ListItem -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Scaffold -import androidx.compose.material3.SnackbarHost -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.text.style.TextOverflow -import androidx.lifecycle.viewmodel.compose.viewModel -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.displayUrl -import bennu.composeapp.generated.resources.Res -import bennu.composeapp.generated.resources.accepted_by_every_relay_for_n_of_m_entries -import bennu.composeapp.generated.resources.accepted_by_n_of_m_relays -import bennu.composeapp.generated.resources.broadcast_all -import bennu.composeapp.generated.resources.curated_entries -import bennu.composeapp.generated.resources.in_list -import bennu.composeapp.generated.resources.no_relays_to_send_it_to -import bennu.composeapp.generated.resources.relay_and_answer -import bennu.composeapp.generated.resources.relay_sending -import bennu.composeapp.generated.resources.sending_entry_n_of_m -import bennu.composeapp.generated.resources.signed_by_the_group_on -import bennu.composeapp.generated.resources.suggested_by -import bennu.composeapp.generated.resources.this_group_has_not_accepted_anything_into_a_list_yet -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.emptyFlow -import org.jetbrains.compose.resources.stringResource -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.machankura.bennu.compose.database.model.NostrEvent -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.extensions.shortened -import com.machankura.bennu.compose.extensions.toFormattedTimeAndDateString -import com.machankura.bennu.compose.network.dto.RelayDTO -import com.machankura.bennu.compose.network.relays.EventPublishTransport -import com.machankura.bennu.compose.network.relays.NostrPublishResult -import com.machankura.bennu.compose.nostr.GroupCuratedEntry -import com.machankura.bennu.compose.nostr.GroupCuratedSchema -import com.machankura.bennu.compose.nostr.curated.CuratedEntry -import com.machankura.bennu.compose.nostr.curated.CuratedEntryEvent -import com.machankura.bennu.compose.nostr.curated.CuratedField -import com.machankura.bennu.compose.nostr.curated.CuratedSchema -import com.machankura.bennu.compose.nostr.curated.CuratedSchemaEvent -import com.machankura.bennu.compose.nostr.curated.CuratedVisibility -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.ui.composable.navigation.routes.BroadcastGroupSignedEventRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.widgets.Decorative -import com.machankura.bennu.compose.ui.composable.widgets.EmptyState -import com.machankura.bennu.compose.ui.composable.widgets.ErrorState -import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator -import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState -import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton -import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition -import com.machankura.bennu.compose.ui.composable.widgets.buttons.BroadcastButton -import com.machankura.bennu.compose.ui.composable.widgets.buttons.ExtendedFab -import com.machankura.bennu.compose.ui.composable.widgets.label -import com.machankura.bennu.compose.ui.theme.ConformancePreviews -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.theme.readableContent -import com.machankura.bennu.compose.ui.theme.spacing -import com.machankura.bennu.compose.ui.view.model.GroupCuratedEntriesViewModel -import com.machankura.bennu.compose.ui.view.model.GroupCuratedEntriesViewModel.BroadcastAllProgress -import com.machankura.bennu.compose.ui.view.model.GroupCuratedEntriesViewModel.EntryBroadcast -import com.machankura.bennu.compose.ui.view.state.GroupCuratedEntriesUIState -import kotlin.time.Instant - -/** - * The entries the group has accepted into the lists it curates, newest first. - * - * Pushed from its row on the group's screen, which counts the entries and - * nothing more. This is where they are read: one card per entry with a - * broadcast under it, and one button at the bottom that broadcasts all of - * them. No gate on any of it, because reading what the group decided takes - * no share of the key, and neither does repeating its signature to a relay. - * - * The two broadcasts differ in what the member sees first. The button under - * a card opens `BroadcastGroupSignedEventScreen`, where the relays are shown - * and can be changed before the send; the one at the bottom sends every - * entry straight to where that screen would have started, one after another, - * and says under each card what its relays answered. See - * `GroupCuratedEntriesViewModel.broadcastAll` for why one at a time. - * - * There is no way in to add one here, because an entry is accepted from the - * queue it was suggested to, which is reached from its schema's card on the - * `GroupCuratedSchemasScreen`. The empty state says as much. - */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun GroupCuratedEntriesScreen( - activeUserPublicKey: HexKey, - chatRoomId: String, - relayHint: String?, - initialGroupCuratedEntriesUIState: GroupCuratedEntriesUIState = - GroupCuratedEntriesUIState.Loading, - chatRepository: ChatRepository, - publishTransport: EventPublishTransport, - onNavigateToRoute: (Route) -> Unit, - onNavigateBack: () -> Unit, -) { - val groupCuratedEntriesViewModel: GroupCuratedEntriesViewModel = viewModel( - factory = GroupCuratedEntriesViewModel.factory( - chatRoomId = chatRoomId, - initialGroupCuratedEntriesUIState = initialGroupCuratedEntriesUIState, - chatRepository = chatRepository, - publishTransport = publishTransport, - ) - ) - - LaunchedEffect(true) { - if (initialGroupCuratedEntriesUIState == GroupCuratedEntriesUIState.Loading) { - groupCuratedEntriesViewModel.initiate() - } - } - - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - topBar = { - TopAppBar( - title = { - Text( - text = stringResource(Res.string.curated_entries), - maxLines = 1, - overflow = TextOverflow.Ellipsis - ) - }, - navigationIcon = { NavigateBackButton(onNavigateBack) } - ) - }, - bottomBar = { - // Only over a list with something in it. The empty state already - // says why there is nothing to send, and a button that sends - // nothing under it would say the opposite. - val loaded = groupCuratedEntriesViewModel.groupCuratedEntriesUIState - as? GroupCuratedEntriesUIState.Loaded - - if (loaded != null && loaded.groupCuratedEntries.isNotEmpty()) { - val canSend = !groupCuratedEntriesViewModel.isActionPending.value - - BottomAppBar( - actions = {}, - floatingActionButton = { - ExtendedFab( - label = stringResource(Res.string.broadcast_all), - icon = { Icon(Icons.Default.CellTower, contentDescription = Decorative) }, - enabled = canSend, - onClick = { - groupCuratedEntriesViewModel.broadcastAll() - } - ) - } - ) - } - } - ) { padding -> - ScreenStateTransition(groupCuratedEntriesViewModel.groupCuratedEntriesUIState) { uiState -> - when (val state = uiState) { - is GroupCuratedEntriesUIState.Error -> { - // Nothing to retry: the room came from a navigation argument, - // and reading it again with the same one fails the same way. - ErrorState( - modifier = Modifier.padding(padding), - message = state.message, - onRetry = null - ) - } - - GroupCuratedEntriesUIState.Loading -> { - Column( - modifier = Modifier.fillMaxWidth().padding(padding) - .padding(MaterialTheme.spacing.screenMargin), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.sectionGap) - ) { - Spacer(modifier = Modifier.height(MaterialTheme.spacing.emphasisGap)) - - LoadingDataIndicator(fillScreen = false) - } - } - - is GroupCuratedEntriesUIState.Loaded -> { - LazyColumn( - modifier = Modifier.padding(padding).readableContent().fillMaxSize() - .padding(MaterialTheme.spacing.space250), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space125) - ) { - if (state.groupCuratedEntries.isEmpty()) { - item { - EmptyState( - message = stringResource( - Res.string.this_group_has_not_accepted_anything_into_a_list_yet - ) - ) - } - } else { - // The last press of "Broadcast all", summed up, above - // the cards that break it down. Persistent rather than - // a snackbar, because it is the answer the member came - // for and a snackbar would be gone before the last - // card had been read. - groupCuratedEntriesViewModel.broadcastAllProgress?.let { progress -> - item(key = "broadcast-all-progress") { - BroadcastAllProgressLine(progress = progress) - } - } - - items( - items = state.groupCuratedEntries, - key = { accepted -> accepted.signedEvent.id } - ) { accepted -> - // The card, what its relays answered, and its - // broadcast as one item, so all three stay under - // the entry they are about however the list is - // arranged. The answer sits above the button - // because the button is what a refusal calls for: - // it opens the screen where the relay can be - // changed and the send tried again. - Column( - modifier = Modifier.fillMaxWidth(), - horizontalAlignment = Alignment.CenterHorizontally - ) { - GroupCuratedEntryCard(accepted = accepted) - - groupCuratedEntriesViewModel.entryBroadcasts[accepted.signedEvent.id] - ?.let { EntryBroadcastLines(broadcast = it) } - - BroadcastButton( - onClick = { - onNavigateToRoute.invoke( - BroadcastGroupSignedEventRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint, - signedEventId = accepted.signedEvent.id - ) - ) - } - ) - } - } - } - } - } - } - } - } -} - -/** - * Where "Broadcast all" has got to: which entry is out while the batch runs, - * and how many were accepted everywhere once it is done -- in the primary - * colour when that is all of them, and the error colour when the cards below - * have a refusal to show. - */ -@Composable -private fun BroadcastAllProgressLine(progress: BroadcastAllProgress) { - Text( - text = when (progress) { - is BroadcastAllProgress.Sending -> - stringResource(Res.string.sending_entry_n_of_m, progress.entry, progress.total) - is BroadcastAllProgress.Done -> - stringResource( - Res.string.accepted_by_every_relay_for_n_of_m_entries, - progress.acceptedEverywhere, - progress.total - ) - }, - style = MaterialTheme.typography.bodyMedium, - color = when (progress) { - is BroadcastAllProgress.Sending -> MaterialTheme.colorScheme.onSurfaceVariant - is BroadcastAllProgress.Done -> if (progress.acceptedEverywhere == progress.total) { - MaterialTheme.colorScheme.primary - } else { - MaterialTheme.colorScheme.error - } - }, - textAlign = TextAlign.Center, - modifier = Modifier.fillMaxWidth() - ) -} - -/** - * What one entry's relays answered to "Broadcast all", under its card. - * - * The count first, in the words the one-event screen uses for its own; then - * one line per relay that did not say OK, in the relay's words, because - * "blocked: not on the allow list" is something a member can act on and a - * count of two out of three is not. A relay that said OK is in the count and - * nowhere else. - */ -@Composable -private fun EntryBroadcastLines(broadcast: EntryBroadcast) { - Column( - modifier = Modifier.fillMaxWidth().padding(vertical = MaterialTheme.spacing.relatedGap), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap), - horizontalAlignment = Alignment.CenterHorizontally - ) { - when (broadcast) { - EntryBroadcast.Sending -> Text( - text = stringResource(Res.string.relay_sending), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - textAlign = TextAlign.Center - ) - - EntryBroadcast.NoRelays -> Text( - text = stringResource(Res.string.no_relays_to_send_it_to), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error, - textAlign = TextAlign.Center - ) - - is EntryBroadcast.Sent -> { - Text( - text = stringResource( - Res.string.accepted_by_n_of_m_relays, - broadcast.accepted, - broadcast.asked - ), - style = MaterialTheme.typography.bodySmall, - color = if (broadcast.isAcceptedEverywhere) { - MaterialTheme.colorScheme.primary - } else { - MaterialTheme.colorScheme.error - }, - textAlign = TextAlign.Center - ) - - broadcast.refusals.forEach { (relay, outcome) -> - Text( - text = stringResource( - Res.string.relay_and_answer, - // The host rather than the whole URL, as the - // one-event screen's rows: every relay here starts - // `wss://`. - relay.displayUrl(), - outcome.label() - ), - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.error, - textAlign = TextAlign.Center - ) - } - } - } - } -} - -/** - * One entry the group accepted into a list it curates, as the list's own word. - * - * The title first, because every list has one; then which list, since a group - * may curate several and an entry says nothing about its list on its face; - * then the glance the queue row gives -- the fields that say what the entry - * *is*, labelled as the schema labels them, and not the links -- and the body - * where the list has one. The last line credits the suggester, when there was - * one, and dates the group's decision, which is the fact a member reading the - * screen came for. - * - * Not a way in to anything: the entry is revised from the queue it was - * suggested to, where the suggestion it came from and the "Curated" mark sit - * side by side, and the card's one action is the broadcast under it. - */ -@Composable -private fun GroupCuratedEntryCard(accepted: GroupCuratedEntry) { - val schema = accepted.list.schema - val entry = accepted.entry - - Card(modifier = Modifier.fillMaxWidth()) { - ListItem( - leadingContent = { - Icon( - Icons.Default.CheckCircle, - contentDescription = Decorative, - tint = MaterialTheme.colorScheme.primary - ) - }, - headlineContent = { - Text( - text = accepted.title, - maxLines = 2, - overflow = TextOverflow.Ellipsis - ) - }, - supportingContent = { - Column( - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap) - ) { - Text( - text = stringResource(Res.string.in_list, schema.displayName()), - style = MaterialTheme.typography.labelMedium, - maxLines = 1, - overflow = TextOverflow.Ellipsis - ) - - glanceOf(entry, schema)?.let { - Text( - text = it, - style = MaterialTheme.typography.bodySmall, - maxLines = 2, - overflow = TextOverflow.Ellipsis - ) - } - - bodyOf(entry, schema)?.let { - Text( - text = it, - maxLines = 3, - overflow = TextOverflow.Ellipsis - ) - } - - Text( - text = listOfNotNull( - entry.source?.let { stringResource(Res.string.suggested_by, it.pubKey.shortened()) }, - stringResource( - Res.string.signed_by_the_group_on, - accepted.signedAt.toFormattedTimeAndDateString() - ) - ).joinToString(" · "), - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - } - } - ) - } -} - -@ConformancePreviews -@Composable -private fun GroupCuratedEntriesScreenPreview() { - val chatRoomId = "d".repeat(64) - - // Built rather than read out of signed events: the reading checks a real - // signature, and there is no real one here. - val films = GroupCuratedSchema( - signedEvent = GroupSignedEvent( - id = "c".repeat(64), - chatRoomId = chatRoomId, - publicKey = chatRoomId, - kind = CuratedSchemaEvent.KIND, - tags = emptyArray(), - content = "", - signature = "f".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_000) - ), - schema = CuratedSchema( - identifier = "films", - title = "Films worth translating suggestion", - name = "Films worth translating", - description = "Things the group would translate, with a link to each.", - visibility = CuratedVisibility.Public, - fields = listOf(CuratedField.IDENTIFIER, CuratedField.TITLE), - relays = listOf("wss://relay.one.example") - ) - ) - - BennuTheme { - Surface(modifier = Modifier.fillMaxSize()) { - GroupCuratedEntriesScreen( - activeUserPublicKey = "a".repeat(64), - chatRoomId = chatRoomId, - relayHint = null, - initialGroupCuratedEntriesUIState = GroupCuratedEntriesUIState.Loaded( - localChatRoom = LocalChatRoom( - chatRoom = ChatRoom( - id = chatRoomId, - userPublicKey = "a".repeat(64), - subject = "Translation room", - description = null, - initialGiftWrapPayloadId = "sdfaer", - mlsGroupState = "state" - ) - ), - groupCuratedEntries = listOf( - GroupCuratedEntry( - signedEvent = GroupSignedEvent( - id = "e".repeat(64), - chatRoomId = chatRoomId, - publicKey = chatRoomId, - kind = CuratedEntryEvent.CANONICAL_KIND, - tags = arrayOf( - arrayOf("d", "magic-money"), - arrayOf("title", "Magic Money") - ), - content = "", - signature = "f".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_900) - ), - list = films, - entry = CuratedEntry( - kind = CuratedEntryEvent.CANONICAL_KIND, - id = "e".repeat(64), - pubKey = chatRoomId, - createdAt = 1_700_000_900, - identifier = "magic-money", - title = "Magic Money", - values = mapOf( - "identifier" to listOf("magic-money"), - "title" to listOf("Magic Money"), - ), - source = null - ) - ) - ) - ), - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - publishTransport = object : EventPublishTransport { - override suspend fun publishEvent( - nostrEvent: NostrEvent, - relays: Set - ): Flow = emptyFlow() - }, - onNavigateToRoute = {}, - onNavigateBack = {}, - ) - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupCuratedSchemasScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupCuratedSchemasScreen.kt deleted file mode 100644 index 0edfc8df..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupCuratedSchemasScreen.kt +++ /dev/null @@ -1,458 +0,0 @@ -package com.machankura.bennu.compose.ui.composable - -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.ExperimentalLayoutApi -import androidx.compose.foundation.layout.FlowRow -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.automirrored.filled.PlaylistAdd -import androidx.compose.material.icons.filled.Ballot -import androidx.compose.material.icons.filled.Edit -import androidx.compose.material.icons.filled.Inbox -import androidx.compose.material3.Card -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.Icon -import androidx.compose.material3.ListItem -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Scaffold -import androidx.compose.material3.SnackbarHost -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.text.style.TextOverflow -import androidx.lifecycle.viewmodel.compose.viewModel -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import bennu.composeapp.generated.resources.Res -import bennu.composeapp.generated.resources.add_schema -import bennu.composeapp.generated.resources.curated_schemas -import bennu.composeapp.generated.resources.fields_colon -import bennu.composeapp.generated.resources.signed_by_the_group_on -import bennu.composeapp.generated.resources.this_group_has_not_published_a_curated_schema_yet -import bennu.composeapp.generated.resources.view_suggestions -import org.jetbrains.compose.resources.stringResource -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.extensions.toFormattedTimeAndDateString -import com.machankura.bennu.compose.nostr.GroupCuratedSchema -import com.machankura.bennu.compose.nostr.curated.CuratedField -import com.machankura.bennu.compose.nostr.curated.CuratedSchema -import com.machankura.bennu.compose.nostr.curated.CuratedSchemaEvent -import com.machankura.bennu.compose.nostr.curated.CuratedVisibility -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.ui.composable.navigation.routes.BroadcastGroupSignedEventRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.CuratedSuggestionListRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.EditGroupCuratedSchemaRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.navigation.routes.SelectCuratedSchemaTemplateRoute -import com.machankura.bennu.compose.ui.composable.widgets.Decorative -import com.machankura.bennu.compose.ui.composable.widgets.EmptyState -import com.machankura.bennu.compose.ui.composable.widgets.ErrorState -import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator -import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState -import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton -import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition -import com.machankura.bennu.compose.ui.composable.widgets.buttons.BroadcastButton -import com.machankura.bennu.compose.ui.theme.ConformancePreviews -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.theme.readableContent -import com.machankura.bennu.compose.ui.theme.spacing -import com.machankura.bennu.compose.ui.view.model.GroupCuratedSchemasViewModel -import com.machankura.bennu.compose.ui.view.state.GroupCuratedSchemasUIState -import kotlin.time.Instant - -/** - * The lists the group curates, as the schemas it signed for them. - * - * Pushed from its row on the group's screen, which counts the schemas and - * nothing more. This is where they are read: one card per list, most recently - * signed first, each with its queue and its broadcast under it, and -- for a - * member holding a share of the key -- the way into the editor, on the card - * for a revision, and at the end the way to a new list, which starts with the - * template picker rather than with the editor: a new list has a shape to - * choose and a revision has one already. - * - * A schema exists to be read by people who were never in the room, so a member - * without a share reads it like anybody else, and reads its queue, which the - * group did not write. What they cannot do is propose a revision -- neither a - * new schema nor an edit -- since proposing is a signature by the group and - * `proposeSigningBatch` throws for a device holding no share. - */ -@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class) -@Composable -fun GroupCuratedSchemasScreen( - activeUserPublicKey: HexKey, - chatRoomId: String, - relayHint: String?, - initialGroupCuratedSchemasUIState: GroupCuratedSchemasUIState = - GroupCuratedSchemasUIState.Loading, - chatRepository: ChatRepository, - onNavigateToRoute: (Route) -> Unit, - onNavigateBack: () -> Unit, -) { - val groupCuratedSchemasViewModel: GroupCuratedSchemasViewModel = viewModel( - factory = GroupCuratedSchemasViewModel.factory( - chatRoomId = chatRoomId, - initialGroupCuratedSchemasUIState = initialGroupCuratedSchemasUIState, - chatRepository = chatRepository, - ) - ) - - LaunchedEffect(true) { - if (initialGroupCuratedSchemasUIState == GroupCuratedSchemasUIState.Loading) { - groupCuratedSchemasViewModel.initiate() - } - } - - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - topBar = { - TopAppBar( - title = { - Text( - text = stringResource(Res.string.curated_schemas), - maxLines = 1, - overflow = TextOverflow.Ellipsis - ) - }, - navigationIcon = { NavigateBackButton(onNavigateBack) } - ) - } - ) { padding -> - ScreenStateTransition(groupCuratedSchemasViewModel.groupCuratedSchemasUIState) { uiState -> - when (val state = uiState) { - is GroupCuratedSchemasUIState.Error -> { - // Nothing to retry: the room came from a navigation argument, - // and reading it again with the same one fails the same way. - ErrorState( - modifier = Modifier.padding(padding), - message = state.message, - onRetry = null - ) - } - - GroupCuratedSchemasUIState.Loading -> { - Column( - modifier = Modifier.fillMaxWidth().padding(padding) - .padding(MaterialTheme.spacing.screenMargin), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.sectionGap) - ) { - Spacer(modifier = Modifier.height(MaterialTheme.spacing.emphasisGap)) - - LoadingDataIndicator(fillScreen = false) - } - } - - is GroupCuratedSchemasUIState.Loaded -> { - // A revision opens the editor on the schema to revise, which - // needs no template: it starts from the schema itself. - val edit: (String) -> Unit = { identifier -> - onNavigateToRoute.invoke( - EditGroupCuratedSchemaRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint, - identifier = identifier, - template = null - ) - ) - } - - // A new list opens the template picker, which opens the - // editor in turn on the shape chosen there. - val add: () -> Unit = { - onNavigateToRoute.invoke( - SelectCuratedSchemaTemplateRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint - ) - ) - } - - LazyColumn( - modifier = Modifier.padding(padding).readableContent().fillMaxSize() - .padding(MaterialTheme.spacing.space250), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space125) - ) { - if (state.groupCuratedSchemas.isEmpty()) { - item { - EmptyState( - message = stringResource( - Res.string.this_group_has_not_published_a_curated_schema_yet - ), - action = if (state.canSign) { - { AddSchemaButton(onClick = add) } - } else { - null - } - ) - } - } else { - items( - items = state.groupCuratedSchemas, - key = { curated -> curated.signedEvent.id } - ) { curated -> - // The card and its queue as one item, so the - // button stays under the schema it is about - // however the list is arranged. - Column( - modifier = Modifier.fillMaxWidth(), - horizontalAlignment = Alignment.CenterHorizontally - ) { - GroupCuratedSchemaCard( - curatedSchema = curated, - // Into the editor for a member who could - // propose a revision, and a plain card for - // one who could not: the screen's gate, - // applied to the card because each schema - // is edited on its own. - onEdit = if (state.canSign) { - { edit(curated.identifier) } - } else { - null - } - ) - - // Under every schema and behind no gate, - // because the queue is the one thing here - // the group did not write: a schema exists - // to be answered by strangers, and reading - // the answers takes no share of the key. - // Per card because each list has its own - // queue. - // - // Beside the broadcast button rather than - // over it, wrapping where the two will not - // fit on one line: both are about this one - // card and a column of buttons under every - // schema would read as a menu. - FlowRow( - horizontalArrangement = Arrangement.spacedBy( - MaterialTheme.spacing.itemGap, - Alignment.CenterHorizontally - ) - ) { - TextButton( - onClick = { - onNavigateToRoute.invoke( - CuratedSuggestionListRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint, - identifier = curated.identifier - ) - ) - } - ) { - Icon(Icons.Default.Inbox, contentDescription = Decorative) - - Spacer( - modifier = Modifier.width(MaterialTheme.spacing.space125) - ) - - Text(stringResource(Res.string.view_suggestions)) - } - - BroadcastButton( - onClick = { - onNavigateToRoute.invoke( - BroadcastGroupSignedEventRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint, - signedEventId = curated.signedEvent.id - ) - ) - } - ) - } - } - } - - if (state.canSign) { - item { - AddSchemaButton(onClick = add) - } - } - } - } - } - } - } - } -} - -/** - * One list the group curates, as the schema it signed for it. - * - * Named by the list -- the domain where it claims one, else the name -- because - * that is what a suggester sees the list called; the title under it is the label - * the event carries. The fields are listed by label rather than counted, since - * what a reader wants to know about a list is what an entry in it asks for, and - * "13 fields" answers a different question. - * - * The visibility is on the last line beside the date, because who may suggest is - * the one fact on the card a member might act on -- a closed list is one they - * would have to be named on. - * - * [onEdit] null draws a card that cannot be opened. It is the screen's gate - * applied per card: a schema is edited on its own, so the way in has to be on it. - */ -@Composable -private fun GroupCuratedSchemaCard( - curatedSchema: GroupCuratedSchema, - onEdit: (() -> Unit)? -) { - val content: @Composable () -> Unit = { - ListItem( - leadingContent = { - Icon(Icons.Default.Ballot, contentDescription = Decorative) - }, - trailingContent = onEdit?.let { - { Icon(Icons.Default.Edit, contentDescription = "Edit schema") } - }, - headlineContent = { - Text( - text = curatedSchema.schema.displayName(), - maxLines = 1, - overflow = TextOverflow.Ellipsis - ) - }, - supportingContent = { - Column( - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap) - ) { - Text( - text = curatedSchema.schema.title, - style = MaterialTheme.typography.labelMedium, - maxLines = 1, - overflow = TextOverflow.Ellipsis - ) - - Text( - text = curatedSchema.schema.description, - maxLines = 3, - overflow = TextOverflow.Ellipsis - ) - - Text( - text = stringResource( - Res.string.fields_colon, - curatedSchema.schema.fields.joinToString { it.labelOrName() } - ), - style = MaterialTheme.typography.bodySmall, - maxLines = 2, - overflow = TextOverflow.Ellipsis - ) - - Text( - text = listOfNotNull( - curatedSchema.schema.visibility?.let { stringResource(it.label()) }, - stringResource( - Res.string.signed_by_the_group_on, - curatedSchema.signedAt.toFormattedTimeAndDateString() - ) - ).joinToString(" · "), - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - } - } - ) - } - - if (onEdit != null) { - Card(modifier = Modifier.fillMaxWidth(), onClick = onEdit) { content() } - } else { - Card(modifier = Modifier.fillMaxWidth()) { content() } - } -} - -/** - * The way to a list that does not exist yet: `SelectCuratedSchemaTemplateScreen`, - * and through it the editor. The icon is decorative because the label is - * beside it. - */ -@Composable -private fun AddSchemaButton(onClick: () -> Unit) { - TextButton(onClick = onClick) { - Icon(Icons.AutoMirrored.Filled.PlaylistAdd, contentDescription = Decorative) - - Spacer(modifier = Modifier.width(MaterialTheme.spacing.space125)) - - Text(stringResource(Res.string.add_schema)) - } -} - -@ConformancePreviews -@Composable -private fun GroupCuratedSchemasScreenPreview() { - val chatRoomId = "d".repeat(64) - - BennuTheme { - Surface(modifier = Modifier.fillMaxSize()) { - GroupCuratedSchemasScreen( - activeUserPublicKey = "a".repeat(64), - chatRoomId = chatRoomId, - relayHint = null, - initialGroupCuratedSchemasUIState = GroupCuratedSchemasUIState.Loaded( - localChatRoom = LocalChatRoom( - chatRoom = ChatRoom( - id = chatRoomId, - userPublicKey = "a".repeat(64), - subject = "Translation room", - description = null, - initialGiftWrapPayloadId = "sdfaer", - mlsGroupState = "state" - ) - ), - // Built rather than read out of a signed event: the reading - // checks a real signature, and there is no real one here. - groupCuratedSchemas = listOf( - GroupCuratedSchema( - signedEvent = GroupSignedEvent( - id = "c".repeat(64), - chatRoomId = chatRoomId, - publicKey = chatRoomId, - kind = CuratedSchemaEvent.KIND, - tags = emptyArray(), - content = "", - signature = "f".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_000) - ), - schema = CuratedSchema( - identifier = "films", - title = "Films worth translating suggestion", - name = "Films worth translating", - description = "Things the group would translate, with a link to each.", - visibility = CuratedVisibility.Public, - fields = listOf(CuratedField.IDENTIFIER, CuratedField.TITLE), - relays = listOf("wss://relay.one.example") - ) - ) - ), - canSign = true - ), - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - onNavigateToRoute = {}, - onNavigateBack = {}, - ) - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ProposeGroupEventScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ProposeGroupEventScreen.kt index 488eabfc..0dd670a3 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ProposeGroupEventScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ProposeGroupEventScreen.kt @@ -80,7 +80,6 @@ import bennu.composeapp.generated.resources.that_is_not_json import bennu.composeapp.generated.resources.the_content_is_not_a_profile import bennu.composeapp.generated.resources.the_group_signs_an_event_so_it_takes_a_quorum import bennu.composeapp.generated.resources.this_group_has_no_shared_key_to_sign_an_event -import bennu.composeapp.generated.resources.this_schema_cannot_be_signed_as_it_is import bennu.composeapp.generated.resources.unsigned_event import bennu.composeapp.generated.resources.what_the_group_would_sign import org.jetbrains.compose.resources.stringResource @@ -91,8 +90,8 @@ import org.jetbrains.compose.resources.stringResource * The typed editors each build one kind of statement; this takes any of the * kinds the group's screen can show, as JSON, the way another tool prints one. * Above the paste is what the group would be signing, read back the way the - * signing screen will describe it, so a member sees "Curated schema · bitcoin.mov" - * rather than a wall of brackets before deciding -- and sees why the group will + * signing screen will describe it, so a member sees "Post · gm" rather than a + * wall of brackets before deciding -- and sees why the group will * not be asked when the paste is something it could never show. * * The byline is the group's, as on the post composer and for the same reason: @@ -364,48 +363,30 @@ private fun ProposalPreview(ready: GroupEventProposal.Ready) { * Why the group will not be asked, under the paste it is about. * * Named rather than silent: a button that does nothing for a paste it refuses is - * indistinguishable from a missed tap. A schema's reasons are the same sentences - * the schema editor uses, since they are the same checks. + * indistinguishable from a missed tap. */ @Composable private fun RefusalNotice(refused: GroupEventProposal.Refused) { - Column( - modifier = Modifier.fillMaxWidth(), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap) - ) { - Text( - text = when (refused) { - GroupEventProposal.Refused.NotJson -> stringResource(Res.string.that_is_not_json) - GroupEventProposal.Refused.NotAnObject -> stringResource(Res.string.an_event_is_a_json_object) - GroupEventProposal.Refused.NoKind -> stringResource(Res.string.an_event_needs_a_kind) - is GroupEventProposal.Refused.KindNotAccepted -> stringResource( - Res.string.kind_n_has_nowhere_to_go_on_this_screen, - refused.kind.toString(), - GroupEventProposal.ACCEPTED_KINDS.sorted().joinToString() - ) - GroupEventProposal.Refused.TagsMalformed -> - stringResource(Res.string.tags_must_be_a_list_of_lists_of_strings) - GroupEventProposal.Refused.ContentNotText -> stringResource(Res.string.content_must_be_text) - GroupEventProposal.Refused.ProfileUnreadable -> - stringResource(Res.string.the_content_is_not_a_profile) - GroupEventProposal.Refused.PostBlank -> stringResource(Res.string.a_post_needs_something_to_say) - is GroupEventProposal.Refused.SchemaUnusable -> - stringResource(Res.string.this_schema_cannot_be_signed_as_it_is) - }, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error - ) - - if (refused is GroupEventProposal.Refused.SchemaUnusable) { - refused.problems.forEach { problem -> - Text( - text = problem.message(), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error - ) - } - } - } + Text( + text = when (refused) { + GroupEventProposal.Refused.NotJson -> stringResource(Res.string.that_is_not_json) + GroupEventProposal.Refused.NotAnObject -> stringResource(Res.string.an_event_is_a_json_object) + GroupEventProposal.Refused.NoKind -> stringResource(Res.string.an_event_needs_a_kind) + is GroupEventProposal.Refused.KindNotAccepted -> stringResource( + Res.string.kind_n_has_nowhere_to_go_on_this_screen, + refused.kind.toString(), + GroupEventProposal.ACCEPTED_KINDS.sorted().joinToString() + ) + GroupEventProposal.Refused.TagsMalformed -> + stringResource(Res.string.tags_must_be_a_list_of_lists_of_strings) + GroupEventProposal.Refused.ContentNotText -> stringResource(Res.string.content_must_be_text) + GroupEventProposal.Refused.ProfileUnreadable -> + stringResource(Res.string.the_content_is_not_a_profile) + GroupEventProposal.Refused.PostBlank -> stringResource(Res.string.a_post_needs_something_to_say) + }, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error + ) } @ConformancePreviews diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/SelectCuratedSchemaTemplateScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/SelectCuratedSchemaTemplateScreen.kt deleted file mode 100644 index de2b014e..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/SelectCuratedSchemaTemplateScreen.kt +++ /dev/null @@ -1,248 +0,0 @@ -package com.machankura.bennu.compose.ui.composable - -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.verticalScroll -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.automirrored.filled.ArrowForward -import androidx.compose.material.icons.automirrored.filled.Chat -import androidx.compose.material.icons.filled.Category -import androidx.compose.material.icons.filled.Link -import androidx.compose.material.icons.filled.Tune -import androidx.compose.material3.Card -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.Icon -import androidx.compose.material3.ListItem -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Scaffold -import androidx.compose.material3.SnackbarHost -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.vector.ImageVector -import androidx.compose.ui.text.style.TextOverflow -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import bennu.composeapp.generated.resources.Res -import bennu.composeapp.generated.resources.a_list_is_a_schema_what_an_entry_may_contain -import bennu.composeapp.generated.resources.fields_colon -import bennu.composeapp.generated.resources.pick_a_shape_to_start_from -import bennu.composeapp.generated.resources.start_a_list -import bennu.composeapp.generated.resources.template_catalogue -import bennu.composeapp.generated.resources.template_catalogue_description -import bennu.composeapp.generated.resources.template_custom -import bennu.composeapp.generated.resources.template_custom_description -import bennu.composeapp.generated.resources.template_discussion -import bennu.composeapp.generated.resources.template_discussion_description -import bennu.composeapp.generated.resources.template_links -import bennu.composeapp.generated.resources.template_links_description -import org.jetbrains.compose.resources.StringResource -import org.jetbrains.compose.resources.stringResource -import com.machankura.bennu.compose.nostr.curated.CuratedSchemaTemplate -import com.machankura.bennu.compose.ui.composable.navigation.routes.EditGroupCuratedSchemaRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.widgets.Decorative -import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState -import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton -import com.machankura.bennu.compose.ui.theme.ConformancePreviews -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.theme.readableContent -import com.machankura.bennu.compose.ui.theme.spacing - -/** - * The first step of adding a curated schema: which shape the list starts from. - * - * curare.to's "Start a list" page, which is what its `/new` shows before a - * template is chosen: a line on what a list is, and one card per template - * naming it, saying what it is for and listing what an entry in it asks for. - * Tapping a card opens the editor seeded from that template, so that a list - * started here and one started on that site are the same kind of thing -- - * and a member who wants none of the shapes takes *Custom*, which is the two - * fields every list has and what "Add schema" used to open on directly. - * - * There is nothing to load and no state to keep: the templates are constants, - * and the choice leaves as an argument to `EditGroupCuratedSchemaRoute` rather - * than being remembered here. Back from the editor is this screen and another - * shape, the way the browser's back is on the site. - * - * Gated by the screen before it, not here. "Add schema" is offered only to a - * member holding a share of the key, and the editor says so again if a screen - * ever reaches it another way. - */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun SelectCuratedSchemaTemplateScreen( - activeUserPublicKey: HexKey, - chatRoomId: String, - relayHint: String?, - onNavigateToRoute: (Route) -> Unit, - onNavigateBack: () -> Unit, -) { - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - topBar = { - TopAppBar( - title = { - Text( - text = stringResource(Res.string.start_a_list), - maxLines = 1, - overflow = TextOverflow.Ellipsis - ) - }, - navigationIcon = { NavigateBackButton(onNavigateBack) } - ) - } - ) { innerPadding -> - // A scrolling column rather than a lazy list: four cards, all of them - // wanted at once, and nothing under them to page in. - Column( - modifier = Modifier - .padding(innerPadding) - .readableContent() - .fillMaxSize() - .verticalScroll(rememberScrollState()) - .padding( - horizontal = MaterialTheme.spacing.screenMargin, - vertical = MaterialTheme.spacing.itemGap - ), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap) - ) { - // At the leading edge like the cards under it, whose icons and - // headlines it lines up with; the editor after this one centres - // its lead because nothing on it has an edge to keep. - Text( - text = stringResource(Res.string.a_list_is_a_schema_what_an_entry_may_contain), - style = MaterialTheme.typography.bodyMedium - ) - - Text( - text = stringResource(Res.string.pick_a_shape_to_start_from), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - - CuratedSchemaTemplate.entries.forEach { template -> - CuratedSchemaTemplateCard( - template = template, - onClick = { - onNavigateToRoute.invoke( - EditGroupCuratedSchemaRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint, - identifier = null, - template = template.key - ) - ) - } - ) - } - } - } -} - -/** - * One shape a list can start from, as a card that opens the editor on it. - * - * The site's card is the name, the description and a count of fields. The - * count is the one thing changed: the fields are listed by label instead, the - * way the group's own schema cards list them, because what a member choosing - * a shape wants to know is what an entry in it will ask for, and "6 fields" - * answers a different question. The identifier is among them although a form - * never asks for it: the editor lists it as a row too, marked derived, and the - * card shows the rows the editor is about to. - */ -@Composable -private fun CuratedSchemaTemplateCard( - template: CuratedSchemaTemplate, - onClick: () -> Unit -) { - Card(modifier = Modifier.fillMaxWidth(), onClick = onClick) { - ListItem( - leadingContent = { - // Decorative: the name beside it is the label, and the card is - // the target. - Icon(template.icon(), contentDescription = Decorative) - }, - trailingContent = { - Icon(Icons.AutoMirrored.Filled.ArrowForward, contentDescription = Decorative) - }, - headlineContent = { - Text( - text = stringResource(template.label()), - maxLines = 1, - overflow = TextOverflow.Ellipsis - ) - }, - supportingContent = { - Column( - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap) - ) { - Text(text = stringResource(template.description())) - - // Unclipped, unlike the group's schema cards: a template's - // fields are this build's own and ten at most, and the list - // is what the choice is made on. - Text( - text = stringResource( - Res.string.fields_colon, - template.fields.joinToString { it.labelOrName() } - ), - style = MaterialTheme.typography.bodySmall - ) - } - } - ) - } -} - -/** - * What the picker calls a template. - * - * A `when` rather than a field on each entry, for the reason `CuratedVisibility` - * has one: the enum stays the protocol's four shapes with no copy behind it, - * and a fifth is a compile error here rather than a card with no name. - */ -private fun CuratedSchemaTemplate.label(): StringResource = when (this) { - CuratedSchemaTemplate.Links -> Res.string.template_links - CuratedSchemaTemplate.Discussion -> Res.string.template_discussion - CuratedSchemaTemplate.Catalogue -> Res.string.template_catalogue - CuratedSchemaTemplate.Custom -> Res.string.template_custom -} - -/** What the template is for, in the site's words. */ -private fun CuratedSchemaTemplate.description(): StringResource = when (this) { - CuratedSchemaTemplate.Links -> Res.string.template_links_description - CuratedSchemaTemplate.Discussion -> Res.string.template_discussion_description - CuratedSchemaTemplate.Catalogue -> Res.string.template_catalogue_description - CuratedSchemaTemplate.Custom -> Res.string.template_custom_description -} - -/** The picture of the shape: what the entries mostly are, or the sliders for none in particular. */ -private fun CuratedSchemaTemplate.icon(): ImageVector = when (this) { - CuratedSchemaTemplate.Links -> Icons.Default.Link - CuratedSchemaTemplate.Discussion -> Icons.AutoMirrored.Filled.Chat - CuratedSchemaTemplate.Catalogue -> Icons.Default.Category - CuratedSchemaTemplate.Custom -> Icons.Default.Tune -} - -@ConformancePreviews -@Composable -private fun SelectCuratedSchemaTemplateScreenPreview() { - BennuTheme { - Surface(modifier = Modifier.fillMaxSize()) { - SelectCuratedSchemaTemplateScreen( - activeUserPublicKey = "a".repeat(64), - chatRoomId = "d".repeat(64), - relayHint = null, - onNavigateToRoute = {}, - onNavigateBack = {}, - ) - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/BennuNavHost.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/BennuNavHost.kt index d560dd20..6b4896cb 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/BennuNavHost.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/BennuNavHost.kt @@ -45,19 +45,13 @@ import com.machankura.bennu.compose.ui.composable.DkgRound1ApprovalScreen import com.machankura.bennu.compose.ui.composable.DkgRound2ApprovalScreen import com.machankura.bennu.compose.ui.composable.EditGroupNostrProfileScreen import com.machankura.bennu.compose.ui.composable.AddGroupPostScreen -import com.machankura.bennu.compose.ui.composable.AcceptCuratedSuggestionScreen -import com.machankura.bennu.compose.ui.composable.EditGroupCuratedSchemaScreen -import com.machankura.bennu.compose.ui.composable.SelectCuratedSchemaTemplateScreen import com.machankura.bennu.compose.ui.composable.BroadcastGroupSignedEventScreen -import com.machankura.bennu.compose.ui.composable.CuratedSuggestionListScreen import com.machankura.bennu.compose.ui.composable.ProposeGroupEventScreen import com.machankura.bennu.compose.ui.composable.EditGroupRelaysScreen import com.machankura.bennu.compose.ui.composable.GroupNostrProfileScreen import com.machankura.bennu.compose.ui.composable.GroupRelaysScreen import com.machankura.bennu.compose.ui.composable.GroupWalletScreen import com.machankura.bennu.compose.ui.composable.GroupPostsScreen -import com.machankura.bennu.compose.ui.composable.GroupCuratedSchemasScreen -import com.machankura.bennu.compose.ui.composable.GroupCuratedEntriesScreen import com.machankura.bennu.compose.ui.composable.HomeScreen import com.machankura.bennu.compose.ui.composable.ImplementationPendingScreen import com.machankura.bennu.compose.ui.composable.KeyPackageManagementScreen @@ -154,11 +148,7 @@ import com.machankura.bennu.compose.ui.composable.navigation.routes.AddArtifactR import com.machankura.bennu.compose.ui.composable.navigation.routes.AddDialectRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.EditGroupNostrProfileRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.AddGroupPostRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.AcceptCuratedSuggestionRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.EditGroupCuratedSchemaRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.SelectCuratedSchemaTemplateRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.BroadcastGroupSignedEventRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.CuratedSuggestionListRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.ProposeGroupEventRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.EditGroupRelaysRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupNostrProfileRoute @@ -168,8 +158,6 @@ import com.machankura.bennu.compose.wallet.GroupOnchainWallets import com.machankura.bennu.compose.wallet.GroupTransactionWatcher import fr.acinq.phoenix.managers.NodeParamsManager import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupPostsRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupCuratedSchemasRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupCuratedEntriesRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.FrostSigningRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.ProposalListRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.AddChapterRoute @@ -1300,42 +1288,6 @@ fun BennuNavHost( } ) } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - GroupCuratedSchemasScreen( - activeUserPublicKey = route.activeUserPublicKey, - chatRoomId = route.chatRoomId, - relayHint = route.relayHint, - chatRepository = databaseChatRepository, - onNavigateToRoute = { actionRoute -> - navController.navigate(route = actionRoute) - }, - onNavigateBack = { - navController.popBackStack() - } - ) - } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - GroupCuratedEntriesScreen( - activeUserPublicKey = route.activeUserPublicKey, - chatRoomId = route.chatRoomId, - relayHint = route.relayHint, - chatRepository = databaseChatRepository, - // The pool itself, for "Broadcast all": the same send as the - // broadcast screen's, for the same reason it does not go - // through the queue. See `BroadcastGroupSignedEventViewModel`. - publishTransport = synchronizationViewModel.relaysSocketManager, - onNavigateToRoute = { actionRoute -> - navController.navigate(route = actionRoute) - }, - onNavigateBack = { - navController.popBackStack() - } - ) - } composable { backStackEntry -> val route = backStackEntry.toRoute() @@ -1405,101 +1357,6 @@ fun BennuNavHost( } ) } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - SelectCuratedSchemaTemplateScreen( - activeUserPublicKey = route.activeUserPublicKey, - chatRoomId = route.chatRoomId, - relayHint = route.relayHint, - // Pushed rather than replaced, so back from the editor is - // this screen and another shape. - onNavigateToRoute = { editorRoute -> - navController.navigate(route = editorRoute) - }, - onNavigateBack = { - navController.popBackStack() - } - ) - } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - EditGroupCuratedSchemaScreen( - activeUserPublicKey = route.activeUserPublicKey, - chatRoomId = route.chatRoomId, - relayHint = route.relayHint, - identifier = route.identifier, - template = route.template, - chatRepository = databaseChatRepository, - frostSigningRepository = databaseFrostSigningRepository, - onNavigateToRouteAndPopUpInclusive = { signingRoute -> - // Replace the editor so back returns to the group rather - // than to a schema whose proposal has already gone out -- - // and, for a new list, the template picker under it, for - // the same reason: the shape has been chosen and signed - // for, and offering it again would offer a second list. - navController.navigate(route = signingRoute) { - if (route.identifier == null) { - popUpTo { - inclusive = true - } - } else { - popUpTo { - inclusive = true - } - } - } - }, - onNavigateBack = { - navController.popBackStack() - } - ) - } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - CuratedSuggestionListScreen( - activeUserPublicKey = route.activeUserPublicKey, - chatRoomId = route.chatRoomId, - relayHint = route.relayHint, - identifier = route.identifier, - nostrRepository = databaseNostrRepository, - chatRepository = databaseChatRepository, - onNavigateBack = { - navController.popBackStack() - }, - onNavigateToRoute = { acceptRoute -> - navController.navigate(route = acceptRoute) - } - ) - } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - AcceptCuratedSuggestionScreen( - activeUserPublicKey = route.activeUserPublicKey, - chatRoomId = route.chatRoomId, - relayHint = route.relayHint, - identifier = route.identifier, - suggestionId = route.suggestionId, - nostrRepository = databaseNostrRepository, - chatRepository = databaseChatRepository, - frostSigningRepository = databaseFrostSigningRepository, - onNavigateBack = { - navController.popBackStack() - }, - onNavigateToRouteAndPopUpInclusive = { signingRoute -> - // Replace the form so back returns to the queue rather - // than to an entry whose proposal has already gone out. - navController.navigate(route = signingRoute) { - popUpTo { - inclusive = true - } - } - } - ) - } composable { backStackEntry -> val route = backStackEntry.toRoute() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/AcceptCuratedSuggestionRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/AcceptCuratedSuggestionRoute.kt deleted file mode 100644 index 1f4af5c3..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/AcceptCuratedSuggestionRoute.kt +++ /dev/null @@ -1,22 +0,0 @@ -package com.machankura.bennu.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -/** - * The form for taking one suggestion into a list the group curates: the entry - * as it was suggested, open for the group's edits, and a button that asks the - * group to sign it as the list's own. - * - * [identifier] is the schema's `d`, for the reason `CuratedSuggestionListRoute` - * gives; [suggestionId] is the suggestion's event id rather than its - * coordinate, because the canonical entry pins the exact version the group - * read -- the NIP's `e` tag -- and the id is what names a version. - */ -@Serializable -data class AcceptCuratedSuggestionRoute( - val activeUserPublicKey: String, - val chatRoomId: String, // TODO: have this as a publicKey - val relayHint: String?, - val identifier: String, - val suggestionId: String -): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/CuratedSuggestionListRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/CuratedSuggestionListRoute.kt deleted file mode 100644 index 21355463..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/CuratedSuggestionListRoute.kt +++ /dev/null @@ -1,19 +0,0 @@ -package com.machankura.bennu.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -/** - * The queue of one list the group curates: everything anyone has suggested to - * the schema at [identifier], read off the relays the schema names. - * - * Named by the schema's `d` for the reason `EditGroupCuratedSchemaRoute` is: - * the coordinate is what every suggestion replies to, and the group re-signing - * the schema changes the event without changing the queue. - */ -@Serializable -data class CuratedSuggestionListRoute( - val activeUserPublicKey: String, - val chatRoomId: String, // TODO: have this as a publicKey - val relayHint: String?, - val identifier: String -): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/EditGroupCuratedSchemaRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/EditGroupCuratedSchemaRoute.kt deleted file mode 100644 index fca3d832..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/EditGroupCuratedSchemaRoute.kt +++ /dev/null @@ -1,27 +0,0 @@ -package com.machankura.bennu.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -/** - * The editor for one of a group's curated schemas. - * - * [identifier] is the schema's `d`, and null opens the editor on a new one. It - * is the identifier rather than the event id because kind 31889 is addressable: - * an edit replaces the event under the same `d`, and the editor's job is to - * propose that replacement, so the coordinate is what names the thing being - * edited and the event is only its current version. - * - * [template] is the key of the `CuratedSchemaTemplate` a new schema starts - * from -- what `SelectCuratedSchemaTemplateRoute` chose, and the same word - * curare.to's editor takes as `?template=`. It means nothing on an edit, which - * starts from the schema itself, and null on a new schema is the bare two - * fields every list has. - */ -@Serializable -data class EditGroupCuratedSchemaRoute( - val activeUserPublicKey: String, - val chatRoomId: String, // TODO: have this as a publicKey - val relayHint: String?, - val identifier: String?, - val template: String? -): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupCuratedEntriesRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupCuratedEntriesRoute.kt deleted file mode 100644 index c83d50f5..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupCuratedEntriesRoute.kt +++ /dev/null @@ -1,16 +0,0 @@ -package com.machankura.bennu.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -/** - * The entries the group has accepted into the lists it curates, newest first, - * with a broadcast under each. Nothing is added from here: an entry is accepted - * from the queue it was suggested to, which is reached from its schema's card - * on the [GroupCuratedSchemasRoute] screen. - */ -@Serializable -data class GroupCuratedEntriesRoute( - val activeUserPublicKey: String, - val chatRoomId: String, // TODO: have this as a publicKey - val relayHint: String? -): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupCuratedSchemasRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupCuratedSchemasRoute.kt deleted file mode 100644 index fa005ffc..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupCuratedSchemasRoute.kt +++ /dev/null @@ -1,16 +0,0 @@ -package com.machankura.bennu.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -/** - * The lists the group curates, as the schemas it signed for them, one card per - * list with its queue and its broadcast under it. Each card is the way into - * that schema's editor for a member holding a share of the key, and the screen - * ends with the way to add one. - */ -@Serializable -data class GroupCuratedSchemasRoute( - val activeUserPublicKey: String, - val chatRoomId: String, // TODO: have this as a publicKey - val relayHint: String? -): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupNostrProfileRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupNostrProfileRoute.kt index a3fd5583..06f3254c 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupNostrProfileRoute.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupNostrProfileRoute.kt @@ -7,9 +7,9 @@ import kotlinx.serialization.Serializable * * The group's screen names the profile in a row; this is where it is read, with * the broadcast under it and, for a member holding a share of the key, the way - * into the editor. One of the five screens the group's signed work is split - * across -- see [GroupRelaysRoute], [GroupPostsRoute], [GroupCuratedSchemasRoute] - * and [GroupCuratedEntriesRoute] -- each pushed from its row on the group's screen. + * into the editor. One of the three screens the group's signed work is split + * across -- see [GroupRelaysRoute] and [GroupPostsRoute] -- each pushed from its + * row on the group's screen. */ @Serializable data class GroupNostrProfileRoute( diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/SelectCuratedSchemaTemplateRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/SelectCuratedSchemaTemplateRoute.kt deleted file mode 100644 index 04986a48..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/SelectCuratedSchemaTemplateRoute.kt +++ /dev/null @@ -1,19 +0,0 @@ -package com.machankura.bennu.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -/** - * The first step of adding a curated schema: which shape the list starts from. - * - * Pushed from the group's schemas screen, and pushing the editor in turn with - * the chosen template's key -- so that back from the editor is this screen and - * a different shape, the way curare.to's `/new` page is under its editor. - * There is no template to carry: the choice is made here and leaves as an - * argument to `EditGroupCuratedSchemaRoute`. - */ -@Serializable -data class SelectCuratedSchemaTemplateRoute( - val activeUserPublicKey: String, - val chatRoomId: String, // TODO: have this as a publicKey - val relayHint: String? -): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/AcceptCuratedSuggestionViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/AcceptCuratedSuggestionViewModel.kt deleted file mode 100644 index ab3af30c..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/AcceptCuratedSuggestionViewModel.kt +++ /dev/null @@ -1,324 +0,0 @@ -package com.machankura.bennu.compose.ui.view.model - -import androidx.compose.foundation.text.input.TextFieldState -import androidx.compose.runtime.MutableState -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateListOf -import androidx.compose.runtime.mutableStateMapOf -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import androidx.compose.runtime.snapshots.SnapshotStateList -import androidx.compose.runtime.snapshots.SnapshotStateMap -import androidx.lifecycle.ViewModel -import androidx.lifecycle.ViewModelProvider -import androidx.lifecycle.viewModelScope -import androidx.lifecycle.viewmodel.initializer -import androidx.lifecycle.viewmodel.viewModelFactory -import co.touchlab.kermit.Logger -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.IO -import kotlinx.coroutines.flow.first -import kotlinx.coroutines.launch -import com.machankura.bennu.compose.nostr.CuratedSuggestion -import com.machankura.bennu.compose.nostr.curated.CuratedEntryProblem -import com.machankura.bennu.compose.nostr.curated.CuratedField -import com.machankura.bennu.compose.nostr.curated.CuratedSuggestionRef -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.repository.NostrRepository -import com.machankura.bennu.compose.ui.view.state.AcceptCuratedSuggestionUIState - -/** - * One suggestion, taken into the list: the entry as somebody suggested it, - * edited by a member, and proposed as the group's own. - * - * Nothing here is saved. The working copy is one input per value the entry - * has, held on this view model rather than in the composition so that the - * window turning does not throw an edit away, and the button folds it into a - * kind 31890 for the room's quorum to put its key to. The list changes on - * every member's device at once, when a quorum has signed, or not at all. - * - * ### What is edited, and what is kept - * - * Curation is editorial -- the NIP says the curator may fix a year or swap a - * poster on the way through -- so every field the schema's form asks for is - * open. Two things are not. The `d` is kept whatever field writes it, because - * the canonical entry SHOULD land on the suggestion's coordinate so that - * accepting it twice revises one entry rather than making two. And a field the - * schema marks `derived` is kept as the suggester's client filled it in: this - * app derives nothing, and an entry a form never asked for is not one a form - * should let a member invent. - * - * ### Refused before proposed - * - * The button runs the queue's own verifier over the event it is about to - * propose, and refuses with the fields named. A signature is the most expensive - * thing this app does, and a canonical entry the queue would not count -- a - * year outside the schema's range, an option that is not one -- would be a - * quorum spent on an entry no client shows. - */ -class AcceptCuratedSuggestionViewModel( - val chatRoomId: String, - val activeUserPublicKey: HexKey, - val relayHint: String?, - /** The `d` of the schema whose list the entry goes into. */ - val identifier: String, - /** The event id of the suggestion being taken up. */ - val suggestionId: String, - initialAcceptCuratedSuggestionUIState: AcceptCuratedSuggestionUIState, - val nostrRepository: NostrRepository, - val chatRepository: ChatRepository, - val frostSigningRepository: FrostSigningRepository, -): ViewModel() { - - var acceptCuratedSuggestionUIState: AcceptCuratedSuggestionUIState by mutableStateOf( - initialAcceptCuratedSuggestionUIState - ) - private set - - private val logger = Logger.withTag(TAG) - - val isActionPending: MutableState = mutableStateOf(false) - - /** - * The working copy: for each field the form asks for, one input per value. - * - * A field that repeats has as many inputs as the suggestion had values, and - * can be given more; every other field has exactly one. Keyed by the - * schema's field name, which is what the entry is keyed by too. - */ - val inputs: SnapshotStateMap> = mutableStateMapOf() - - /** - * Why the last proposal did not go out, or nothing. Set by the button and - * left showing until the next press, since the button is the thing that - * will clear it. - */ - var problems: List by mutableStateOf(emptyList()) - private set - - private var isSeeded = false - - fun initiate() { - viewModelScope.launch(Dispatchers.IO) { - val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) - if (localChatRoom == null) { - acceptCuratedSuggestionUIState = AcceptCuratedSuggestionUIState.Error("Couldn't find the group") - return@launch - } - - val schema = chatRepository.groupCuratedSchemas(chatRoomId).firstOrNull { it.identifier == identifier } - if (schema == null) { - acceptCuratedSuggestionUIState = AcceptCuratedSuggestionUIState.Error("Couldn't find that schema") - return@launch - } - - // The same reading the queue screen makes, so what is accepted here - // is what was shown there: newest per coordinate, checked against - // the schema, and marked when the group already has an entry for it. - // An id the reading no longer holds is a version something newer has - // replaced since the row was tapped, and the newer one is what the - // queue now shows. - val events = nostrRepository.observeNostrEventsMatching(schema.queueReadFilter()).first() - val suggestion = CuratedSuggestion.queueOf(schema, events).firstOrNull { it.id == suggestionId } - if (suggestion == null) { - acceptCuratedSuggestionUIState = AcceptCuratedSuggestionUIState.Error("Couldn't find that suggestion") - return@launch - } - - acceptCuratedSuggestionUIState = AcceptCuratedSuggestionUIState.Loaded( - localChatRoom = localChatRoom, - schema = schema, - suggestion = suggestion, - canSign = localChatRoom.chatRoom.mlsGroupState != null && - frostSigningRepository.canSign(chatRoomId), - ) - } - } - - /** - * Fills the working copy from the suggestion, once. - * - * One input per value the suggestion carries for each field the form asks - * for, and one blank input for a field it carries nothing for, so there is - * somewhere to type. Called from the screen rather than from [initiate], - * because the loader is not the only way a loaded state arrives: a preview - * and a layout test both hand one straight in. Runs once, so the effect - * that calls it re-firing does not undo an edit. - */ - fun seedWorkingCopy(state: AcceptCuratedSuggestionUIState.Loaded) { - if (isSeeded) return - isSeeded = true - - val entry = state.suggestion.entry - - editableFields(state).forEach { field -> - val values = entry.values[field.name].orEmpty().ifEmpty { listOf("") } - inputs[field.name] = mutableStateListOf(*values.map { TextFieldState(it) }.toTypedArray()) - } - } - - /** Adds a blank input under [fieldName], for a field that repeats. */ - fun addValue(fieldName: String) { - inputs[fieldName]?.add(TextFieldState()) - } - - /** - * Drops the input at [index] under [fieldName]. The last input stays, blank - * rather than gone, so the field is still there to be typed into. - */ - fun removeValue(fieldName: String, index: Int) { - val values = inputs[fieldName] ?: return - if (index !in values.indices) return - - if (values.size == 1) { - values[0] = TextFieldState() - } else { - values.removeAt(index) - } - } - - /** - * The problems about [fieldName], for the field's own error state. A - * `require-any` rule is filed under its first field, so it shows there. - */ - fun problemsFor(fieldName: String): List = problems.filter { it.field == fieldName } - - /** - * The problems that are about no field on the form: the entry as a whole, - * or a field the form keeps rather than asks for. Shown at the top, since - * there is no input to show them under. - */ - fun problemsAboutTheEntry(state: AcceptCuratedSuggestionUIState.Loaded): List { - val editable = editableFields(state).map { it.name }.toSet() - return problems.filterNot { it.field in editable } - } - - /** - * The entry as the form has it: what was typed for every field the form - * asks for, and what was suggested for every field it keeps. - * - * Keyed by field name and holding every value, which is the shape - * `CuratedEntryEvent.canonicalTemplate` lays out as tags. Blank inputs come - * through and are dropped there; a blank is not a value. - */ - fun draft(state: AcceptCuratedSuggestionUIState.Loaded): Map> { - val suggested = state.suggestion.entry.values - - return state.schema.schema.fields.associate { field -> - field.name to (inputs[field.name]?.map { it.text.toString() } ?: suggested[field.name].orEmpty()) - } - } - - /** - * Opens a session over the entry, or says why not. - * - * Two refusals before anything is proposed and each is the caller's to - * say: an entry the queue would refuse, which is [onInvalid] with the - * reasons left in [problems]; and a proposal that could not be opened, - * which is [onFailure]. Both stay on the form with the edits still in it. - */ - fun proposeEntry( - state: AcceptCuratedSuggestionUIState.Loaded, - onSuccess: (sessionId: String) -> Unit, - onInvalid: () -> Unit, - onFailure: () -> Unit - ) { - // Guard against double submits. Two sessions over two versions of one - // entry would leave the list decided by whichever quorum finished last. - if (isActionPending.value) return - - val template = state.schema.canonicalTemplate( - values = draft(state), - source = CuratedSuggestionRef.of(state.suggestion.entry), - ) - - problems = state.schema.verifyCanonical(template) - if (problems.isNotEmpty()) { - onInvalid.invoke() - return - } - - isActionPending.value = true - - viewModelScope.launch(Dispatchers.IO) { - val session = runCatching { - frostSigningRepository.proposeSigning( - localChatRoom = state.localChatRoom, - userPublicKey = activeUserPublicKey, - kind = template.kind, - tags = template.tags, - content = template.content, - ) - }.onFailure { error -> - logger.e("Failed to propose a canonical entry for ${state.schema.coordinate()}", error) - }.getOrNull() - - viewModelScope.launch(Dispatchers.Main) { - if (session != null) { - onSuccess.invoke(session.id) - } else { - onFailure.invoke() - } - } - - isActionPending.value = false - } - } - - companion object { - private const val TAG = "AcceptCuratedSuggestionViewModel" - - /** The tag of the field the form keeps whatever else it says: the entry's coordinate. */ - private const val IDENTIFIER_TAG = "d" - - /** - * The fields the form opens for editing: the ones the schema's form asks - * for, less the one writing to `d`. See the class note for why those two - * are kept as they were suggested. - */ - fun editableFields(state: AcceptCuratedSuggestionUIState.Loaded): List = - state.schema.schema.formFields().filterNot { it.tag() == IDENTIFIER_TAG } - - /** - * The fields the form shows but does not open: what the suggester's client - * filled in, and what the entry is addressed by. In the schema's order, - * and only the ones the suggestion has a value for, since a kept field - * with nothing in it has nothing to show. - */ - fun keptFields(state: AcceptCuratedSuggestionUIState.Loaded): List { - val editable = editableFields(state).map { it.name }.toSet() - val values = state.suggestion.entry.values - - return state.schema.schema.fields.filter { it.name !in editable && values[it.name].orEmpty().isNotEmpty() } - } - - fun factory( - activeUserPublicKey: HexKey, - chatRoomId: String, - relayHint: String?, - identifier: String, - suggestionId: String, - initialAcceptCuratedSuggestionUIState: AcceptCuratedSuggestionUIState = - AcceptCuratedSuggestionUIState.Loading, - nostrRepository: NostrRepository, - chatRepository: ChatRepository, - frostSigningRepository: FrostSigningRepository - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - AcceptCuratedSuggestionViewModel( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint, - identifier = identifier, - suggestionId = suggestionId, - initialAcceptCuratedSuggestionUIState = initialAcceptCuratedSuggestionUIState, - nostrRepository = nostrRepository, - chatRepository = chatRepository, - frostSigningRepository = frostSigningRepository - ) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/BroadcastGroupSignedEventViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/BroadcastGroupSignedEventViewModel.kt index e9997409..86c5e8f7 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/BroadcastGroupSignedEventViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/BroadcastGroupSignedEventViewModel.kt @@ -33,12 +33,9 @@ import com.machankura.bennu.compose.network.relays.EventPublishTransport import com.machankura.bennu.compose.network.relays.NostrPublishResult import com.machankura.bennu.compose.network.relays.RelayPool import com.machankura.bennu.compose.network.sockets.NostrIncomingMessage -import com.machankura.bennu.compose.nostr.GroupCuratedSchema import com.machankura.bennu.compose.nostr.GroupRelayList import com.machankura.bennu.compose.nostr.GroupRelaySet import com.machankura.bennu.compose.nostr.Relays -import com.machankura.bennu.compose.nostr.curated.CuratedEntryEvent -import com.machankura.bennu.compose.nostr.curated.CuratedSchemaEvent import com.machankura.bennu.compose.repository.ChatRepository import com.machankura.bennu.compose.ui.view.state.BroadcastGroupSignedEventUIState import kotlin.time.Duration.Companion.milliseconds @@ -74,9 +71,8 @@ import kotlin.time.Duration.Companion.milliseconds * ### Where the relays come from * * [defaultRelaysFor]: the group's own General list where it has agreed one, the - * app's publish set where it has not, plus the indexers for a relay list and the - * list's own relays for a schema and for an entry into it, minus anything the - * group has blocked. The member can add and remove before sending, and the + * app's publish set where it has not, plus the indexers for a relay list, minus + * anything the group has blocked. The member can add and remove before sending, and the * seeded list is a suggestion rather than a rule. */ class BroadcastGroupSignedEventViewModel( @@ -189,7 +185,6 @@ class BroadcastGroupSignedEventViewModel( localChatRoom = localChatRoom, signedEvent = signedEvent, relayLists = chatRepository.groupRelayLists(chatRoomId), - schemas = chatRepository.groupCuratedSchemas(chatRoomId), ) } } @@ -206,14 +201,11 @@ class BroadcastGroupSignedEventViewModel( fun seedRelays( relayLists: List, kind: Kind, - tags: Array>, - content: String, - schemas: List = emptyList(), ) { if (isSeeded) return isSeeded = true - relays.addAll(defaultRelaysFor(relayLists, kind, tags, content, schemas)) + relays.addAll(defaultRelaysFor(relayLists, kind)) } fun clearAddFailure() { @@ -434,19 +426,10 @@ class BroadcastGroupSignedEventViewModel( * The group's General list is the answer NIP-65 gives -- its write relays, * where it has agreed any -- and the app's own publish set stands in for a * group that has not, since a list of nothing would make the button a - * no-op on every group until somebody edits it. Two kinds add to that: - * - * - A relay list goes to the indexers as well. The list says where to find - * the group, so sending it only to the relays it names is circular -- a - * reader who already knew those relays would not need the list. - * - A curated schema goes to the relays it names for its own replies, so a - * client reading suggestions there finds what they are replying to. - * - * - An entry into a curated list goes to the same relays as its schema, - * which the NIP makes a MUST: that is where the list's readers look, - * and where the queue screen reads the entry back to mark the - * suggestion it came from. The entry names its schema by coordinate, - * so the relays are read off the group's own copy of it in [schemas]. + * no-op on every group until somebody edits it. A relay list goes to the + * indexers as well: the list says where to find the group, so sending it + * only to the relays it names is circular -- a reader who already knew + * those relays would not need the list. * * And nothing goes to a relay the group has blocked, whatever the other * lists say; that is what a blocked list is for. @@ -454,9 +437,6 @@ class BroadcastGroupSignedEventViewModel( fun defaultRelaysFor( relayLists: List, kind: Kind, - tags: Array> = emptyArray(), - content: String = "", - schemas: List = emptyList(), ): List { val general = relayLists.firstOrNull { it.set == GroupRelaySet.General } ?.relays.orEmpty() @@ -471,26 +451,12 @@ class BroadcastGroupSignedEventViewModel( emptyList() } - val schemaRelays = when (kind) { - CuratedSchemaEvent.KIND -> - runCatching { CuratedSchemaEvent.read(tags, content).relays } - .getOrDefault(emptyList()) - .mapNotNull { GroupRelaySet.relayUrlOrNull(it) } - - CuratedEntryEvent.CANONICAL_KIND -> - schemas.firstOrNull { it.isRepliedToBy(tags) } - ?.schema?.relays.orEmpty() - .mapNotNull { GroupRelaySet.relayUrlOrNull(it) } - - else -> emptyList() - } - val blocked = relayLists.firstOrNull { it.set == GroupRelaySet.Blocked } ?.relays.orEmpty() .map { it.url } .toSet() - return (where + indexers + schemaRelays).distinct().filterNot { it in blocked } + return (where + indexers).distinct().filterNot { it in blocked } } fun factory( diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChatRoomDetailViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChatRoomDetailViewModel.kt index 23c1cfaa..a7f77e8b 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChatRoomDetailViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChatRoomDetailViewModel.kt @@ -97,8 +97,6 @@ class ChatRoomDetailViewModel( groupNostrProfile = chatRepository.groupNostrProfile(chatRoomId), groupRelayLists = chatRepository.groupRelayLists(chatRoomId), groupPosts = chatRepository.groupPosts(chatRoomId), - groupCuratedSchemas = chatRepository.groupCuratedSchemas(chatRoomId), - groupCuratedEntries = chatRepository.groupCuratedEntries(chatRoomId), groupWallet = chatRepository.groupWallet(chatRoomId, NodeParamsManager.chain), canEditNostrProfile = canSign, canAddSubgroup = canSign, diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/CuratedSuggestionListViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/CuratedSuggestionListViewModel.kt deleted file mode 100644 index 0b6ed93e..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/CuratedSuggestionListViewModel.kt +++ /dev/null @@ -1,257 +0,0 @@ -package com.machankura.bennu.compose.ui.view.model - -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import androidx.lifecycle.ViewModel -import androidx.lifecycle.ViewModelProvider -import androidx.lifecycle.viewModelScope -import androidx.lifecycle.viewmodel.initializer -import androidx.lifecycle.viewmodel.viewModelFactory -import co.touchlab.kermit.Logger -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.IO -import kotlinx.coroutines.Job -import kotlinx.coroutines.delay -import kotlinx.coroutines.flow.distinctUntilChanged -import kotlinx.coroutines.launch -import kotlinx.coroutines.sync.Mutex -import kotlinx.coroutines.sync.withLock -import com.machankura.bennu.compose.database.model.SynchronizeNostrEventRequest -import com.machankura.bennu.compose.nostr.CuratedSuggestion -import com.machankura.bennu.compose.nostr.GroupCuratedSchema -import com.machankura.bennu.compose.nostr.GroupRelayList -import com.machankura.bennu.compose.nostr.GroupRelaySet -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.NostrRepository -import com.machankura.bennu.compose.ui.view.state.CuratedSuggestionListUIState -import kotlin.time.Duration.Companion.seconds - -/** - * The queue of one list the group curates, read off the relays the schema - * names. - * - * A pull, the way every one-off read in this app is: a request row per relay - * for the sync pump to drain, and a watch on the local table for what comes - * back. Nothing here talks to a relay itself. What the screen shows is - * therefore what this device has *stored* for the coordinate, which is also - * what it shows with no network at all -- and what it showed last time, until - * the relays answer again. - * - * ### Where the queue is read from - * - * The schema's `relay` tags, first. They are signed into the schema for exactly - * this: a client that finds the list anywhere knows where its replies live and - * cannot be sent elsewhere by an unsigned config. A schema that names none -- - * the NIP allows it and says a client may then pick its own -- is read from - * the group's general relay list, which is where the group said it publishes, - * and failing that from this build's default. The screen says which. - * - * ### What "still looking" means - * - * The pump marks a request sent when it goes out and processed when an event - * comes back, and a relay holding nothing for the coordinate answers with an - * EOSE the pump does not record. So there is no signal for "asked and empty", - * and the screen would otherwise call every list empty for the second before - * its rows arrived. [ASK_TIMEOUT] stands in: the queue is being asked until - * something lands or the wait runs out, and after that an empty queue is - * empty. The reference client does the same with a six-second timer. - */ -class CuratedSuggestionListViewModel( - val chatRoomId: String, - val activeUserPublicKey: HexKey, - val relayHint: String?, - /** The `d` of the schema whose queue this is. */ - val identifier: String, - initialCuratedSuggestionListUIState: CuratedSuggestionListUIState, - val nostrRepository: NostrRepository, - val chatRepository: ChatRepository, -): ViewModel() { - - var curatedSuggestionListUIState: CuratedSuggestionListUIState by mutableStateOf( - initialCuratedSuggestionListUIState - ) - private set - - private val logger = Logger.withTag(TAG) - - /** - * Serialises the read-modify-write on the state. The watch, the timer and - * a re-ask each update one field of it from their own coroutine, and a copy - * taken by one and written after another's is a lost update. - */ - private val stateMutex = Mutex() - - private var askTimeout: Job? = null - - fun initiate() { - viewModelScope.launch(Dispatchers.IO) { - val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) - if (localChatRoom == null) { - curatedSuggestionListUIState = CuratedSuggestionListUIState.Error("Couldn't find the group") - return@launch - } - - // Opened on a schema this device does not hold: nothing to ask for, - // since the coordinate is the group's key and the identifier and - // half of that came from a screen that no longer agrees. - val schema = chatRepository.groupCuratedSchemas(chatRoomId).firstOrNull { it.identifier == identifier } - if (schema == null) { - curatedSuggestionListUIState = CuratedSuggestionListUIState.Error("Couldn't find that schema") - return@launch - } - - val relays = relaysToAsk( - schema = schema, - general = chatRepository.groupRelayLists(chatRoomId).firstOrNull { it.set == GroupRelaySet.General }, - ) - - curatedSuggestionListUIState = CuratedSuggestionListUIState.Loaded( - localChatRoom = localChatRoom, - schema = schema, - relays = relays, - isAsking = true, - ) - - ask(schema, relays) - watch(schema) - } - } - - /** - * Asks the relays again, for a member who believes something is missing. - * - * The one thing the watch does not do on its own: it shows what arrives, - * and this is how more is made to arrive. Idempotent on the stored rows -- - * an event already held is upserted, not duplicated. - */ - fun askAgain() { - val loaded = curatedSuggestionListUIState as? CuratedSuggestionListUIState.Loaded ?: return - - viewModelScope.launch(Dispatchers.IO) { - update { it.copy(isAsking = true) } - ask(loaded.schema, loaded.relays) - } - } - - private suspend fun ask(schema: GroupCuratedSchema, relays: List) { - logger.d("Asking ${relays.size} relay(s) for the queue of ${schema.coordinate()}") - - nostrRepository.queueSynchronizeNostrEvent(requestsFor(schema, relays)) - - askTimeout?.cancel() - askTimeout = viewModelScope.launch(Dispatchers.IO) { - delay(ASK_TIMEOUT) - update { it.copy(isAsking = false) } - } - } - - /** - * Watches the stored rows for the coordinate for as long as the screen - * lives, re-reading the queue whole on every change. Whole rather than - * incrementally because the reading is a merge -- newest per coordinate, - * curated by identifier -- and a merge over a delta is a different reading. - */ - private suspend fun watch(schema: GroupCuratedSchema) { - nostrRepository.observeNostrEventsMatching(schema.queueReadFilter()) - .distinctUntilChanged() - .collect { events -> - val queue = CuratedSuggestion.queueOf(schema, events) - logger.d("${queue.size} suggestion(s) to ${schema.coordinate()} among ${events.size} stored event(s)") - - update { loaded -> withQueue(loaded, queue) } - } - } - - private suspend fun update( - change: (CuratedSuggestionListUIState.Loaded) -> CuratedSuggestionListUIState.Loaded - ) { - stateMutex.withLock { - val loaded = curatedSuggestionListUIState as? CuratedSuggestionListUIState.Loaded ?: return - curatedSuggestionListUIState = change(loaded) - } - } - - companion object { - private const val TAG = "CuratedSuggestionListViewModel" - - /** - * The schema's relays, else the group's, else the default. See the - * class note for why in that order. Normalised so that two spellings - * of one relay are one request, and only the group's *read* relays, - * since this is a read. - * - * [general] is the group's general relay list as the screen has it, or - * null in a room that has none of that to say. An agreed-but-empty - * list falls through to the default rather than asking nobody: the - * group withdrew where it publishes, not where its lists are read. - */ - internal fun relaysToAsk(schema: GroupCuratedSchema, general: GroupRelayList?): List { - val named = schema.schema.relays.mapNotNull { RelayUrlNormalizer.normalizeOrNull(it)?.url }.distinct() - if (named.isNotEmpty()) return named - - val relays = general?.takeIf { it.isAgreed }?.relays ?: GroupRelaySet.General.defaults() - - return relays.filter { it.read }.map { it.url.url }.distinct() - .ifEmpty { GroupRelaySet.General.defaults().map { it.url.url } } - } - - /** One request per relay, each carrying the NIP's two queries for the coordinate. */ - internal fun requestsFor(schema: GroupCuratedSchema, relays: List): List = - relays.map { relayUrl -> - SynchronizeNostrEventRequest( - purpose = PURPOSE, - synchronizationFilters = schema.queueFilters(), - relayURL = relayUrl, - level = 0, - ) - } - - /** - * The state once [queue] has been read off the stored rows. Something - * arriving means the relays have answered, so the asking ends there; - * nothing arriving leaves it to the timer. - */ - internal fun withQueue( - loaded: CuratedSuggestionListUIState.Loaded, - queue: List, - ): CuratedSuggestionListUIState.Loaded = loaded.copy( - suggestions = queue, - isAsking = loaded.isAsking && queue.isEmpty(), - ) - - /** The purpose the sync rows are filed under, for anything that counts them. */ - const val PURPOSE = "curated-queue" - - /** - * How long an empty queue is "being asked" before it is called empty. - * Longer than the reference client's six seconds because the request - * queues behind the pump's four subscription slots before it goes out. - */ - internal val ASK_TIMEOUT = 10.seconds - - fun factory( - chatRoomId: String, - activeUserPublicKey: HexKey, - relayHint: String?, - identifier: String, - initialCuratedSuggestionListUIState: CuratedSuggestionListUIState = CuratedSuggestionListUIState.Loading, - nostrRepository: NostrRepository, - chatRepository: ChatRepository, - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - CuratedSuggestionListViewModel( - chatRoomId = chatRoomId, - activeUserPublicKey = activeUserPublicKey, - relayHint = relayHint, - identifier = identifier, - initialCuratedSuggestionListUIState = initialCuratedSuggestionListUIState, - nostrRepository = nostrRepository, - chatRepository = chatRepository, - ) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/EditGroupCuratedSchemaViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/EditGroupCuratedSchemaViewModel.kt deleted file mode 100644 index 316936bf..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/EditGroupCuratedSchemaViewModel.kt +++ /dev/null @@ -1,576 +0,0 @@ -package com.machankura.bennu.compose.ui.view.model - -import androidx.compose.runtime.MutableState -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateListOf -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import androidx.lifecycle.ViewModel -import androidx.lifecycle.ViewModelProvider -import androidx.lifecycle.viewModelScope -import androidx.lifecycle.viewmodel.initializer -import androidx.lifecycle.viewmodel.viewModelFactory -import co.touchlab.kermit.Logger -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.extensions.bech32ToHexOrNull -import com.machankura.bennu.compose.nostr.GroupCuratedSchema -import com.machankura.bennu.compose.nostr.GroupRelaySet -import com.machankura.bennu.compose.nostr.curated.CuratedField -import com.machankura.bennu.compose.nostr.curated.CuratedFieldType -import com.machankura.bennu.compose.nostr.curated.CuratedSchema -import com.machankura.bennu.compose.nostr.curated.CuratedSchemaEvent -import com.machankura.bennu.compose.nostr.curated.CuratedSchemaProblem -import com.machankura.bennu.compose.nostr.curated.CuratedSchemaTemplate -import com.machankura.bennu.compose.nostr.curated.CuratedUnsupportedField -import com.machankura.bennu.compose.nostr.curated.CuratedVisibility -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.ui.view.state.EditGroupCuratedSchemaUIState -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.IO -import kotlinx.coroutines.launch - -/** - * One of the group's curated schemas, edited locally and proposed as one event. - * - * Nothing here is saved. The parts of the schema that are lists -- its fields, - * its rules, its suggesters, its relays -- live on this view model as snapshot - * state so that a bottom sheet opening over the form, or the window turning, - * does not throw an edit away; the identity fields are text and live in the - * composition like every other form's. The button folds both halves into a - * [CuratedSchema], refuses it for any reason a reader would, and otherwise opens - * one signing session over it. The schema changes on every member's device at - * once, when a quorum has signed, or not at all. - * - * ### Edit and replace - * - * Kind 31889 is addressable, so proposing a schema under an identifier the group - * already signed one for *replaces* it -- which is what an edit is, and why the - * identifier is the one thing the editor will not let an edit change. A new - * identifier is a new list, with a queue of its own, and the group's screen - * offers that as adding a schema rather than as editing this one. - * - * ### Starting from a template - * - * A new schema is seeded from a [CuratedSchemaTemplate] -- curare.to's four - * shapes, chosen on the screen before this one and named by [template] -- so - * that the form opens on a list's worth of fields rather than on the two every - * list has, and so that the identifier field records how a client derives an - * entry's `d`, which is what lets that site's form post to a list started here. - * The template decides only what the working copy starts as: it is not kept, - * and nothing about the schema remembers which one it came from. - * - * The comparison for "nothing changed" is against the schema as the group signed - * it, normalized on both sides, because re-signing an identical schema would put - * a second statement on the record with a newer timestamp: harmless, since the - * kind is replaceable, and still a lie about when the group last decided - * anything about the list. - */ -class EditGroupCuratedSchemaViewModel( - val chatRoomId: String, - val activeUserPublicKey: HexKey, - val relayHint: String?, - /** The `d` of the schema being edited, or null for a new one. */ - val identifier: String?, - /** - * The key of the [CuratedSchemaTemplate] a new schema starts from; see - * [CuratedSchemaTemplate.byKey] for what null and an unknown key get. Not - * read on an edit, which starts from the schema itself. - */ - val template: String? = null, - initialEditGroupCuratedSchemaUIState: EditGroupCuratedSchemaUIState, - val chatRepository: ChatRepository, - val frostSigningRepository: FrostSigningRepository, -): ViewModel() { - - var editGroupCuratedSchemaUIState: EditGroupCuratedSchemaUIState by mutableStateOf( - initialEditGroupCuratedSchemaUIState - ) - private set - - private val logger = Logger.withTag(TAG) - - val isActionPending: MutableState = mutableStateOf(false) - - /** Who may suggest. Always set: the editor never proposes a schema without one. */ - var visibility: CuratedVisibility by mutableStateOf(CuratedVisibility.Public) - private set - - /** The working copy of the schema's fields, in the order they will be written. */ - val fields = mutableStateListOf() - - /** - * The fields of an existing schema this build cannot show, carried through - * unchanged so that an edit here does not sign them away. Not state: the - * editor has no control over them, which is the point. - */ - private val unsupportedFields = mutableListOf() - - /** - * The working copy of the `require-any` rules, each a set of field names. - * - * A rule may hold fewer than two names while it is being built; one that - * still does when the button is pressed says nothing and is dropped rather - * than refused -- see `CuratedSchema.requireAny`. - */ - val requireAny = mutableStateListOf>() - - /** The working copy of the `p` tags: pubkeys besides the group that may suggest. */ - val suggesters = mutableStateListOf() - - /** The working copy of the `relay` tags. */ - val relays = mutableStateListOf() - - /** The field the sheet is open on, or null while it is closed. */ - var editingField: FieldEdit? by mutableStateOf(null) - private set - - /** - * Why the last proposal did not go out, or nothing. Set by the button and - * left showing until the next press, since the button is the thing that - * will clear it. - */ - var problems: List by mutableStateOf(emptyList()) - private set - - /** Why the last relay was refused, or null. Cleared by the next keystroke. */ - var addRelayFailure: AddRelayFailure? by mutableStateOf(null) - private set - - /** Why the last suggester was refused, or null. Cleared by the next keystroke. */ - var addSuggesterFailure: AddSuggesterFailure? by mutableStateOf(null) - private set - - private var isSeeded = false - - /** - * A field on the sheet. [index] is its place in [fields], or null for one - * being added -- which is also what decides whether committing it appends - * or replaces. - */ - data class FieldEdit(val index: Int?, val field: CuratedField) - - enum class AddRelayFailure { - /** Not a `wss://` URL, or one pointing at this machine. */ - NotARelay, - - /** Already named, which is a no-op rather than a mistake. */ - AlreadyListed, - } - - enum class AddSuggesterFailure { - /** Neither an npub nor 64 hex characters. */ - NotAPubkey, - - AlreadyListed, - } - - /** Why a field cannot be committed as it stands. */ - enum class FieldProblem { - NameMissing, - - /** A field name is the key a form collects a value under, and a key is one word. */ - NameHasSpaces, - - /** Another field already answers to that name. */ - NameTaken, - } - - fun initiateEditGroupCuratedSchema() { - viewModelScope.launch(Dispatchers.IO) { - val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) - - editGroupCuratedSchemaUIState = if (localChatRoom == null) { - EditGroupCuratedSchemaUIState.Error("Couldn't find the chat room") - } else { - val existing = identifier?.let { wanted -> - chatRepository.groupCuratedSchemas(chatRoomId).firstOrNull { it.identifier == wanted } - } - - if (identifier != null && existing == null) { - // Opened on a schema this device does not hold. Nothing to - // retry and nothing to edit; offering a blank form under that - // identifier would propose a replacement for a list nobody - // here has read. - EditGroupCuratedSchemaUIState.Error("Couldn't find that schema") - } else { - EditGroupCuratedSchemaUIState.Loaded( - localChatRoom = localChatRoom, - existing = existing, - defaultRelays = defaultRelays(chatRoomId), - canSign = localChatRoom.chatRoom.mlsGroupState != null && - frostSigningRepository.canSign(chatRoomId), - ) - } - } - } - } - - /** - * Where a new schema says its list lives: the relays the group has said it - * writes to, since that is where its canonical entries would be read from. - * - * The NIP-65 list where the group has agreed one, else that set's defaults - * -- which is this build's own relay, and the same thing a group opening the - * relay editor for the first time is shown. A schema with no relays is one - * whose suggestions could go anywhere, so the seed is worth getting right. - */ - private suspend fun defaultRelays(chatRoomId: String): List { - val general = chatRepository.groupRelayLists(chatRoomId) - .firstOrNull { it.set == GroupRelaySet.General } - ?: return GroupRelaySet.General.defaults().map { it.url.url } - - return (if (general.isAgreed) general.relays else general.set.defaults()) - .filter { it.write } - .map { it.url.url } - } - - /** - * Fills the working copy from the schema the group signed, once. - * - * An existing schema starts at itself. A new one starts at its [template]'s - * fields and rules -- every template carrying the identifier and the title, - * which `CuratedSchema.normalized` would put back anyway, shown up front so - * that what the member sees is what the group will sign -- and at the - * group's own relays. - * - * Called from the screen rather than from [initiateEditGroupCuratedSchema], - * because the loader is not the only way a loaded state arrives: a preview - * and a layout test both hand one straight in. Runs once, so the effect that - * calls it re-firing does not undo an edit. - */ - fun seedWorkingCopy(state: EditGroupCuratedSchemaUIState.Loaded) { - if (isSeeded) return - isSeeded = true - - val schema = state.existing?.schema - if (schema != null) { - visibility = schema.visibility ?: CuratedVisibility.Public - fields.addAll(schema.fields) - unsupportedFields.addAll(schema.unsupportedFields) - requireAny.addAll(schema.requireAny) - suggesters.addAll(schema.suggesters) - relays.addAll(schema.relays) - } else { - val shape = CuratedSchemaTemplate.byKey(template) - visibility = CuratedVisibility.Public - fields.addAll(shape.fields) - requireAny.addAll(shape.requireAny) - relays.addAll(state.defaultRelays) - } - } - - fun selectVisibility(visibility: CuratedVisibility) { - this.visibility = visibility - } - - /** - * Whether [field] is one of the two every list must have. - * - * Decided by the tag it writes to, not its name, because that is what the - * NIP's rule is about: a list needs a field writing to `d` and one writing - * to `title`, whatever they are called. Such a field cannot be removed or - * made optional here -- `CuratedSchema.normalized` would only put it back. - */ - fun isMandatory(field: CuratedField): Boolean = - CuratedField.MANDATORY.any { (tag, _) -> field.tag() == tag } - - /** Opens the sheet on a blank field. Text, because most fields are. */ - fun startAddingField() { - editingField = FieldEdit( - index = null, - field = CuratedField(name = "", type = CuratedFieldType.Text, isRequired = false), - ) - } - - fun startEditingField(index: Int) { - fields.getOrNull(index)?.let { editingField = FieldEdit(index = index, field = it) } - } - - fun dismissFieldEditor() { - editingField = null - } - - /** - * Puts [field] into the working copy at the place the sheet was opened on, - * or says why it cannot. - * - * Null means it went in and the sheet is closed. A rename follows through to - * the rules that named the field, since a rule naming a field that no longer - * exists would silently never be satisfied. - */ - fun commitField(field: CuratedField): FieldProblem? { - val edit = editingField ?: return null - - val name = field.name.trim() - if (name.isEmpty()) return FieldProblem.NameMissing - if (name.any { it.isWhitespace() }) return FieldProblem.NameHasSpaces - if (fields.withIndex().any { (index, other) -> index != edit.index && other.name == name }) { - return FieldProblem.NameTaken - } - - val committed = field.copy(name = name) - - if (edit.index == null) { - fields.add(committed) - } else { - val previous = fields[edit.index] - fields[edit.index] = committed - if (previous.name != name) { - requireAny.indices.forEach { group -> - requireAny[group] = requireAny[group].map { if (it == previous.name) name else it } - } - } - } - - editingField = null - return null - } - - /** Drops the field at [index] and takes it out of any rule that named it. */ - fun removeField(index: Int) { - val removed = fields.getOrNull(index) ?: return - if (isMandatory(removed)) return - - fields.removeAt(index) - requireAny.indices.forEach { group -> - requireAny[group] = requireAny[group].filterNot { it == removed.name } - } - editingField = null - } - - fun addRequireAnyGroup() { - requireAny.add(emptyList()) - } - - fun toggleRequireAny(group: Int, fieldName: String) { - val names = requireAny.getOrNull(group) ?: return - requireAny[group] = if (fieldName in names) names - fieldName else names + fieldName - } - - fun removeRequireAnyGroup(group: Int) { - if (group in requireAny.indices) requireAny.removeAt(group) - } - - /** - * Adds [input] to the suggesters, or says why it did not. - * - * True when the row appeared, which is the caller's cue to clear the field. - */ - fun addSuggester(input: String): Boolean { - val pubkey = pubkeyOrNull(input) ?: run { - addSuggesterFailure = AddSuggesterFailure.NotAPubkey - return false - } - - if (pubkey in suggesters) { - addSuggesterFailure = AddSuggesterFailure.AlreadyListed - return false - } - - suggesters.add(pubkey) - addSuggesterFailure = null - return true - } - - fun removeSuggester(pubkey: HexKey) { - suggesters.remove(pubkey) - } - - fun clearAddSuggesterFailure() { - addSuggesterFailure = null - } - - /** - * Adds [url] to the relays, or says why it did not. - * - * Held to the same rule as the group's relay lists -- `wss://`, not this - * machine -- rather than to the NIP's looser one, because this is a relay - * the group is about to sign for strangers to publish to. See - * `GroupRelaySet.relayUrlOrNull`. - */ - fun addRelay(url: String): Boolean { - val relay = GroupRelaySet.relayUrlOrNull(url) ?: run { - addRelayFailure = AddRelayFailure.NotARelay - return false - } - - // Compared normalized, because a relay signed into an existing schema is - // kept as it was written and the normalizer adds a trailing slash: the - // same host with and without one is one relay, not two. - if (relays.any { GroupRelaySet.relayUrlOrNull(it) == relay }) { - addRelayFailure = AddRelayFailure.AlreadyListed - return false - } - - relays.add(relay.url) - addRelayFailure = null - return true - } - - fun removeRelay(url: String) { - relays.remove(url) - } - - fun clearAddRelayFailure() { - addRelayFailure = null - } - - /** - * The schema as the form has it: the text fields trimmed and the lists as - * they stand, with a rule too short to mean anything left out. - */ - fun draft( - identifier: String, - title: String, - name: String, - description: String, - picture: String, - domain: String, - ): CuratedSchema = CuratedSchema( - identifier = identifier.trim(), - title = title.trim(), - name = name.trim(), - description = description.trim(), - visibility = visibility, - picture = picture.trim().ifEmpty { null }, - domain = domain.trim().ifEmpty { null }?.let(CuratedSchemaEvent::normalizeDomain), - fields = fields.toList(), - unsupportedFields = unsupportedFields.toList(), - requireAny = requireAny.filter { it.size > 1 }, - suggesters = suggesters.toList(), - relays = relays.toList(), - ) - - /** - * Opens a session over the schema, or says why not. - * - * Three refusals before anything is proposed and each is the caller's to - * say: a schema a reader would reject, which is [onInvalid] with the - * reasons; an edit that changed nothing, which is [onNothingToPropose]; and - * a proposal that could not be opened, which is [onFailure]. All of them - * stay on the form with the edits still in it. - */ - fun proposeSchema( - localChatRoom: LocalChatRoom, - existing: GroupCuratedSchema?, - identifier: String, - title: String, - name: String, - description: String, - picture: String, - domain: String, - onSuccess: (sessionId: String) -> Unit, - onInvalid: () -> Unit, - onNothingToPropose: () -> Unit, - onFailure: () -> Unit - ) { - // Guard against double submits. Two sessions over two versions of one - // schema would leave the list's form decided by whichever quorum - // finished last. - if (isActionPending.value) return - - val schema = draft( - // The identifier of an existing schema is the coordinate every - // suggestion to it replies to, so an edit keeps it whatever the - // field says -- and the field is read-only to say so. - identifier = existing?.identifier ?: identifier, - title = title, - name = name, - description = description, - picture = picture, - domain = domain, - ) - - problems = schema.problems() - if (problems.isNotEmpty()) { - onInvalid.invoke() - return - } - - if (existing != null && existing.schema == schema.normalized()) { - onNothingToPropose.invoke() - return - } - - isActionPending.value = true - - val template = GroupCuratedSchema.template(schema) - - viewModelScope.launch(Dispatchers.IO) { - val session = runCatching { - frostSigningRepository.proposeSigning( - localChatRoom = localChatRoom, - userPublicKey = activeUserPublicKey, - kind = template.kind, - tags = template.tags, - content = template.content, - ) - }.onFailure { error -> - logger.e("Failed to propose a curated schema for $chatRoomId", error) - }.getOrNull() - - viewModelScope.launch(Dispatchers.Main) { - if (session != null) { - onSuccess.invoke(session.id) - } else { - onFailure.invoke() - } - } - - isActionPending.value = false - } - } - - companion object { - private const val TAG = "EditGroupCuratedSchemaViewModel" - - /** - * [input] as a pubkey the schema could name, or null. - * - * An npub -- with or without a `nostr:` in front, the way it is pasted - * from most clients -- or 64 hex characters in either case. Nothing else, - * and in particular not a NIP-05 address, since resolving one is a - * network round trip and this is a field on a form. - */ - fun pubkeyOrNull(input: String): HexKey? { - val trimmed = input.trim().removePrefix("nostr:") - - val hex = if (trimmed.startsWith("npub1", ignoreCase = true)) { - trimmed.bech32ToHexOrNull() - } else { - trimmed.lowercase() - } - - return hex?.takeIf { candidate -> - candidate.length == 64 && candidate.all { it in '0'..'9' || it in 'a'..'f' } - } - } - - fun factory( - activeUserPublicKey: HexKey, - chatRoomId: String, - relayHint: String?, - identifier: String?, - template: String? = null, - initialEditGroupCuratedSchemaUIState: EditGroupCuratedSchemaUIState = - EditGroupCuratedSchemaUIState.Loading, - chatRepository: ChatRepository, - frostSigningRepository: FrostSigningRepository - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - EditGroupCuratedSchemaViewModel( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint, - identifier = identifier, - template = template, - initialEditGroupCuratedSchemaUIState = initialEditGroupCuratedSchemaUIState, - chatRepository = chatRepository, - frostSigningRepository = frostSigningRepository - ) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupCuratedEntriesViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupCuratedEntriesViewModel.kt deleted file mode 100644 index 8e491817..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupCuratedEntriesViewModel.kt +++ /dev/null @@ -1,232 +0,0 @@ -package com.machankura.bennu.compose.ui.view.model - -import androidx.compose.runtime.MutableState -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateMapOf -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import androidx.lifecycle.ViewModel -import androidx.lifecycle.ViewModelProvider -import androidx.lifecycle.viewModelScope -import androidx.lifecycle.viewmodel.initializer -import androidx.lifecycle.viewmodel.viewModelFactory -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.IO -import kotlinx.coroutines.Job -import kotlinx.coroutines.launch -import com.machankura.bennu.compose.network.relays.EventPublishTransport -import com.machankura.bennu.compose.nostr.GroupCuratedEntry -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.ui.view.model.BroadcastGroupSignedEventViewModel.RelayOutcome -import com.machankura.bennu.compose.ui.view.state.GroupCuratedEntriesUIState - -/** - * The entries the group has accepted into its lists, read once for the screen - * that shows them. One read rather than a watch, for the reason - * `GroupNostrProfileViewModel` gives. Nothing here asks whether this device - * can sign, because nothing on the screen would change if it could. - * - * ### Broadcast all - * - * The one thing the screen does besides show: [broadcastAll] sends every - * entry, one after another, each to the relays its own broadcast screen would - * have filled in -- `defaultRelaysFor`, read against the group's relay lists - * and the entry's own schema -- and says under each card what its relays - * answered. The member sees nothing before pressing, which is the difference - * from sending one at a time: that screen exists so the relays can be read - * and changed first, and this button is for the member who has read them - * once and has twenty entries to send. The seeded list is what a member who - * reads nothing and presses the button sends to there too. - * - * One entry at a time rather than all at once, for two reasons. The rows fill - * in top to bottom, so the member can see where the batch is; and a public - * relay sent twenty events in one burst answers "rate-limited" to most of - * them, which would make the button worse than the twenty presses it saves. - * Each entry's send is bounded by the same ceiling as a single broadcast, - * and the whole batch by nothing but that, since a long list is meant to - * take a while. It goes to the pool directly rather than through the queue, - * for the reason `BroadcastGroupSignedEventViewModel` gives, and it is only - * as durable as the button press: leaving the screen ends it where it is. - */ -class GroupCuratedEntriesViewModel( - val chatRoomId: String, - initialGroupCuratedEntriesUIState: GroupCuratedEntriesUIState, - val chatRepository: ChatRepository, - val publishTransport: EventPublishTransport, -): ViewModel() { - - var groupCuratedEntriesUIState: GroupCuratedEntriesUIState by mutableStateOf( - initialGroupCuratedEntriesUIState - ) - private set - - val isActionPending: MutableState = mutableStateOf(false) - - /** - * How each entry's send went the last time the button was pressed, keyed - * by the signed event's id. An entry the batch has not reached yet has - * none, which is how the screen tells "not yet" from "sending". - */ - val entryBroadcasts = mutableStateMapOf() - - /** - * Where the last press has got to, or null before the first one. - * - * On the screen rather than in a snackbar, for the reason the one-event - * screen gives: it is the answer the member came for, and it should still - * be there once the cards under it have been read. Cleared when the next - * press starts. - */ - var broadcastAllProgress: BroadcastAllProgress? by mutableStateOf(null) - private set - - /** One entry's part of one press of the button. */ - sealed interface EntryBroadcast { - /** Sent, and not every relay has answered yet. */ - data object Sending : EntryBroadcast - - /** - * Not sent, because there was nowhere to send it: everything the seed - * rule would have named is on the group's blocked list. The one-event - * screen meets the same case as an empty list and a snackbar. - */ - data object NoRelays : EntryBroadcast - - /** Every relay has answered, or been given up on. */ - data class Sent(val outcomes: Map) : EntryBroadcast { - val accepted: Int get() = outcomes.count { it.value == RelayOutcome.Accepted } - - val asked: Int get() = outcomes.size - - val isAcceptedEverywhere: Boolean get() = accepted == asked - - /** - * The relays that did not say OK, with what they said instead, in - * the order they were asked. Named under the count because the - * relay's reason is what a member can act on, and a count is not. - */ - val refusals: List> - get() = outcomes.filterValues { it != RelayOutcome.Accepted }.toList() - } - } - - /** How far the last press has got, and then how it went. */ - sealed interface BroadcastAllProgress { - /** Entry [entry] of [total] is out, counting from one. */ - data class Sending(val entry: Int, val total: Int) : BroadcastAllProgress - - /** - * Every entry has been sent, and [acceptedEverywhere] of [total] were - * accepted by every relay they went to. The rest say under their own - * cards which relay refused, and why. - */ - data class Done(val acceptedEverywhere: Int, val total: Int) : BroadcastAllProgress - } - - fun initiate() { - viewModelScope.launch(Dispatchers.IO) { - val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) - - groupCuratedEntriesUIState = if (localChatRoom == null) { - GroupCuratedEntriesUIState.Error("Couldn't find the group") - } else { - GroupCuratedEntriesUIState.Loaded( - localChatRoom = localChatRoom, - groupCuratedEntries = chatRepository.groupCuratedEntries(chatRoomId), - relayLists = chatRepository.groupRelayLists(chatRoomId), - ) - } - } - } - - /** - * Sends every entry on the screen, in the order it shows them, and records - * what each one's relays said. - * - * Returns the batch, for a caller that has to wait for it, and null when - * nothing was sent: a press while one is already out, or a screen with no - * entries on it, which has no button. - */ - fun broadcastAll(): Job? { - // Guard against double submits. A second press while the first is out - // would send every entry twice and count each answer twice. - if (isActionPending.value) return null - - val state = groupCuratedEntriesUIState as? GroupCuratedEntriesUIState.Loaded ?: return null - val entries = state.groupCuratedEntries - if (entries.isEmpty()) return null - - isActionPending.value = true - broadcastAllProgress = null - entryBroadcasts.clear() - - return viewModelScope.launch(Dispatchers.IO) { - var acceptedEverywhere = 0 - - entries.forEachIndexed { index, accepted -> - broadcastAllProgress = BroadcastAllProgress.Sending(entry = index + 1, total = entries.size) - - val sent = send(accepted, state) - entryBroadcasts[accepted.signedEvent.id] = sent - if (sent is EntryBroadcast.Sent && sent.isAcceptedEverywhere) acceptedEverywhere++ - } - - broadcastAllProgress = BroadcastAllProgress.Done( - acceptedEverywhere = acceptedEverywhere, - total = entries.size, - ) - - isActionPending.value = false - } - } - - /** - * One entry, to where its own broadcast screen would have sent it. - * - * The relays are the seed rule's, read against the group's lists and the - * entry's own schema -- an entry carries the list it is in, so the rule - * is handed that one schema rather than all of the group's. - */ - private suspend fun send( - accepted: GroupCuratedEntry, - state: GroupCuratedEntriesUIState.Loaded, - ): EntryBroadcast { - val signedEvent = accepted.signedEvent - val targets = BroadcastGroupSignedEventViewModel.defaultRelaysFor( - relayLists = state.relayLists, - kind = signedEvent.kind, - tags = signedEvent.tags, - content = signedEvent.content, - schemas = listOf(accepted.list), - ) - - if (targets.isEmpty()) return EntryBroadcast.NoRelays - - entryBroadcasts[signedEvent.id] = EntryBroadcast.Sending - - return EntryBroadcast.Sent( - BroadcastGroupSignedEventViewModel.sendToRelays(publishTransport, signedEvent, targets) - ) - } - - companion object { - fun factory( - chatRoomId: String, - initialGroupCuratedEntriesUIState: GroupCuratedEntriesUIState = - GroupCuratedEntriesUIState.Loading, - chatRepository: ChatRepository, - publishTransport: EventPublishTransport, - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - GroupCuratedEntriesViewModel( - chatRoomId = chatRoomId, - initialGroupCuratedEntriesUIState = initialGroupCuratedEntriesUIState, - chatRepository = chatRepository, - publishTransport = publishTransport, - ) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupCuratedSchemasViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupCuratedSchemasViewModel.kt deleted file mode 100644 index 6b2137dd..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupCuratedSchemasViewModel.kt +++ /dev/null @@ -1,66 +0,0 @@ -package com.machankura.bennu.compose.ui.view.model - -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import androidx.lifecycle.ViewModel -import androidx.lifecycle.ViewModelProvider -import androidx.lifecycle.viewModelScope -import androidx.lifecycle.viewmodel.initializer -import androidx.lifecycle.viewmodel.viewModelFactory -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.IO -import kotlinx.coroutines.launch -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.ui.view.state.GroupCuratedSchemasUIState - -/** - * The schemas of the lists the group curates, read once for the screen that - * shows them. One read rather than a watch, for the reason - * `GroupNostrProfileViewModel` gives. - */ -class GroupCuratedSchemasViewModel( - val chatRoomId: String, - initialGroupCuratedSchemasUIState: GroupCuratedSchemasUIState, - val chatRepository: ChatRepository, -): ViewModel() { - - var groupCuratedSchemasUIState: GroupCuratedSchemasUIState by mutableStateOf( - initialGroupCuratedSchemasUIState - ) - private set - - fun initiate() { - viewModelScope.launch(Dispatchers.IO) { - val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) - - groupCuratedSchemasUIState = if (localChatRoom == null) { - GroupCuratedSchemasUIState.Error("Couldn't find the group") - } else { - GroupCuratedSchemasUIState.Loaded( - localChatRoom = localChatRoom, - groupCuratedSchemas = chatRepository.groupCuratedSchemas(chatRoomId), - canSign = localChatRoom.chatRoom.mlsGroupState != null && - chatRepository.canSign(chatRoomId), - ) - } - } - } - - companion object { - fun factory( - chatRoomId: String, - initialGroupCuratedSchemasUIState: GroupCuratedSchemasUIState = - GroupCuratedSchemasUIState.Loading, - chatRepository: ChatRepository, - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - GroupCuratedSchemasViewModel( - chatRoomId = chatRoomId, - initialGroupCuratedSchemasUIState = initialGroupCuratedSchemasUIState, - chatRepository = chatRepository, - ) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/AcceptCuratedSuggestionUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/AcceptCuratedSuggestionUIState.kt deleted file mode 100644 index db966141..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/AcceptCuratedSuggestionUIState.kt +++ /dev/null @@ -1,34 +0,0 @@ -package com.machankura.bennu.compose.ui.view.state - -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.CuratedSuggestion -import com.machankura.bennu.compose.nostr.GroupCuratedSchema - -sealed interface AcceptCuratedSuggestionUIState { - data class Loaded( - val localChatRoom: LocalChatRoom, - /** The list the entry would go into, as the group last signed it. */ - val schema: GroupCuratedSchema, - /** - * The suggestion being taken up, as the queue screen read it: the entry - * keyed by the schema's fields, who suggested it, and whether the group - * already has. The form starts as this, and the canonical entry points - * back at it. - */ - val suggestion: CuratedSuggestion, - /** - * Whether this device holds a share of the group's key. - * - * False leaves the form writable and the button inert, for the reason - * the other editors give: reading and editing cost nothing, and only a - * share-holder can open the session that would sign. - */ - val canSign: Boolean = false, - ): AcceptCuratedSuggestionUIState - - data class Error( - val message: String - ): AcceptCuratedSuggestionUIState - - data object Loading: AcceptCuratedSuggestionUIState -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/BroadcastGroupSignedEventUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/BroadcastGroupSignedEventUIState.kt index 7b9eb675..a9b4b6b0 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/BroadcastGroupSignedEventUIState.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/BroadcastGroupSignedEventUIState.kt @@ -2,7 +2,6 @@ package com.machankura.bennu.compose.ui.view.state import com.machankura.bennu.compose.database.model.GroupSignedEvent import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.GroupCuratedSchema import com.machankura.bennu.compose.nostr.GroupRelayList sealed interface BroadcastGroupSignedEventUIState { @@ -17,12 +16,6 @@ sealed interface BroadcastGroupSignedEventUIState { * `BroadcastGroupSignedEventViewModel.defaultRelaysFor`. */ val relayLists: List = emptyList(), - /** - * The lists the group curates, for an entry into one of them: the NIP - * says a canonical entry goes to its schema's relays, and the entry - * names its schema by coordinate rather than carrying the relays itself. - */ - val schemas: List = emptyList(), ): BroadcastGroupSignedEventUIState data class Error( diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ChatRoomDetailUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ChatRoomDetailUIState.kt index 2e505c04..60729548 100755 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ChatRoomDetailUIState.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ChatRoomDetailUIState.kt @@ -6,8 +6,6 @@ import com.machankura.bennu.compose.database.model.GroupKeyState import com.machankura.bennu.compose.managers.SubgroupManager import com.machankura.bennu.compose.database.model.GroupSignedEvent import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.GroupCuratedEntry -import com.machankura.bennu.compose.nostr.GroupCuratedSchema import com.machankura.bennu.compose.nostr.GroupNostrProfile import com.machankura.bennu.compose.nostr.GroupPost import com.machankura.bennu.compose.nostr.GroupRelayList @@ -86,29 +84,6 @@ sealed interface ChatRoomDetailUIState { * every group until somebody proposes one. */ val groupPosts: List = emptyList(), - /** - * The lists this group curates, as the schemas it signed for them, most - * recently signed first. - * - * Under the posts because a schema is the other thing a group publishes - * for strangers to answer: a post is the group speaking, a schema is the - * group asking -- for entries to a list it will then curate. The row - * counts them; they are read on `GroupCuratedSchemasScreen`. Empty in a - * group that curates nothing, which is every group until somebody - * proposes a schema. - */ - val groupCuratedSchemas: List = emptyList(), - /** - * The entries this group has accepted into the lists it curates, most - * recently signed first. - * - * Under the schemas because they are what a schema is *for*: the schema - * asks, strangers suggest, and these are what the group decided to - * stand behind. The row counts them; they are read on - * `GroupCuratedEntriesScreen`. Empty in a group that has accepted - * nothing, which is every group until a quorum signs an entry. - */ - val groupCuratedEntries: List = emptyList(), /** * The wallet this group has opened on the app's network, or null for one * it has not. Under the identity block because it is not part of the @@ -120,7 +95,7 @@ sealed interface ChatRoomDetailUIState { /** * Whether this device could sign an event for the group, which on this * screen gates the paste at the end of the identity block. Each of the - * five screens the rows open reads the same capability for its own gate. + * three screens the rows open reads the same capability for its own gate. * * The same capability [canAddSubgroup] wants, and wanted for the same * reason: proposing anything in the group's name is a signature by the diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/CuratedSuggestionListUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/CuratedSuggestionListUIState.kt deleted file mode 100644 index b91f5219..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/CuratedSuggestionListUIState.kt +++ /dev/null @@ -1,40 +0,0 @@ -package com.machankura.bennu.compose.ui.view.state - -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.CuratedSuggestion -import com.machankura.bennu.compose.nostr.GroupCuratedSchema - -sealed interface CuratedSuggestionListUIState { - data class Loaded( - val localChatRoom: LocalChatRoom, - /** The list whose queue this is, as the group last signed it. */ - val schema: GroupCuratedSchema, - /** - * Where the queue was read from: the relays the schema names, or the - * group's own where it names none. On the screen because a queue read - * from the wrong relays is an empty queue with no way to tell it from - * a list nobody has written to. - */ - val relays: List = emptyList(), - /** Everything suggested to the list, newest first. */ - val suggestions: List = emptyList(), - /** - * Whether the relays are still being asked. - * - * A pull through the sync queue has no end-of-stored-events the screen - * can see, so this is bounded by time rather than by an answer: true - * from the request going out until the first suggestion lands or the - * wait runs out. While it is true and nothing has arrived, the screen - * is looking rather than empty. - */ - val isAsking: Boolean = false, - ): CuratedSuggestionListUIState { - val curatedCount: Int get() = suggestions.count { it.isCurated } - } - - data class Error( - val message: String - ): CuratedSuggestionListUIState - - data object Loading: CuratedSuggestionListUIState -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/EditGroupCuratedSchemaUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/EditGroupCuratedSchemaUIState.kt deleted file mode 100644 index 2fcf36e2..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/EditGroupCuratedSchemaUIState.kt +++ /dev/null @@ -1,42 +0,0 @@ -package com.machankura.bennu.compose.ui.view.state - -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.GroupCuratedSchema - -sealed interface EditGroupCuratedSchemaUIState { - data class Loaded( - val localChatRoom: LocalChatRoom, - /** - * The schema being edited, as the group last signed it, or null for a new - * one. - * - * Kept beside the working copy rather than replaced by it, because the - * button proposes only when something differs -- and "differs" needs - * both halves. Null also locks nothing: a new schema's identifier is the - * member's to choose, and an existing one's is not. - */ - val existing: GroupCuratedSchema? = null, - /** - * The relays a new schema starts with: where the group has said it - * publishes, since that is where its list would be read. - * - * Only a new schema is seeded from these. An existing one has its own - * relays signed into it, and those are the ones an edit starts from. - */ - val defaultRelays: List = emptyList(), - /** - * Whether this device holds a share of the group's key. - * - * False leaves the form writable and the button inert, for the same - * reason the other editors do: drafting a schema costs nothing, and only - * a share-holder can open the session that would sign it. - */ - val canSign: Boolean = false, - ): EditGroupCuratedSchemaUIState - - data class Error( - val message: String - ): EditGroupCuratedSchemaUIState - - data object Loading: EditGroupCuratedSchemaUIState -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupCuratedEntriesUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupCuratedEntriesUIState.kt deleted file mode 100644 index 2ed9ccae..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupCuratedEntriesUIState.kt +++ /dev/null @@ -1,35 +0,0 @@ -package com.machankura.bennu.compose.ui.view.state - -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.GroupCuratedEntry -import com.machankura.bennu.compose.nostr.GroupRelayList - -sealed interface GroupCuratedEntriesUIState { - data class Loaded( - val localChatRoom: LocalChatRoom, - /** - * The entries this group has accepted into the lists it curates, most - * recently signed first. Empty in a group that has accepted nothing, - * which is every group until a quorum signs an entry. - * - * No capability beside it, because nothing on the screen needs one: - * reading what the group decided takes no share of the key, and - * neither does repeating its signature to a relay. - */ - val groupCuratedEntries: List = emptyList(), - /** - * Where the group has said it lives, for "Broadcast all": each entry - * goes where its own broadcast screen would send it before the member - * changed anything, and that starts from these. See - * `BroadcastGroupSignedEventViewModel.defaultRelaysFor`; the list's - * own relays come off the entry, which carries its schema. - */ - val relayLists: List = emptyList(), - ): GroupCuratedEntriesUIState - - data class Error( - val message: String - ): GroupCuratedEntriesUIState - - data object Loading: GroupCuratedEntriesUIState -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupCuratedSchemasUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupCuratedSchemasUIState.kt deleted file mode 100644 index e317cc8c..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupCuratedSchemasUIState.kt +++ /dev/null @@ -1,31 +0,0 @@ -package com.machankura.bennu.compose.ui.view.state - -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.GroupCuratedSchema - -sealed interface GroupCuratedSchemasUIState { - data class Loaded( - val localChatRoom: LocalChatRoom, - /** - * The lists this group curates, as the schemas it signed for them, most - * recently signed first. Empty in a group that curates nothing, which - * is every group until somebody proposes a schema. - */ - val groupCuratedSchemas: List = emptyList(), - /** - * Whether this device holds a share of the group's key. - * - * False leaves the schemas readable -- and their queues, which take no - * share to read -- and hides both ways into the editor, the card's and - * the button's, for the reason `GroupNostrProfileUIState.Loaded.canSign` - * gives. - */ - val canSign: Boolean = false, - ): GroupCuratedSchemasUIState - - data class Error( - val message: String - ): GroupCuratedSchemasUIState - - data object Loading: GroupCuratedSchemasUIState -} diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/CuratedSuggestionTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/CuratedSuggestionTest.kt deleted file mode 100644 index 0ebffe8c..00000000 --- a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/CuratedSuggestionTest.kt +++ /dev/null @@ -1,191 +0,0 @@ -package com.machankura.bennu.compose.nostr - -import com.machankura.bennu.compose.database.GENESIS_AT -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.machankura.bennu.compose.database.model.NostrEvent -import com.machankura.bennu.compose.database.model.Profile -import com.machankura.bennu.compose.database.model.intermdiate.LocalNostrEvent -import com.machankura.bennu.compose.nostr.curated.CuratedField -import com.machankura.bennu.compose.nostr.curated.CuratedFieldConfig -import com.machankura.bennu.compose.nostr.curated.CuratedFieldType -import com.machankura.bennu.compose.nostr.curated.CuratedSchema -import com.machankura.bennu.compose.nostr.curated.CuratedSchemaEvent -import com.machankura.bennu.compose.nostr.curated.CuratedVisibility -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFalse -import kotlin.test.assertTrue -import kotlin.time.Instant - -/** - * The queue of a list the group curates, read off whatever this device has - * stored for the coordinate. - * - * The rows come from a filter on kind and `a` tag, which is broader than the - * queue in three ways this reading has to close: an event that does not satisfy - * the schema, a kind 31890 signed by somebody other than the group, and an - * older version of an entry its author has since replaced. And one thing it - * has to add: whether the group has already taken a suggestion up, which is a - * canonical entry sharing its `d`. - * - * Also what to call a stranger. A profile that has arrived is a name; the - * placeholder the indexer writes on first sight is not, and a queue full of - * "LOADING..." would be a queue of nobody. - */ -class CuratedSuggestionTest { - private val chatRoomId = "d4c3b2a1".repeat(8) - private val ada = "a".repeat(64) - private val bob = "b".repeat(64) - - private val films = GroupCuratedSchema( - signedEvent = GroupSignedEvent( - id = "c".repeat(64), - chatRoomId = chatRoomId, - publicKey = chatRoomId, - kind = CuratedSchemaEvent.KIND, - tags = emptyArray(), - content = "", - signature = "f".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_000), - ), - schema = CuratedSchema( - identifier = "films", - title = "Film suggestion", - name = "Films worth translating", - description = "Films the group would subtitle.", - visibility = CuratedVisibility.Public, - fields = listOf( - CuratedField.IDENTIFIER, - CuratedField.TITLE, - CuratedField( - "watchUrl", - CuratedFieldType.Url, - isRequired = true, - config = CuratedFieldConfig(tag = "r", marker = "watch") - ), - ), - ).normalized(), - ) - - private val coordinate = films.coordinate() - - @Test - fun `the queue is every suggestion that satisfies the schema newest first`() { - val queue = CuratedSuggestion.queueOf( - films, - listOf( - stored(suggestion(ada, "older", "The older one", 1_700_000_000)), - stored(suggestion(bob, "newer", "The newer one", 1_700_000_900)), - // No watch link, which the schema requires: not shown with the - // gap blanked out, not shown at all. - stored(suggestion(ada, "broken", "The broken one", 1_700_000_500, watchUrl = null)), - // Another list's reply with this one's identifier. Not this queue. - stored(suggestion(ada, "elsewhere", "Somebody else's", 1_700_000_600, root = "31889:${"e".repeat(64)}:films")), - // A text note that happens to carry the coordinate. - stored(suggestion(ada, "note", "A note", 1_700_000_700).copy(kind = 1)), - ) - ) - - assertEquals(listOf("The newer one", "The older one"), queue.map { it.entry.title }) - assertTrue(queue.none { it.isCurated }) - } - - @Test - fun `an entry its author has replaced shows once as the newer version`() { - val queue = CuratedSuggestion.queueOf( - films, - listOf( - stored(suggestion(ada, "rise", "The Rise and Rise of Bitcoin", 1_700_000_000)), - stored(suggestion(ada, "rise", "The Rise and Rise of Bitcoin (2014)", 1_700_000_900)), - // The same `d` under another key is another entry: coordinates - // carry the author. - stored(suggestion(bob, "rise", "Bob's rise", 1_700_000_100)), - ) - ) - - assertEquals( - listOf("The Rise and Rise of Bitcoin (2014)", "Bob's rise"), - queue.map { it.entry.title } - ) - } - - @Test - fun `a suggestion the group has taken up is marked and the group's entry is not in the queue`() { - val queue = CuratedSuggestion.queueOf( - films, - listOf( - stored(suggestion(ada, "rise", "The Rise and Rise of Bitcoin", 1_700_000_000)), - stored(suggestion(bob, "magic", "Magic Money", 1_700_000_100)), - stored(canonical(chatRoomId, "rise", "The Rise and Rise of Bitcoin", 1_700_000_900)), - // A kind 31890 by somebody who is not the curator is nobody's - // list, and marks nothing. - stored(canonical(bob, "magic", "Magic Money", 1_700_000_950)), - ) - ) - - assertEquals(listOf("Magic Money", "The Rise and Rise of Bitcoin"), queue.map { it.entry.title }) - assertEquals( - mapOf("Magic Money" to false, "The Rise and Rise of Bitcoin" to true), - queue.associate { it.entry.title to it.isCurated } - ) - } - - @Test - fun `a suggester is named by their profile and by their key until one arrives`() { - val named = Profile( - publicKey = ada, - displayName = "Ada", - nostrEventId = "e".repeat(64), - createdAt = Instant.fromEpochSeconds(1_700_000_000), - ) - val placeholder = Profile( - publicKey = bob, - displayName = "LOADING...", - nostrEventId = "e".repeat(64), - createdAt = GENESIS_AT, - ) - - val queue = CuratedSuggestion.queueOf( - films, - listOf( - stored(suggestion(ada, "one", "One", 1_700_000_000), profile = named), - stored(suggestion(bob, "two", "Two", 1_700_000_100), profile = placeholder), - stored(suggestion("c".repeat(64), "three", "Three", 1_700_000_200), profile = null), - ) - ) - - assertEquals( - listOf("cccccccc", "bbbbbbbb", "Ada"), - queue.map { it.suggesterName() } - ) - assertFalse(queue.any { it.suggesterName() == "LOADING..." }) - } - - private fun suggestion( - pubKey: String, - identifier: String, - title: String, - createdAt: Long, - watchUrl: String? = "https://example.com/watch", - root: String = coordinate, - ) = NostrEvent( - id = createdAt.toString().padStart(60, '0') + pubKey.take(4), - pubKey = pubKey, - kind = CuratedSchemaEvent.SUGGESTION_KIND, - tags = listOfNotNull( - arrayOf("d", identifier), - arrayOf("title", title), - watchUrl?.let { arrayOf("r", it, "watch") }, - arrayOf("a", root, "", "root"), - ).toTypedArray(), - content = "", - sig = "b".repeat(128), - createdAt = Instant.fromEpochSeconds(createdAt), - ) - - private fun canonical(pubKey: String, identifier: String, title: String, createdAt: Long) = - suggestion(pubKey, identifier, title, createdAt).copy(kind = CuratedSchemaEvent.CANONICAL_KIND) - - private fun stored(event: NostrEvent, profile: Profile? = null) = - LocalNostrEvent(nostrEvent = event, profile = profile) -} diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/GroupCuratedEntryTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/GroupCuratedEntryTest.kt deleted file mode 100644 index f2ba664a..00000000 --- a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/GroupCuratedEntryTest.kt +++ /dev/null @@ -1,317 +0,0 @@ -package com.machankura.bennu.compose.nostr - -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray -import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher -import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.crypto.frost.Frost -import fr.acinq.bitcoin.crypto.frost.IndividualNonce -import fr.acinq.bitcoin.crypto.frost.KeyMaterial -import fr.acinq.bitcoin.crypto.frost.SecretNonce -import fr.acinq.bitcoin.crypto.frost.Session -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.machankura.bennu.compose.extensions.toHex -import com.machankura.bennu.compose.managers.SharedKeyDerivation -import com.machankura.bennu.compose.nostr.curated.CuratedEntryEvent -import com.machankura.bennu.compose.nostr.curated.CuratedField -import com.machankura.bennu.compose.nostr.curated.CuratedFieldConfig -import com.machankura.bennu.compose.nostr.curated.CuratedFieldType -import com.machankura.bennu.compose.nostr.curated.CuratedSchema -import com.machankura.bennu.compose.nostr.curated.CuratedSchemaEvent -import com.machankura.bennu.compose.nostr.curated.CuratedSuggestionRef -import com.machankura.bennu.compose.nostr.curated.CuratedVisibility -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertNotNull -import kotlin.test.assertNull - -/** - * What may be shown as an entry the group accepted into a list it curates. - * - * The reading gate is `GroupCuratedSchemaTest`'s -- the room has to be the - * author and the signature has to be the room's -- plus the two things this - * reader alone decides. An entry is read against the list it replies to, so - * one replying to a list this device holds no schema for is not shown, and one - * the list's own fields refuse is not shown either: it is the check the queue - * makes on a relay's copy, made here on the group's own, so the two screens - * cannot disagree about what the group accepted. - * - * The ordering half is the schema's: one per coordinate, newest winning, since - * re-curating is a newer event under the same `d`. - */ -class GroupCuratedEntryTest { - private val participants = 3 - private val threshold = 2 - - private val groupMaterial: KeyMaterial = Frost.trustedDealerKeygen( - thresholdSecretKey = PrivateKey( - ByteVector32("1c0ffee0000000000000000000000000000000000000000000000000000000a1") - ), - nParticipants = participants, - threshold = threshold - ) - - /** Another group entirely, for the entries signed by the wrong room. */ - private val strangerMaterial: KeyMaterial = Frost.trustedDealerKeygen( - thresholdSecretKey = PrivateKey( - ByteVector32("3decade0000000000000000000000000000000000000000000000000000000c3") - ), - nParticipants = participants, - threshold = threshold - ) - - private val path = SharedKeyDerivation.MARMOT_ADMIN_GROUP_PATH - - private val chatRoomId = - SharedKeyDerivation.marmotGroupId(groupMaterial.thresholdPublicKey.value.toHex(), path) - - private val suggester = "eebb74ab6bfb8485722ab1d4acee856eee96f17a9e1721f9c7cc63376c40b860" - - private val films = CuratedSchema( - identifier = "films", - title = "Film suggestion", - name = "Films worth translating", - description = "Films the group would subtitle, with a link to watch each one.", - visibility = CuratedVisibility.Public, - fields = listOf( - CuratedField.IDENTIFIER, - CuratedField.TITLE, - CuratedField("year", CuratedFieldType.Year, isRequired = false, label = "Year", config = CuratedFieldConfig(min = 1900, max = 2100)), - CuratedField( - name = "watchUrl", - type = CuratedFieldType.Url, - isRequired = true, - label = "Where to watch", - config = CuratedFieldConfig(tag = "r", marker = "watch", max = 500, https = true), - ), - ), - relays = listOf("wss://relay.example.com"), - ) - - private val books = films.copy(identifier = "books", name = "Books worth translating") - - /** The lists as the group's screen holds them: read off the group's real signatures. */ - private val schemas: List = listOf(films, books).map { schema -> - assertNotNull(GroupCuratedSchema.of(signed(CuratedSchemaEvent.template(schema, createdAt = 1_700_000_000)), chatRoomId)) - } - - private val filmsList = schemas.first { it.identifier == "films" } - private val booksList = schemas.first { it.identifier == "books" } - - private fun riseAndRise(year: String = "2014") = mapOf( - "identifier" to listOf("imdb:tt2821314"), - "title" to listOf("The Rise and Rise of Bitcoin"), - "year" to listOf(year), - "watchUrl" to listOf("https://bitcoindoc.com/"), - ) - - private val source = CuratedSuggestionRef( - id = "a".repeat(64), - coordinate = "31888:$suggester:imdb:tt2821314", - pubKey = suggester, - ) - - private fun entry( - list: GroupCuratedSchema = filmsList, - values: Map> = riseAndRise(), - createdAt: Long = 1_700_000_900, - ): EventTemplate<*> = CuratedEntryEvent.canonicalTemplate( - schema = list.schema, - coordinate = list.coordinate(), - curator = list.publicKey, - values = values, - source = source, - createdAt = createdAt, - ) - - @Test - fun `an entry the room signed into a list it curates is one it accepted`() { - val accepted = assertNotNull(GroupCuratedEntry.of(signed(entry()), chatRoomId, schemas)) - - assertEquals("The Rise and Rise of Bitcoin", accepted.title) - assertEquals("imdb:tt2821314", accepted.identifier) - assertEquals("31890:$chatRoomId:imdb:tt2821314", accepted.coordinate()) - assertEquals(filmsList, accepted.list) - assertEquals("2014", accepted.entry.value("year")) - assertEquals(source, accepted.entry.source) - } - - @Test - fun `an entry another group signed is not this group's`() { - val stranger = GroupSignedEvent.fromEvent( - event = event(entry(), material = strangerMaterial), - chatRoomId = chatRoomId - ) - - assertNull(GroupCuratedEntry.of(stranger, chatRoomId, schemas)) - } - - @Test - fun `an entry the room did not sign is not one`() { - // Authored by the room and signed by somebody else: a member declaring - // the group accepted something, which the reading verifies rather than - // trusting the author field. - assertNull(GroupCuratedEntry.of(signed(entry(), signer = strangerMaterial), chatRoomId, schemas)) - - listOf("f".repeat(128), "not a signature", "").forEach { rubbish -> - assertNull( - GroupCuratedEntry.of(signed(entry(), signature = rubbish), chatRoomId, schemas), - "an entry signed with \"$rubbish\" was accepted" - ) - } - } - - @Test - fun `an event of another kind is not an entry`() { - assertNull( - GroupCuratedEntry.of(signed(entry()).copy(kind = CuratedEntryEvent.SUGGESTION_KIND), chatRoomId, schemas) - ) - } - - @Test - fun `an entry into a list this device holds no schema for is not shown`() { - // Really signed, and replying to a real list -- just not one among the - // schemas the reader was given. There are no fields to read it by. - assertNull(GroupCuratedEntry.of(signed(entry(list = booksList)), chatRoomId, schemas = listOf(filmsList))) - } - - @Test - fun `an entry the list's own fields refuse is not shown`() { - // The room's real signature over a year outside the schema's range: the - // group's statement, and still not an entry the list's readers would - // count. The queue would drop the relay's copy for the same reason. - val outOfRange = signed(entry(values = riseAndRise(year = "1850"))) - - assertNull(GroupCuratedEntry.of(outOfRange, chatRoomId, schemas)) - assertEquals(emptyList(), GroupCuratedEntry.newestPerEntryAmong(listOf(outOfRange), chatRoomId, schemas)) - } - - @Test - fun `the newest per coordinate wins and two identifiers are two entries`() { - val first = signed(entry(createdAt = 1_700_000_900)) - val revised = signed(entry(values = riseAndRise(year = "2015"), createdAt = 1_700_001_800)) - val another = signed( - entry( - values = mapOf( - "identifier" to listOf("magic-money"), - "title" to listOf("Magic Money"), - "watchUrl" to listOf("https://example.com/watch"), - ), - createdAt = 1_700_001_200, - ) - ) - - listOf( - listOf(first, revised, another), - listOf(another, revised, first), - listOf(revised, another, first), - ).forEach { events -> - val accepted = GroupCuratedEntry.newestPerEntryAmong(events, chatRoomId, schemas) - - assertEquals( - listOf("imdb:tt2821314", "magic-money"), - accepted.map { it.identifier }, - "the entries came back in the wrong order, or one of them went missing" - ) - assertEquals("2015", accepted.first().entry.value("year"), "a re-curation did not replace the entry it revised") - } - } - - @Test - fun `the same identifier in two lists is one coordinate and the newer decides`() { - val inFilms = signed(entry(list = filmsList, createdAt = 1_700_000_900)) - val inBooks = signed(entry(list = booksList, createdAt = 1_700_001_800)) - - val accepted = GroupCuratedEntry.newestPerEntryAmong(listOf(inFilms, inBooks), chatRoomId, schemas) - - assertEquals(1, accepted.size, "one coordinate was shown as two entries") - assertEquals(booksList, accepted.single().list) - } - - /** An entry as `FrostSigningManager.complete` files one. */ - private fun signed( - template: EventTemplate<*>, - material: KeyMaterial = groupMaterial, - signer: KeyMaterial = material, - signature: String? = null - ): GroupSignedEvent = GroupSignedEvent.fromEvent( - event = event(template, material, signer, signature), - chatRoomId = chatRoomId, - derivationPath = SharedKeyDerivation.formatPath(path) - ) - - private fun event( - template: EventTemplate<*>, - material: KeyMaterial = groupMaterial, - signer: KeyMaterial = material, - signature: String? = null - ): Event { - val groupPubKey = SharedKeyDerivation - .derive(material.thresholdPublicKey.value.toHex(), path) - .hex - - val id = EventHasher.hashId( - pubKey = groupPubKey, - createdAt = template.createdAt, - kind = template.kind, - tags = template.tags, - content = template.content - ) - - return Event( - id = id, - pubKey = groupPubKey, - createdAt = template.createdAt, - kind = template.kind, - tags = template.tags, - content = template.content, - sig = signature ?: groupSignature(signer, id) - ) - } - - /** - * A real FROST signature by [material]'s quorum over [eventId], through the - * same shape `FrostSigningManager.advance` runs. - */ - private fun groupSignature(material: KeyMaterial, eventId: String): String { - val cache = SharedKeyDerivation - .derive(material.thresholdPublicKey.value.toHex(), path) - .cache - val message = ByteVector(eventId.hexToByteArray()) - val signerIds = listOf(0, 1) - - val nonces = signerIds.map { signerId -> - SecretNonce.generate( - sessionRandom = ByteVector32("a".repeat(63) + "${signerId + 1}"), - secretShare = material.secretShares[signerId], - publicShare = material.publicShares[signerId], - tweakedThresholdPublicKey = cache.tweakedPublicKey, - message = message, - extraInput = null - ) - } - - val signingSession = Session.create( - aggregatedNonce = IndividualNonce.aggregate(nonces.map { it.second }).right!!, - signerIds = signerIds.map { it.toUInt() }, - signerPublicShares = signerIds.map { material.publicShares[it] }, - nParticipants = participants, - threshold = threshold, - tweakCache = cache, - message = message - ) - - val partials = signerIds.mapIndexed { position, signerId -> - signingSession.sign( - nonces[position].first, - material.secretShares[signerId], - signerId.toUInt() - ).right!! - } - - return signingSession.aggregateSigs(partials).right!!.toByteArray().toHex() - } -} diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/GroupCuratedSchemaTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/GroupCuratedSchemaTest.kt deleted file mode 100644 index 830f9fb1..00000000 --- a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/GroupCuratedSchemaTest.kt +++ /dev/null @@ -1,317 +0,0 @@ -package com.machankura.bennu.compose.nostr - -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.machankura.bennu.compose.extensions.toHex -import com.machankura.bennu.compose.managers.SharedKeyDerivation -import com.machankura.bennu.compose.nostr.curated.CuratedField -import com.machankura.bennu.compose.nostr.curated.CuratedFieldConfig -import com.machankura.bennu.compose.nostr.curated.CuratedFieldType -import com.machankura.bennu.compose.nostr.curated.CuratedSchema -import com.machankura.bennu.compose.nostr.curated.CuratedSchemaEvent -import com.machankura.bennu.compose.nostr.curated.CuratedVisibility -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray -import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.crypto.frost.Frost -import fr.acinq.bitcoin.crypto.frost.IndividualNonce -import fr.acinq.bitcoin.crypto.frost.KeyMaterial -import fr.acinq.bitcoin.crypto.frost.SecretNonce -import fr.acinq.bitcoin.crypto.frost.Session -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertNotNull -import kotlin.test.assertNull -import kotlin.test.assertTrue - -/** - * What may be shown as a list the group curates. - * - * The reading gate is `GroupPostTest`'s -- the room has to be the author and the - * signature has to be the room's -- and it carries a weight of its own here: a - * schema read wrong would have strangers filling in a form under a group's name - * that the group never agreed to, and the group's key accepting entries against - * it. The third refusal is this reader's alone: a schema the room really signed - * but that no client could act on is not shown as one it curates. - * - * The ordering half is between the profile's and the posts': one per identifier, - * newest winning within it, because the kind is addressable and a group may - * curate several lists. - */ -class GroupCuratedSchemaTest { - private val participants = 3 - private val threshold = 2 - - private val groupMaterial: KeyMaterial = Frost.trustedDealerKeygen( - thresholdSecretKey = PrivateKey( - ByteVector32("1c0ffee0000000000000000000000000000000000000000000000000000000a1") - ), - nParticipants = participants, - threshold = threshold - ) - - /** Another group entirely, for the schemas signed by the wrong room. */ - private val strangerMaterial: KeyMaterial = Frost.trustedDealerKeygen( - thresholdSecretKey = PrivateKey( - ByteVector32("3decade0000000000000000000000000000000000000000000000000000000c3") - ), - nParticipants = participants, - threshold = threshold - ) - - private val path = SharedKeyDerivation.MARMOT_ADMIN_GROUP_PATH - - private val chatRoomId = - SharedKeyDerivation.marmotGroupId(groupMaterial.thresholdPublicKey.value.toHex(), path) - - private val films = CuratedSchema( - identifier = "films", - title = "Film suggestion", - name = "Films worth translating", - description = "Films the group would subtitle, with a link to watch each one.", - visibility = CuratedVisibility.Public, - fields = listOf( - CuratedField.IDENTIFIER, - CuratedField.TITLE, - CuratedField( - name = "watchUrl", - type = CuratedFieldType.Url, - isRequired = true, - placeholder = "https://…", - label = "Where to watch", - config = CuratedFieldConfig(tag = "r", marker = "watch", max = 500, https = true), - ), - ), - relays = listOf("wss://relay.example.com"), - ) - - @Test - fun `a schema the room signed is a list the group curates`() { - val curated = assertNotNull( - GroupCuratedSchema.of(signedEvent = signed(films), chatRoomId = chatRoomId) - ) - - assertEquals("films", curated.identifier) - assertEquals(chatRoomId, curated.publicKey) - assertEquals("31889:$chatRoomId:films", curated.coordinate()) - assertEquals(films, curated.schema) - assertEquals("Films worth translating", curated.schema.displayName()) - } - - @Test - fun `a schema another group signed is not this group's`() { - // A real quorum and a real signature by a group with no standing to - // curate for this one. The row names this room because that is where it - // was filed; the author is what decides whose list it is. - val stranger = GroupSignedEvent.fromEvent( - event = schemaEvent(films, material = strangerMaterial), - chatRoomId = chatRoomId - ) - - assertNull(GroupCuratedSchema.of(signedEvent = stranger, chatRoomId = chatRoomId)) - } - - @Test - fun `a schema the room did not sign is not one`() { - // Authored by the room and signed by somebody else: the shape a member - // declaring a list in the group's name would produce, and the reason the - // reading verifies rather than trusting the author field. - assertNull( - GroupCuratedSchema.of( - signedEvent = signed(films, signer = strangerMaterial), - chatRoomId = chatRoomId - ) - ) - - listOf("f".repeat(128), "not a signature", "").forEach { rubbish -> - assertNull( - GroupCuratedSchema.of( - signedEvent = signed(films, signature = rubbish), - chatRoomId = chatRoomId - ), - "a schema signed with \"$rubbish\" was accepted" - ) - } - } - - @Test - fun `an event of another kind is not a schema`() { - assertNull( - GroupCuratedSchema.of( - signedEvent = signed(films).copy(kind = CuratedSchemaEvent.SUGGESTION_KIND), - chatRoomId = chatRoomId - ) - ) - } - - @Test - fun `a schema the room signed but no client could act on is refused`() { - // The room's real signature over a kind 31889 with no visibility. It is - // the group's statement and it is still not a list: a reader that showed - // it would be showing a form nobody may be allowed to fill in. - val unusable = signed( - films, - tags = CuratedSchemaEvent.template(films, createdAt = 1_700_000_000).tags - .filterNot { it[0] == "visibility" } - .toTypedArray() - ) - - assertNull(GroupCuratedSchema.of(signedEvent = unusable, chatRoomId = chatRoomId)) - assertEquals(emptyList(), GroupCuratedSchema.newestPerListAmong(listOf(unusable), chatRoomId)) - } - - @Test - fun `the newest per identifier wins and two identifiers are two lists`() { - val firstFilms = signed(films, createdAt = 1_700_000_000) - val editedFilms = signed(films.copy(description = "Films the group would subtitle."), createdAt = 1_700_000_900) - val books = signed(films.copy(identifier = "books", name = "Books worth translating"), createdAt = 1_700_000_300) - - listOf( - listOf(firstFilms, editedFilms, books), - listOf(books, editedFilms, firstFilms), - listOf(editedFilms, books, firstFilms), - ).forEach { events -> - val lists = GroupCuratedSchema.newestPerListAmong(events, chatRoomId) - - assertEquals( - listOf("films", "books"), - lists.map { it.identifier }, - "the lists came back in the wrong order, or one of them went missing" - ) - assertEquals( - "Films the group would subtitle.", - lists.first().schema.description, - "an edit did not replace the schema it revised" - ) - } - } - - @Test - fun `two versions signed in the same second resolve the same way on every device`() { - val one = signed(films.copy(description = "One."), createdAt = 1_700_000_000) - val other = signed(films.copy(description = "Other."), createdAt = 1_700_000_000) - - val expected = GroupCuratedSchema.newestPerListAmong(listOf(one, other), chatRoomId).single() - - assertEquals( - expected, - GroupCuratedSchema.newestPerListAmong(listOf(other, one), chatRoomId).single(), - "a tie on the timestamp was broken differently by the two orderings" - ) - assertEquals( - if (one.id > other.id) "One." else "Other.", - expected.schema.description, - "the tie should break on the id, which is the only thing both devices share" - ) - } - - @Test - fun `a schema the editor built reads back as the group defined it`() { - val template = GroupCuratedSchema.template(films) - - assertEquals(CuratedSchemaEvent.KIND, template.kind) - assertEquals(films.description, template.content) - - val curated = assertNotNull( - GroupCuratedSchema.of( - signedEvent = signed(films, tags = template.tags, content = template.content), - chatRoomId = chatRoomId - ) - ) - - assertEquals(films, curated.schema) - assertTrue(curated.schema.fields.first { it.name == "watchUrl" }.isRequired) - } - - /** A schema as `FrostSigningManager.complete` files one. */ - private fun signed( - schema: CuratedSchema, - tags: Array> = CuratedSchemaEvent.template(schema, createdAt = 1_700_000_000).tags, - content: String = schema.description, - createdAt: Long = 1_700_000_000, - material: KeyMaterial = groupMaterial, - signer: KeyMaterial = material, - signature: String? = null - ): GroupSignedEvent = GroupSignedEvent.fromEvent( - event = schemaEvent(schema, tags, content, createdAt, material, signer, signature), - chatRoomId = chatRoomId, - derivationPath = SharedKeyDerivation.formatPath(path) - ) - - private fun schemaEvent( - schema: CuratedSchema, - tags: Array> = CuratedSchemaEvent.template(schema, createdAt = 1_700_000_000).tags, - content: String = schema.description, - createdAt: Long = 1_700_000_000, - material: KeyMaterial = groupMaterial, - signer: KeyMaterial = material, - signature: String? = null - ): Event { - val groupPubKey = SharedKeyDerivation - .derive(material.thresholdPublicKey.value.toHex(), path) - .hex - - val id = EventHasher.hashId( - pubKey = groupPubKey, - createdAt = createdAt, - kind = CuratedSchemaEvent.KIND, - tags = tags, - content = content - ) - - return Event( - id = id, - pubKey = groupPubKey, - createdAt = createdAt, - kind = CuratedSchemaEvent.KIND, - tags = tags, - content = content, - sig = signature ?: groupSignature(signer, id) - ) - } - - /** - * A real FROST signature by [material]'s quorum over [eventId], through the - * same shape `FrostSigningManager.advance` runs. - */ - private fun groupSignature(material: KeyMaterial, eventId: String): String { - val cache = SharedKeyDerivation - .derive(material.thresholdPublicKey.value.toHex(), path) - .cache - val message = ByteVector(eventId.hexToByteArray()) - val signerIds = listOf(0, 1) - - val nonces = signerIds.map { signerId -> - SecretNonce.generate( - sessionRandom = ByteVector32("a".repeat(63) + "${signerId + 1}"), - secretShare = material.secretShares[signerId], - publicShare = material.publicShares[signerId], - tweakedThresholdPublicKey = cache.tweakedPublicKey, - message = message, - extraInput = null - ) - } - - val signingSession = Session.create( - aggregatedNonce = IndividualNonce.aggregate(nonces.map { it.second }).right!!, - signerIds = signerIds.map { it.toUInt() }, - signerPublicShares = signerIds.map { material.publicShares[it] }, - nParticipants = participants, - threshold = threshold, - tweakCache = cache, - message = message - ) - - val partials = signerIds.mapIndexed { position, signerId -> - signingSession.sign( - nonces[position].first, - material.secretShares[signerId], - signerId.toUInt() - ).right!! - } - - return signingSession.aggregateSigs(partials).right!!.toByteArray().toHex() - } -} diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/GroupEventProposalTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/GroupEventProposalTest.kt index 7ce93c11..2e9862fb 100644 --- a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/GroupEventProposalTest.kt +++ b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/GroupEventProposalTest.kt @@ -3,9 +3,6 @@ package com.machankura.bennu.compose.nostr import com.machankura.bennu.compose.database.model.GroupSignedEvent import com.machankura.bennu.compose.extensions.toHex import com.machankura.bennu.compose.managers.SharedKeyDerivation -import com.machankura.bennu.compose.nostr.curated.CuratedSchemaEvent -import com.machankura.bennu.compose.nostr.curated.CuratedSchemaProblem -import com.machankura.bennu.compose.nostr.curated.CuratedVisibility import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher @@ -32,7 +29,7 @@ import kotlin.test.assertTrue * that will be filed and shown nowhere. * * The second is the promise the feature makes: a pasted kind 0 becomes the - * profile, a kind 1 a post, a kind 31889 a schema, a relay list a relay list. That + * profile, a kind 1 a post, a relay list a relay list. That * is not this module's doing -- `FrostSigningManager.complete` files every signed * event and the group's screen reads each section off those by kind -- so the * test is the whole chain: the paste read here, signed by a real quorum through @@ -57,44 +54,34 @@ class GroupEventProposalTest { SharedKeyDerivation.marmotGroupId(groupMaterial.thresholdPublicKey.value.toHex(), path) /** - * The bitcoin.mov schema as `npm run schema:dry` would print it: a whole - * event, id, author, signature and time included, abbreviated to the tags - * a reading depends on. + * A post as another client would print it: a whole event, id, author, + * signature and time included. */ - private val pastedSchema = """ + private val pastedPost = """ { "id": "b2f8c7a7b4d5e6f70123456789abcdef0123456789abcdef0123456789abcdef", "pubkey": "7c965d8c2acdfd635562da3bcb82596b595be28b008d8b54ec702ed4c67d9d25", "created_at": 1735689600, - "kind": 31889, + "kind": 1, "tags": [ - ["d", "bitcoin.mov"], - ["title", "bitcoin.mov suggestion"], - ["name", "bitcoin.mov"], - ["description", "Fields for a bitcoin.mov entry."], - ["k", "31888"], - ["visibility", "public"], - ["domain", "bitcoin.mov"], - ["relay", "wss://ephemeral.mantra.press"], - ["field", "identifier", "token", "required", "", "Identifier", "{\"tag\":\"d\",\"max\":80,\"derived\":true}"], - ["field", "title", "text", "required", "The Rise and Rise of Bitcoin", "Title", "{\"max\":200}"], - ["field", "watchUrl", "url", "optional", "", "Watch / reference URL", "{\"tag\":\"r\",\"marker\":\"watch\",\"repeat\":true}"] + ["t", "translation"], + ["alt", "{\"chapter\":1,\"of\":12}"] ], - "content": "Fields for a bitcoin.mov entry.", + "content": "We have finished the first chapter.", "sig": "c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00" } """.trimIndent() @Test fun `a pasted event is read as its kind tags and content and nothing else`() { - val ready = assertIs(GroupEventProposal.read(pastedSchema)) + val ready = assertIs(GroupEventProposal.read(pastedPost)) - assertEquals(31889, ready.kind) - assertEquals("Fields for a bitcoin.mov entry.", ready.content) - assertEquals(11, ready.tags.size) - assertEquals(listOf("d", "bitcoin.mov"), ready.tags.first().toList()) - // The config blob comes through verbatim, escapes and all. - assertEquals("{\"tag\":\"d\",\"max\":80,\"derived\":true}", ready.tags[8][6]) + assertEquals(1, ready.kind) + assertEquals("We have finished the first chapter.", ready.content) + assertEquals(2, ready.tags.size) + assertEquals(listOf("t", "translation"), ready.tags.first().toList()) + // A JSON value inside a tag comes through verbatim, escapes and all. + assertEquals("{\"chapter\":1,\"of\":12}", ready.tags[1][1]) // The id, author, signature and time are not the paste's to decide, and // there is nowhere on a reading for them to go: the session hashes the id @@ -150,10 +137,10 @@ class GroupEventProposalTest { GroupEventProposal.read("""{"kind": 30023, "tags": [["d", "x"]], "content": "An article"}""") ) - // The kinds with a section: the profile, the posts, the four relay lists - // and the schemas. A subgroup certificate is deliberately not among them. + // The kinds with a section: the profile, the posts and the four relay + // lists. A subgroup certificate is deliberately not among them. assertEquals( - setOf(0, 1, 10002, 10050, 10007, 10006, 31889), + setOf(0, 1, 10002, 10050, 10007, 10006), GroupEventProposal.ACCEPTED_KINDS ) } @@ -184,16 +171,6 @@ class GroupEventProposalTest { } } - @Test - fun `a schema a reader would refuse is refused here with the reader's reasons`() { - val withoutVisibility = pastedSchema.replace("""["visibility", "public"],""", "") - - assertEquals( - GroupEventProposal.Refused.SchemaUnusable(listOf(CuratedSchemaProblem.VisibilityMissing)), - GroupEventProposal.read(withoutVisibility) - ) - } - @Test fun `a relay list reads whether or not it names a relay`() { // An empty one is a list the group is withdrawing, which the relays card @@ -231,21 +208,6 @@ class GroupEventProposalTest { assertTrue(posts.single().isNewThread()) } - @Test - fun `a pasted schema once signed is a list the group curates`() { - val ready = assertIs(GroupEventProposal.read(pastedSchema)) - - val curated = assertNotNull(GroupCuratedSchema.of(signed(ready), chatRoomId)) - - assertEquals("bitcoin.mov", curated.identifier) - assertEquals("bitcoin.mov", curated.schema.displayName()) - assertEquals(CuratedVisibility.Public, curated.schema.visibility) - assertEquals(listOf("identifier", "title", "watchUrl"), curated.schema.fields.map { it.name }) - // The coordinate is the group's, not the pasted pubkey's: the group is - // the curator of what it signed. - assertEquals("${CuratedSchemaEvent.KIND}:$chatRoomId:bitcoin.mov", curated.coordinate()) - } - @Test fun `a pasted relay list once signed is one of the group's relay lists`() { val ready = assertIs( diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/curated/CuratedEntryEventTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/curated/CuratedEntryEventTest.kt deleted file mode 100644 index 7c01cd28..00000000 --- a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/curated/CuratedEntryEventTest.kt +++ /dev/null @@ -1,678 +0,0 @@ -package com.machankura.bennu.compose.nostr.curated - -import com.vitorpamplona.quartz.nip01Core.core.Event -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFailsWith -import kotlin.test.assertNotNull -import kotlin.test.assertNull -import kotlin.test.assertTrue - -/** - * Kinds 31888 and 31890 as the NIP writes them, read and checked. - * - * The fixtures are the NIP's own examples -- the bitcoin.mov schema, *The Rise - * and Rise of Bitcoin* as `eebb74ab…` suggested it, and the curator signing it - * off -- because the one property worth pinning is that what that site accepts - * is accepted here and what it refuses is refused here for the same reason. - * `CuratedEntryEvent` is a port of the reference module's verifier rule for - * rule, and this is where each rule gets a case. - * - * The other thing pinned is the shape of what comes back: an entry keyed by the - * schema's field names, with the tags the schema does not define ignored rather - * than kept. `director`, `i` and `lang` are on the NIP's example and on no - * field of the NIP's schema, and they are not in the reading. - * - * And the write side is pinned against the same example from the other end: - * the canonical entry built from the suggestion's values is the NIP's canonical - * entry, tag for tag, and what the builder writes is what the reader reads - * back -- which is the property that lets the accept form and the queue screen - * agree about an entry without either seeing the other's code. - */ -class CuratedEntryEventTest { - private val curator = "7c965d8c2acdfd635562da3bcb82596b595be28b008d8b54ec702ed4c67d9d25" - private val suggester = "eebb74ab6bfb8485722ab1d4acee856eee96f17a9e1721f9c7cc63376c40b860" - private val stranger = "1".repeat(64) - - private val coordinate = "31889:$curator:bitcoin.mov" - - /** The NIP's schema, as `CuratedSchemaEventTest` reads it. */ - private val schema: CuratedSchema = assertNotNull( - CuratedSchemaEvent.parse( - Event( - id = "a".repeat(64), - pubKey = curator, - createdAt = 1735689600, - kind = CuratedSchemaEvent.KIND, - tags = arrayOf( - arrayOf("d", "bitcoin.mov"), - arrayOf("title", "bitcoin.mov suggestion"), - arrayOf("name", "bitcoin.mov"), - arrayOf("description", "Fields for a bitcoin.mov entry."), - arrayOf("k", "31888"), - arrayOf("visibility", "public"), - arrayOf("relay", "wss://ephemeral.mantra.press"), - arrayOf("field", "identifier", "token", "required", "", "Identifier", "{\"tag\":\"d\",\"max\":80,\"derived\":true}"), - arrayOf("field", "title", "text", "required", "", "Title", "{\"max\":200}"), - arrayOf("field", "year", "year", "optional", "", "Year", "{\"min\":1900,\"max\":2100}"), - arrayOf("field", "type", "enum", "required", "", "Type", "{\"options\":[\"movie\",\"documentary\",\"short\",\"interview\",\"series\",\"other\"]}"), - arrayOf("field", "watchUrl", "url", "optional", "", "Watch / reference URL", "{\"tag\":\"r\",\"marker\":\"watch\",\"max\":500,\"repeat\":true}"), - arrayOf("field", "imdbUrl", "url", "optional", "", "IMDb URL", "{\"tag\":\"r\",\"marker\":\"imdb\",\"max\":500}"), - arrayOf("field", "image", "image", "optional", "", "Poster image URL (https)", "{\"max\":500}"), - arrayOf("field", "hashtags", "token", "optional", "", "Hashtags", "{\"tag\":\"t\",\"max\":60,\"repeat\":true,\"derived\":true}"), - arrayOf("field", "description", "longtext", "optional", "", "Description / review", "{\"tag\":\"content\",\"max\":4000}"), - arrayOf("require-any", "watchUrl", "imdbUrl"), - ), - content = "Fields for a bitcoin.mov entry.", - sig = "b".repeat(128), - ) - ) - ) - - private val review = "Follows programmer Daniel Mross and the early Bitcoin community from 2011 onward." - - /** *The Rise and Rise of Bitcoin*, as the NIP's example has it. */ - private val riseAndRise: Array> = arrayOf( - arrayOf("d", "imdb:tt2821314"), - arrayOf("title", "The Rise and Rise of Bitcoin"), - arrayOf("year", "2014"), - arrayOf("type", "documentary"), - arrayOf("director", "Nicholas Mross"), - arrayOf("r", "http://bitcoindoc.com/", "watch"), - arrayOf("r", "https://www.imdb.com/title/tt2821314/", "imdb"), - arrayOf("image", "https://upload.wikimedia.org/wikipedia/en/9/96/The_Rise_and_Rise_of_Bitcoin_%282014%29_Film_Poster.jpg"), - arrayOf("i", "imdb:tt2821314"), - arrayOf("lang", "en"), - arrayOf("t", "bitcoin"), - arrayOf("t", "documentary"), - arrayOf("a", coordinate, "wss://ephemeral.mantra.press", "root"), - arrayOf("p", curator), - arrayOf("k", "31889"), - ) - - private val suggestionId = "a809ddc2ad9c7b99e739e872b1b9e99e96ca9a3a4cb28cdf220c74324277eee8" - - @Test - fun `the NIP's suggestion satisfies the NIP's schema and reads by field`() { - assertEquals(emptyList(), CuratedEntryEvent.verifySuggestion(suggestion(), schema, coordinate)) - - val entry = assertNotNull(CuratedEntryEvent.suggestion(suggestion(), schema, coordinate)) - - assertEquals(CuratedEntryEvent.SUGGESTION_KIND, entry.kind) - assertEquals(suggester, entry.pubKey) - assertEquals("imdb:tt2821314", entry.identifier) - assertEquals("The Rise and Rise of Bitcoin", entry.title) - assertEquals("31888:$suggester:imdb:tt2821314", entry.coordinate()) - assertNull(entry.source) - - // By the schema's field names, not by tag: the two `r` tags land on - // two fields, the `t` tags on one, and the content on the field that - // writes there. - assertEquals("2014", entry.value("year")) - assertEquals("documentary", entry.value("type")) - assertEquals("http://bitcoindoc.com/", entry.value("watchUrl")) - assertEquals("https://www.imdb.com/title/tt2821314/", entry.value("imdbUrl")) - assertEquals(listOf("bitcoin", "documentary"), entry.values["hashtags"]) - assertEquals(review, entry.value("description")) - - // What the schema does not define is not read, however much of it there is. - assertEquals( - setOf("identifier", "title", "year", "type", "watchUrl", "imdbUrl", "image", "hashtags", "description"), - entry.values.keys - ) - } - - @Test - fun `the minimum suggestion is enough`() { - // The doc's own minimum: nothing but what the schema insists on, and an - // IMDb link standing in for a watch link under the require-any rule. - val minimum = suggestion( - tags = arrayOf( - arrayOf("d", "bitcoin-the-end-of-money-as-we-know-it"), - arrayOf("title", "Bitcoin: The End of Money as We Know It"), - arrayOf("type", "documentary"), - arrayOf("r", "https://www.imdb.com/title/tt4654844/", "imdb"), - arrayOf("t", "bitcoin"), - arrayOf("a", coordinate, "", "root"), - ), - content = "" - ) - - assertEquals(emptyList(), CuratedEntryEvent.verifySuggestion(minimum, schema, coordinate)) - assertNull(assertNotNull(CuratedEntryEvent.suggestion(minimum, schema, coordinate)).value("description")) - } - - @Test - fun `the NIP's canonical entry is the list's own and points at where it came from`() { - assertEquals(emptyList(), CuratedEntryEvent.verifyCanonical(canonical(), schema, coordinate, curator)) - - val entry = assertNotNull(CuratedEntryEvent.canonical(canonical(), schema, coordinate, curator)) - - assertTrue(entry.isCanonical) - assertEquals("imdb:tt2821314", entry.identifier) - assertEquals("31890:$curator:imdb:tt2821314", entry.coordinate()) - assertEquals( - CuratedSuggestionRef( - id = suggestionId, - coordinate = "31888:$suggester:imdb:tt2821314", - pubKey = suggester - ), - entry.source - ) - } - - @Test - fun `a canonical entry nobody suggested has no source`() { - val unprompted = canonical(tags = riseAndRise) - - assertEquals(emptyList(), CuratedEntryEvent.verifyCanonical(unprompted, schema, coordinate, curator)) - assertNull(assertNotNull(CuratedEntryEvent.canonical(unprompted, schema, coordinate, curator)).source) - } - - @Test - fun `curation is not delegated`() { - // The same event, signed by the suggester: a valid suggestion and not a - // canonical entry, whatever its kind says. - val notTheCurator = canonical(pubKey = suggester) - - assertEquals( - listOf(CuratedEntryProblem(CuratedEntryEvent.FIELD_CURATOR, CuratedEntryProblem.Reason.NotTheCurator)), - CuratedEntryEvent.verifyCanonical(notTheCurator, schema, coordinate, curator) - ) - assertNull(CuratedEntryEvent.canonical(notTheCurator, schema, coordinate, curator)) - } - - @Test - fun `a source that is not a suggestion coordinate is refused`() { - val malformed = canonical( - tags = riseAndRise + arrayOf(arrayOf("a", "31888:not-a-pubkey:imdb:tt2821314", "", "mention")) - ) - - assertEquals( - listOf(CuratedEntryProblem(CuratedEntryEvent.FIELD_SOURCE, CuratedEntryProblem.Reason.SourceMalformed)), - CuratedEntryEvent.verifyCanonical(malformed, schema, coordinate, curator) - ) - } - - @Test - fun `the wrong kind is not an entry of either sort`() { - val note = suggestion(kind = 1) - - assertEquals( - listOf(CuratedEntryProblem(CuratedEntryEvent.FIELD_KIND, CuratedEntryProblem.Reason.WrongKind)), - CuratedEntryEvent.verifySuggestion(note, schema, coordinate) - ) - // And a suggestion is not a canonical entry: same tags, same author rule aside. - assertTrue( - CuratedEntryEvent.verifyCanonical(suggestion(), schema, coordinate, curator) - .any { it.reason == CuratedEntryProblem.Reason.WrongKind } - ) - } - - @Test - fun `a suggestion has to reply to this schema`() { - assertEquals( - listOf(CuratedEntryProblem(CuratedEntryEvent.FIELD_SCHEMA, CuratedEntryProblem.Reason.NotAReply)), - CuratedEntryEvent.verifySuggestion(suggestion(tags = riseAndRise.without("a")), schema, coordinate) - ) - - // Somebody else's list with the same identifier is somebody else's list. - val elsewhere = riseAndRise.replacing("a", "31889:$stranger:bitcoin.mov") - assertEquals( - listOf(CuratedEntryProblem(CuratedEntryEvent.FIELD_SCHEMA, CuratedEntryProblem.Reason.RepliesElsewhere)), - CuratedEntryEvent.verifySuggestion(suggestion(tags = elsewhere), schema, coordinate) - ) - } - - @Test - fun `a required field has to be there`() { - assertEquals( - listOf(CuratedEntryProblem("title", CuratedEntryProblem.Reason.Missing)), - CuratedEntryEvent.verifySuggestion(suggestion(tags = riseAndRise.without("title")), schema, coordinate) - ) - assertEquals( - listOf(CuratedEntryProblem("type", CuratedEntryProblem.Reason.Missing)), - CuratedEntryEvent.verifySuggestion(suggestion(tags = riseAndRise.without("type")), schema, coordinate) - ) - } - - @Test - fun `a field that does not repeat appears once`() { - val twoPosters = riseAndRise + arrayOf(arrayOf("image", "https://example.com/other.jpg")) - assertEquals( - listOf(CuratedEntryProblem("image", CuratedEntryProblem.Reason.Repeated)), - CuratedEntryEvent.verifySuggestion(suggestion(tags = twoPosters), schema, coordinate) - ) - - // Where the schema says `repeat`, two is fine -- and both are read. - val twoWatchLinks = riseAndRise + arrayOf(arrayOf("r", "https://vimeo.com/1", "watch")) - assertEquals(emptyList(), CuratedEntryEvent.verifySuggestion(suggestion(tags = twoWatchLinks), schema, coordinate)) - assertEquals( - listOf("http://bitcoindoc.com/", "https://vimeo.com/1"), - CuratedEntryEvent.read(suggestion(tags = twoWatchLinks), schema).values["watchUrl"] - ) - } - - @Test - fun `every value has to match its field`() { - fun problemsWith(tag: String, value: String) = - CuratedEntryEvent.verifySuggestion(suggestion(tags = riseAndRise.replacing(tag, value)), schema, coordinate) - - // The things the doc lists as rejected, and why they matter. - assertEquals(listOf(CuratedEntryProblem("type", CuratedEntryProblem.Reason.NotAnOption)), problemsWith("type", "musical")) - assertEquals(listOf(CuratedEntryProblem("year", CuratedEntryProblem.Reason.BelowMinimum)), problemsWith("year", "1800")) - assertEquals(listOf(CuratedEntryProblem("year", CuratedEntryProblem.Reason.AboveMaximum)), problemsWith("year", "2200")) - assertEquals(listOf(CuratedEntryProblem("year", CuratedEntryProblem.Reason.NotAWholeNumber)), problemsWith("year", "twenty fourteen")) - assertEquals(listOf(CuratedEntryProblem("image", CuratedEntryProblem.Reason.NotHttps)), problemsWith("image", "http://example.com/poster.jpg")) - assertEquals(listOf(CuratedEntryProblem("title", CuratedEntryProblem.Reason.TooLong)), problemsWith("title", "x".repeat(201))) - assertEquals(listOf(CuratedEntryProblem("identifier", CuratedEntryProblem.Reason.NotOneWord)), problemsWith("d", "imdb tt2821314")) - - // A `javascript:` link ends up in an href. Replacing the watch link - // leaves the IMDb one, so require-any is still met and the URL is the - // only complaint. - val scripted = riseAndRise.map { - if (it[0] == "r" && it[2] == "watch") arrayOf("r", "javascript:alert(1)", "watch") else it - }.toTypedArray() - assertEquals( - listOf(CuratedEntryProblem("watchUrl", CuratedEntryProblem.Reason.NotAUrl)), - CuratedEntryEvent.verifySuggestion(suggestion(tags = scripted), schema, coordinate) - ) - } - - @Test - fun `a require-any group needs one of its fields`() { - val noLinks = riseAndRise.filter { it[0] != "r" }.toTypedArray() - - // Filed under the group's first field, so a form can show it inline. - assertEquals( - listOf(CuratedEntryProblem("watchUrl", CuratedEntryProblem.Reason.RequireAnyUnmet)), - CuratedEntryEvent.verifySuggestion(suggestion(tags = noLinks), schema, coordinate) - ) - } - - @Test - fun `a closed list takes suggestions from the curator and the suggesters it names`() { - val closed = schema.copy(visibility = CuratedVisibility.Closed, suggesters = listOf(suggester)) - - assertEquals(emptyList(), CuratedEntryEvent.verifySuggestion(suggestion(pubKey = suggester), closed, coordinate)) - assertEquals(emptyList(), CuratedEntryEvent.verifySuggestion(suggestion(pubKey = curator), closed, coordinate)) - assertEquals( - listOf(CuratedEntryProblem(CuratedEntryEvent.FIELD_VISIBILITY, CuratedEntryProblem.Reason.NotPermitted)), - CuratedEntryEvent.verifySuggestion(suggestion(pubKey = stranger), closed, coordinate) - ) - - // Private is the same rule; the difference is who is shown the list, not who may write to it. - val private = closed.copy(visibility = CuratedVisibility.Private) - assertEquals( - listOf(CuratedEntryProblem(CuratedEntryEvent.FIELD_VISIBILITY, CuratedEntryProblem.Reason.NotPermitted)), - CuratedEntryEvent.verifySuggestion(suggestion(pubKey = stranger), private, coordinate) - ) - } - - @Test - fun `a value is checked by its type and its config`() { - val duration = CuratedField("runtime", CuratedFieldType.Duration, isRequired = false, config = CuratedFieldConfig(max = 36000)) - assertEquals(CuratedEntryProblem.Reason.NotPositive, CuratedEntryEvent.checkValue(duration, "0")) - assertEquals(CuratedEntryProblem.Reason.AboveMaximum, CuratedEntryEvent.checkValue(duration, "36001")) - // A numeric `max` is a bound, not a length: six digits under the bound is fine. - assertNull(CuratedEntryEvent.checkValue(duration, " 5400 ")) - - val pattern = CuratedField("code", CuratedFieldType.Token, isRequired = false, config = CuratedFieldConfig(pattern = "[a-z]{2,8}")) - assertNull(CuratedEntryEvent.checkValue(pattern, "abc")) - // End to end, not anywhere within. - assertEquals(CuratedEntryProblem.Reason.PatternMismatch, CuratedEntryEvent.checkValue(pattern, "abc1")) - - // A pattern this platform cannot compile is a check it cannot make, and - // an entry it cannot check is not one it vouches for. - val broken = pattern.copy(config = CuratedFieldConfig(pattern = "[unclosed")) - assertEquals(CuratedEntryProblem.Reason.PatternMismatch, CuratedEntryEvent.checkValue(broken, "abc")) - - assertEquals(CuratedEntryProblem.Reason.Empty, CuratedEntryEvent.checkValue(pattern, " ")) - - val strict = CuratedField("site", CuratedFieldType.Url, isRequired = false, config = CuratedFieldConfig(https = true)) - assertEquals(CuratedEntryProblem.Reason.NotHttps, CuratedEntryEvent.checkValue(strict, "http://example.com")) - assertNull(CuratedEntryEvent.checkValue(strict, "https://example.com")) - } - - @Test - fun `a date is checked at whatever precision it was written`() { - val died = CuratedField("died", CuratedFieldType.Date, isRequired = true, config = CuratedFieldConfig(min = 2009, max = 2100)) - - // The three precisions the NIP allows, and a leap day on a leap year. - listOf("2014", "2014-02", "2014-02-28", "2016-02-29", " 2014-02-28 ").forEach { value -> - assertNull(CuratedEntryEvent.checkValue(died, value), "\"$value\" was refused") - } - - // Not one of the three shapes, or a day the calendar does not have. - listOf("2014-13", "2014-00", "2014-02-30", "2014-02-00", "2015-02-29", "2100-02-29", "14-02-28", "2014/02/28", "2014-2-28", "2014-02-28T00:00", "twenty fourteen").forEach { value -> - assertEquals(CuratedEntryProblem.Reason.NotADate, CuratedEntryEvent.checkValue(died, value), "\"$value\" was accepted") - } - - // `min` and `max` bound the year, at whatever precision. - assertEquals(CuratedEntryProblem.Reason.BelowMinimum, CuratedEntryEvent.checkValue(died, "2008-12-31")) - assertEquals(CuratedEntryProblem.Reason.BelowMinimum, CuratedEntryEvent.checkValue(died, "2008")) - assertEquals(CuratedEntryProblem.Reason.AboveMaximum, CuratedEntryEvent.checkValue(died, "2101-01")) - assertNull(CuratedEntryEvent.checkValue(died, "2009-01-03")) - assertNull(CuratedEntryEvent.checkValue(died, "2100")) - - // A date's `max` is a year and never a length: ten characters under a - // bound of eight is fine. And the year 2000 was a leap year, unlike 1900. - val early = died.copy(config = CuratedFieldConfig(max = 8)) - assertNull(CuratedEntryEvent.checkValue(early, "0005-06-07")) - assertNull(CuratedEntryEvent.checkValue(died.copy(config = CuratedFieldConfig()), "2000-02-29")) - assertEquals(CuratedEntryProblem.Reason.NotADate, CuratedEntryEvent.checkValue(died.copy(config = CuratedFieldConfig()), "1900-02-29")) - - assertEquals(CuratedEntryProblem.Reason.Empty, CuratedEntryEvent.checkValue(died, " ")) - } - - @Test - fun `a date keeps the precision it was written at`() { - assertEquals(CuratedDate(2014), CuratedDate.parse("2014")) - assertEquals(CuratedDate(2010, 7), CuratedDate.parse("2010-07")) - assertEquals(CuratedDate(2014, 2, 28), CuratedDate.parse(" 2014-02-28 ")) - assertNull(CuratedDate.parse("2014-")) - assertNull(CuratedDate.parse("")) - } - - @Test - fun `a coordinate splits on the first two colons only`() { - val parsed = assertNotNull(CuratedCoordinate.parse("31888:${suggester.uppercase()}:imdb:tt2821314")) - - assertEquals(31888, parsed.kind) - assertEquals(suggester, parsed.pubKey, "the pubkey was not lowercased") - assertEquals("imdb:tt2821314", parsed.identifier, "the identifier's own colon split it") - assertEquals("31888:$suggester:imdb:tt2821314", parsed.toValue()) - - assertNull(CuratedCoordinate.parse("31888:$suggester:"), "an empty identifier was accepted") - assertNull(CuratedCoordinate.parse("31888:not-a-pubkey:x")) - assertNull(CuratedCoordinate.parse("naddr1qqxnzd3cxqmrzv3exgmr2wfeqgs"), "a bech32 address is not a coordinate") - } - - // -- the write side ----------------------------------------------------------- - - /** The NIP's example, less the tags its schema does not define, which the builder cannot know to write. */ - private val riseAndRiseAsTheSchemaKnowsIt: List> = riseAndRise - .filterNot { it[0] == "director" || it[0] == "i" || it[0] == "lang" } - .map { it.toList() } - - private val sourceBlock: List> = listOf( - listOf("a", "31888:$suggester:imdb:tt2821314", "", "mention"), - listOf("e", suggestionId, "", "mention"), - listOf("p", suggester), - ) - - @Test - fun `the canonical entry built from the NIP's suggestion is the NIP's canonical entry`() { - val suggested = CuratedEntryEvent.read(suggestion(), schema) - - val template = CuratedEntryEvent.canonicalTemplate( - schema = schema, - coordinate = coordinate, - curator = curator, - values = suggested.values, - source = CuratedSuggestionRef.of(suggested), - createdAt = 1735689720, - ) - - assertEquals(CuratedEntryEvent.CANONICAL_KIND, template.kind) - assertEquals(review, template.content) - // The first two blocks identical to the suggestion's, the third the - // pointer back: the doc's own description of the example. - assertEquals(riseAndRiseAsTheSchemaKnowsIt + sourceBlock, template.tags.map { it.toList() }) - - val preview = CuratedEntryEvent.preview(template, curator) - assertEquals(emptyList(), CuratedEntryEvent.verifyCanonical(preview, schema, coordinate, curator)) - - // And it reads back as what went in, which is the property the form - // and the queue rely on: the values, the `d`, and where it came from. - val entry = assertNotNull(CuratedEntryEvent.canonical(preview, schema, coordinate, curator)) - assertEquals(suggested.values, entry.values) - assertEquals("imdb:tt2821314", entry.identifier) - assertEquals(CuratedSuggestionRef(suggestionId, "31888:$suggester:imdb:tt2821314", suggester), entry.source) - } - - @Test - fun `an edit on the way through is what is signed and the d is what was suggested`() { - val suggested = CuratedEntryEvent.read(suggestion(), schema) - val corrected = suggested.values + mapOf( - "year" to listOf("2015"), - "image" to listOf("https://example.com/a-better-poster.jpg"), - ) - - val template = CuratedEntryEvent.canonicalTemplate(schema, coordinate, curator, corrected, CuratedSuggestionRef.of(suggested)) - val preview = CuratedEntryEvent.preview(template, curator) - - assertEquals(emptyList(), CuratedEntryEvent.verifyCanonical(preview, schema, coordinate, curator)) - - val entry = assertNotNull(CuratedEntryEvent.canonical(preview, schema, coordinate, curator)) - assertEquals("2015", entry.value("year")) - assertEquals("https://example.com/a-better-poster.jpg", entry.value("image")) - // Same coordinate as before the edit, so re-curating revises rather than adds. - assertEquals("31890:$curator:imdb:tt2821314", entry.coordinate()) - } - - @Test - fun `a value the schema refuses is refused with its field named not clipped`() { - val suggested = CuratedEntryEvent.read(suggestion(), schema) - val wrong = suggested.values + mapOf( - "year" to listOf("twenty fourteen"), - "title" to listOf("x".repeat(201)), - "type" to listOf("musical"), - ) - - val template = CuratedEntryEvent.canonicalTemplate(schema, coordinate, curator, wrong) - val problems = CuratedEntryEvent.verifyCanonical(CuratedEntryEvent.preview(template, curator), schema, coordinate, curator) - - assertEquals( - setOf( - CuratedEntryProblem("title", CuratedEntryProblem.Reason.TooLong), - CuratedEntryProblem("year", CuratedEntryProblem.Reason.NotAWholeNumber), - CuratedEntryProblem("type", CuratedEntryProblem.Reason.NotAnOption), - ), - problems.toSet() - ) - - // The reference clips a long title to its cap; this does not, because - // the form shows the problem and the member decides how to shorten it. - assertEquals("x".repeat(201), template.tags.first { it[0] == "title" }[1]) - } - - @Test - fun `a blank is not a value a field that repeats takes all of them and one that does not takes the first`() { - val template = CuratedEntryEvent.canonicalTemplate( - schema = schema, - coordinate = coordinate, - curator = curator, - values = mapOf( - "identifier" to listOf("imdb:tt2821314"), - "title" to listOf(" The Rise and Rise of Bitcoin ", "A second title nobody asked for"), - "type" to listOf("documentary"), - "year" to listOf(" "), - "watchUrl" to listOf("http://bitcoindoc.com/", "", "https://mirror.example/watch"), - "description" to listOf(""), - ), - ) - - val tags = template.tags.map { it.toList() } - - assertEquals(listOf(listOf("title", "The Rise and Rise of Bitcoin")), tags.filter { it[0] == "title" }) - assertEquals(emptyList(), tags.filter { it[0] == "year" }) - assertEquals( - listOf( - listOf("r", "http://bitcoindoc.com/", "watch"), - listOf("r", "https://mirror.example/watch", "watch"), - ), - tags.filter { it[0] == "r" } - ) - assertEquals("", template.content) - assertEquals( - emptyList(), - CuratedEntryEvent.verifyCanonical(CuratedEntryEvent.preview(template, curator), schema, coordinate, curator) - ) - } - - @Test - fun `an entry nobody suggested has no source block and the root carries the schema's first relay`() { - val values = CuratedEntryEvent.read(suggestion(), schema).values - - val template = CuratedEntryEvent.canonicalTemplate(schema, coordinate, curator, values, source = null) - val tags = template.tags.map { it.toList() } - - assertEquals(listOf(listOf("a", coordinate, "wss://ephemeral.mantra.press", "root")), tags.filter { it[0] == "a" }) - assertEquals(listOf(listOf("p", curator)), tags.filter { it[0] == "p" }) - assertEquals(emptyList(), tags.filter { it[0] == "e" }) - - val entry = assertNotNull( - CuratedEntryEvent.canonical(CuratedEntryEvent.preview(template, curator), schema, coordinate, curator) - ) - assertNull(entry.source) - } - - @Test - fun `an entry keeps its dates from the suggestion to the list`() { - // The case behind bitcoin.necropolis.report's fourteen dateless entries: - // a build that could not see a `date` field accepted suggestions that - // had one and signed entries that did not. The two dates have to make - // it through the reading and the template both. - val necropolis = assertNotNull( - CuratedSchemaEvent.parse( - Event( - id = "a".repeat(64), - pubKey = curator, - createdAt = 1735689600, - kind = CuratedSchemaEvent.KIND, - tags = arrayOf( - arrayOf("d", "bitcoin.necropolis.report"), - arrayOf("title", "bitcoin.necropolis.report suggestion"), - arrayOf("name", "bitcoin.necropolis.report"), - arrayOf("description", "Bitcoin companies that are no more."), - arrayOf("visibility", "public"), - arrayOf("field", "identifier", "token", "required", "", "Identifier", "{\"tag\":\"d\",\"max\":80,\"derived\":true}"), - arrayOf("field", "title", "text", "required", "", "Title", "{\"max\":200}"), - arrayOf("field", "founded", "date", "optional", "2010-07", "Founded", "{\"min\":1900,\"max\":2100}"), - arrayOf("field", "died", "date", "required", "2014-02-28", "Died", "{\"min\":2009,\"max\":2100}"), - ), - content = "", - sig = "b".repeat(128), - ) - ) - ) - val necropolisCoordinate = "31889:$curator:bitcoin.necropolis.report" - - val mtGox = suggestion( - tags = arrayOf( - arrayOf("d", "domain:mtgox.com"), - arrayOf("title", "Mt. Gox"), - arrayOf("founded", "2010-07"), - arrayOf("died", "2014-02-28"), - arrayOf("a", necropolisCoordinate, "", "root"), - ), - content = "", - ) - assertEquals(emptyList(), CuratedEntryEvent.verifySuggestion(mtGox, necropolis, necropolisCoordinate)) - - val suggested = CuratedEntryEvent.read(mtGox, necropolis) - assertEquals("2010-07", suggested.value("founded")) - assertEquals("2014-02-28", suggested.value("died")) - - val template = CuratedEntryEvent.canonicalTemplate(necropolis, necropolisCoordinate, curator, suggested.values, CuratedSuggestionRef.of(suggested)) - val tags = template.tags.map { it.toList() } - assertEquals(listOf(listOf("founded", "2010-07")), tags.filter { it[0] == "founded" }) - assertEquals(listOf(listOf("died", "2014-02-28")), tags.filter { it[0] == "died" }) - - val entry = assertNotNull( - CuratedEntryEvent.canonical(CuratedEntryEvent.preview(template, curator), necropolis, necropolisCoordinate, curator) - ) - assertEquals(suggested.values, entry.values) - - // And without the `died`, the entry is refused for the field it lacks -- - // which is what every conforming client did to the fourteen. - val dateless = CuratedEntryEvent.canonicalTemplate(necropolis, necropolisCoordinate, curator, suggested.values - "died") - assertEquals( - listOf(CuratedEntryProblem("died", CuratedEntryProblem.Reason.Missing)), - CuratedEntryEvent.verifyCanonical(CuratedEntryEvent.preview(dateless, curator), necropolis, necropolisCoordinate, curator) - ) - } - - @Test - fun `a required field of a type this app cannot write is a reason not to`() { - // What the fourteen should have run into. A type this build does not - // know is left out of the reading, as the NIP allows; an entry written - // without it, when the schema requires it, is one every other client - // refuses. So the write side refuses first, and names the field. - val stars = arrayOf("field", "rating", "stars", "required", "5", "Rating", "{}") - val withStars = CuratedSchemaEvent.read(schemaTags() + stars, "").normalized() - assertEquals( - listOf(CuratedEntryProblem("rating", CuratedEntryProblem.Reason.UnsupportedType)), - CuratedEntryEvent.verifyWritable(withStars) - ) - - // Reading is untouched: the NIP's suggestion still satisfies the schema, - // rating or no rating. - assertEquals(emptyList(), CuratedEntryEvent.verifySuggestion(suggestion(), withStars, coordinate)) - - // An optional one is left out the way the reading leaves it out. - val optional = CuratedSchemaEvent.read(schemaTags() + arrayOf("field", "rating", "stars", "optional", "", "", "{}"), "").normalized() - assertEquals(emptyList(), CuratedEntryEvent.verifyWritable(optional)) - assertEquals(emptyList(), CuratedEntryEvent.verifyWritable(schema)) - } - - @Test - fun `only a suggestion can be pointed at`() { - val theListsOwn = assertNotNull(CuratedEntryEvent.canonical(canonical(), schema, coordinate, curator)) - - assertFailsWith { CuratedSuggestionRef.of(theListsOwn) } - } - - @Test - fun `the headline needs no schema`() { - val entry = CuratedEntryEvent.headline(canonical()) - - assertEquals("The Rise and Rise of Bitcoin", entry.title) - assertEquals("imdb:tt2821314", entry.identifier) - assertEquals(suggester, entry.source?.pubKey) - assertEquals(emptyMap(), entry.values) - } - - /** The NIP's schema's tags, for a test that wants one more of them. */ - private fun schemaTags(): Array> = CuratedSchemaEvent.template(schema, createdAt = 1735689600).tags - - private fun suggestion( - tags: Array> = riseAndRise, - content: String = review, - kind: Int = CuratedEntryEvent.SUGGESTION_KIND, - pubKey: String = suggester, - ): Event = Event( - id = suggestionId, - pubKey = pubKey, - createdAt = 1735689660, - kind = kind, - tags = tags, - content = content, - sig = "b".repeat(128), - ) - - /** The curator signing off on the suggestion, as the NIP's example has it. */ - private fun canonical( - tags: Array> = riseAndRise + arrayOf( - arrayOf("a", "31888:$suggester:imdb:tt2821314", "", "mention"), - arrayOf("e", suggestionId, "", "mention"), - arrayOf("p", suggester), - ), - pubKey: String = curator, - ): Event = Event( - id = "c".repeat(64), - pubKey = pubKey, - createdAt = 1735689720, - kind = CuratedEntryEvent.CANONICAL_KIND, - tags = tags, - content = review, - sig = "b".repeat(128), - ) - - private fun Array>.without(tag: String): Array> = - filter { it[0] != tag }.toTypedArray() - - private fun Array>.replacing(tag: String, value: String): Array> = - map { if (it[0] == tag) arrayOf(tag, value) + it.drop(2) else it }.toTypedArray() -} diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/curated/CuratedSchemaEventTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/curated/CuratedSchemaEventTest.kt deleted file mode 100644 index 5fec47f1..00000000 --- a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/curated/CuratedSchemaEventTest.kt +++ /dev/null @@ -1,507 +0,0 @@ -package com.machankura.bennu.compose.nostr.curated - -import com.vitorpamplona.quartz.nip01Core.core.Event -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFalse -import kotlin.test.assertNotNull -import kotlin.test.assertNull -import kotlin.test.assertTrue - -/** - * Kind 31889 as the NIP writes it, read and written back. - * - * The fixture is the bitcoin.mov schema from the NIP's own example, tag for tag, - * because the point of publishing a schema is that another client can drive its - * form from it -- so the one thing worth pinning is that what that site published - * reads here, and that what this app signs would read there. - * - * The other half is the rejection list. A schema is what suggestions are checked - * against, and a reader that repaired a broken one would be accepting entries - * against a form nobody signed. Every rule the NIP says a client MUST refuse on - * has a case here, and so does the one repair it says a client MUST make. - */ -class CuratedSchemaEventTest { - private val curator = "7c965d8c2acdfd635562da3bcb82596b595be28b008d8b54ec702ed4c67d9d25" - - private val description = "Fields for a bitcoin.mov entry: a Bitcoin movie, documentary, " + - "short, interview or series, with at least one link to watch or look it up." - - /** The NIP's example, as published. */ - private val bitcoinMov: Array> = arrayOf( - arrayOf("d", "bitcoin.mov"), - arrayOf("title", "bitcoin.mov suggestion"), - arrayOf("name", "bitcoin.mov"), - arrayOf("description", description), - arrayOf("k", "31888"), - arrayOf("visibility", "public"), - arrayOf("picture", "https://bitcoin.mov/icon.svg"), - arrayOf("domain", "bitcoin.mov"), - arrayOf("relay", "wss://ephemeral.mantra.press"), - arrayOf("field", "identifier", "token", "required", "the-rise-and-rise-of-bitcoin-2014", "Identifier", "{\"tag\":\"d\",\"max\":80,\"derived\":true}"), - arrayOf("field", "title", "text", "required", "The Rise and Rise of Bitcoin", "Title", "{\"max\":200}"), - arrayOf("field", "year", "year", "optional", "2014", "Year", "{\"min\":1900,\"max\":2100}"), - arrayOf("field", "type", "enum", "required", "documentary", "Type", "{\"options\":[\"movie\",\"documentary\",\"short\",\"interview\",\"series\",\"other\"]}"), - arrayOf("field", "watchUrl", "url", "optional", "https://youtube.com/watch?v=…", "Watch / reference URL", "{\"tag\":\"r\",\"marker\":\"watch\",\"max\":500,\"repeat\":true}"), - arrayOf("field", "imdbUrl", "url", "optional", "https://imdb.com/title/tt2821314", "IMDb URL", "{\"tag\":\"r\",\"marker\":\"imdb\",\"max\":500}"), - arrayOf("field", "image", "image", "optional", "https://…/poster.jpg", "Poster image URL (https)", "{\"max\":500}"), - arrayOf("field", "hashtags", "token", "optional", "bitcoin", "Hashtags", "{\"tag\":\"t\",\"max\":60,\"repeat\":true,\"derived\":true}"), - arrayOf("field", "description", "longtext", "optional", "Why is this worth watching?", "Description / review", "{\"tag\":\"content\",\"max\":4000}"), - arrayOf("require-any", "watchUrl", "imdbUrl"), - ) - - @Test - fun `the bitcoin_mov schema reads as published`() { - val schema = assertNotNull(CuratedSchemaEvent.parse(event())) - - assertEquals("bitcoin.mov", schema.identifier) - assertEquals("bitcoin.mov suggestion", schema.title) - assertEquals("bitcoin.mov", schema.name) - assertEquals(description, schema.description) - assertEquals(CuratedVisibility.Public, schema.visibility) - assertEquals("https://bitcoin.mov/icon.svg", schema.picture) - assertEquals("bitcoin.mov", schema.domain) - assertEquals(31888, schema.suggestionKind) - assertEquals(listOf("wss://ephemeral.mantra.press"), schema.relays) - assertEquals(listOf(listOf("watchUrl", "imdbUrl")), schema.requireAny) - assertEquals(emptyList(), schema.suggesters) - - assertEquals( - listOf("identifier", "title", "year", "type", "watchUrl", "imdbUrl", "image", "hashtags", "description"), - schema.fields.map { it.name } - ) - - // The positional parts and the config, on the field that uses most of them. - val watchUrl = schema.fields.first { it.name == "watchUrl" } - assertEquals(CuratedFieldType.Url, watchUrl.type) - assertFalse(watchUrl.isRequired) - assertEquals("https://youtube.com/watch?v=…", watchUrl.placeholder) - assertEquals("Watch / reference URL", watchUrl.label) - assertEquals("r", watchUrl.tag()) - assertEquals("watch", watchUrl.config.marker) - assertEquals(500L, watchUrl.config.max) - assertEquals(true, watchUrl.config.repeat) - - val type = schema.fields.first { it.name == "type" } - assertEquals(listOf("movie", "documentary", "short", "interview", "series", "other"), type.config.options) - - val identifier = schema.fields.first { it.name == "identifier" } - assertEquals("d", identifier.tag()) - assertEquals(true, identifier.config.derived) - assertTrue(identifier.isRequired) - - // Derived fields are filled in by the client, so a form does not ask. - assertEquals( - listOf("title", "year", "type", "watchUrl", "imdbUrl", "image", "description"), - schema.formFields().map { it.name } - ) - } - - @Test - fun `the domain stands in for the name wherever the list is shown`() { - val schema = assertNotNull(CuratedSchemaEvent.parse(event())) - assertEquals("bitcoin.mov", schema.displayName()) - - val withoutDomain = assertNotNull( - CuratedSchemaEvent.parse(event(tags = bitcoinMov.without("domain").replacing("name", "Bitcoin on screen"))) - ) - assertEquals("Bitcoin on screen", withoutDomain.displayName()) - } - - @Test - fun `a schema round trips through the template`() { - val read = assertNotNull(CuratedSchemaEvent.parse(event())) - - val template = CuratedSchemaEvent.template(read, createdAt = 1735689600) - assertEquals(CuratedSchemaEvent.KIND, template.kind) - // The content mirrors the description, for clients that read content. - assertEquals(description, template.content) - - val reread = assertNotNull(CuratedSchemaEvent.parse(event(tags = template.tags, content = template.content))) - assertEquals(read, reread) - - // And the tags come out in the NIP's order, identity first. - assertEquals( - listOf("d", "title", "name", "description", "k", "visibility", "picture", "domain"), - template.tags.take(8).map { it[0] } - ) - assertEquals(9, template.tags.count { it[0] == "field" }) - assertEquals(listOf("require-any", "watchUrl", "imdbUrl"), template.tags.first { it[0] == "require-any" }.toList()) - assertEquals(listOf("relay", "wss://ephemeral.mantra.press"), template.tags.last().toList()) - } - - @Test - fun `a field tag is written the way the NIP shows it`() { - val schema = assertNotNull(CuratedSchemaEvent.parse(event())) - val tag = schema.fields.first { it.name == "watchUrl" }.toTagArray() - - assertEquals( - listOf("field", "watchUrl", "url", "optional", "https://youtube.com/watch?v=…", "Watch / reference URL", - "{\"tag\":\"r\",\"marker\":\"watch\",\"max\":500,\"repeat\":true}"), - tag.toList() - ) - } - - @Test - fun `a config key this app does not know survives a round trip`() { - // Other clients legitimately add their own. Editing a field here must - // not strip what one of them meant by it. - val field = assertNotNull( - CuratedField.parse(arrayOf("field", "lang", "token", "optional", "en", "Language", "{\"max\":60,\"locale\":\"bcp47\"}")) - ) - - assertEquals(60L, field.config.max) - assertEquals("\"bcp47\"", field.config.others["locale"].toString()) - assertEquals("{\"max\":60,\"locale\":\"bcp47\"}", field.config.toJson()) - } - - @Test - fun `a malformed config costs the field its constraints and not its life`() { - listOf("{not json", "[1,2]", "\"a string\"", "42", "").forEach { blob -> - val field = assertNotNull( - CuratedField.parse(arrayOf("field", "year", "year", "optional", "2014", "Year", blob)), - "the field was dropped over the config \"$blob\"" - ) - assertEquals(CuratedFieldConfig(), field.config, "the config \"$blob\" read as something") - } - - // A known key of the wrong type is dropped rather than kept as something - // it is not; the rest of the blob is kept. - val field = assertNotNull( - CuratedField.parse(arrayOf("field", "year", "year", "optional", "", "", "{\"max\":\"lots\",\"min\":1900}")) - ) - assertNull(field.config.max) - assertEquals(1900L, field.config.min) - } - - @Test - fun `a date field reads as one with its bounds on the year`() { - // bitcoin.necropolis.report's two, as published. Fourteen of its - // entries lost their `died` to a build that dropped the type on the - // way in and then wrote entries without it. - val schema = assertNotNull( - CuratedSchemaEvent.parse( - event( - tags = bitcoinMov.plus( - listOf( - arrayOf("field", "founded", "date", "optional", "2010-07", "Founded", "{\"min\":1900,\"max\":2100,\"hint\":\"YYYY, YYYY-MM or YYYY-MM-DD.\"}"), - arrayOf("field", "died", "date", "required", "2014-02-28", "Died", "{\"min\":2009,\"max\":2100}"), - ) - ) - ) - ) - ) - - val died = schema.fields.first { it.name == "died" } - assertEquals(CuratedFieldType.Date, died.type) - assertTrue(died.isRequired) - assertEquals("2014-02-28", died.placeholder) - assertEquals("Died", died.label) - assertEquals(2009L, died.config.min) - assertEquals(2100L, died.config.max) - - // Its bounds are years, so `max` is a bound and not a length -- but the - // value is not a number, and no keyboard should think it is. - assertTrue(died.type.isBounded) - assertFalse(died.type.isNumeric) - - assertEquals(listOf("founded", "died"), schema.formFields().takeLast(2).map { it.name }) - assertEquals(emptyList(), schema.unsupportedFields) - - assertEquals( - listOf("field", "died", "date", "required", "2014-02-28", "Died", "{\"max\":2100,\"min\":2009}"), - died.toTagArray().toList() - ) - } - - @Test - fun `a field with an unknown type is kept aside one with no name is dropped and the rest are kept`() { - val stars = arrayOf("field", "rating", "stars", "required", "5", "Rating", "{\"max\":5}") - val schema = assertNotNull( - CuratedSchemaEvent.parse( - event( - tags = bitcoinMov.plus( - listOf( - stars, - arrayOf("field", " ", "text", "optional", "", "", "{}"), - arrayOf("field", "short"), - ) - ) - ) - ) - ) - - assertEquals(9, schema.fields.size) - - // A type this build does not know is not a type nobody knows. The - // reader says which field it could not read rather than forgetting - // it, so a writer can refuse to publish an entry without it. - assertEquals( - listOf(CuratedUnsupportedField("rating", "stars", isRequired = true, label = "Rating", tag = stars.toList())), - schema.unsupportedFields - ) - - // And the template writes it back as it came, after the fields it does - // know, so that an edit here cannot sign the list's rules away. - val template = CuratedSchemaEvent.template(schema, createdAt = 1735689600) - val fields = template.tags.filter { it[0] == "field" } - assertEquals(10, fields.size) - assertEquals(stars.toList(), fields.last().toList()) - assertEquals(schema, CuratedSchemaEvent.parse(event(tags = template.tags, content = template.content))) - } - - @Test - fun `a field missing its trailing positions still reads`() { - val field = assertNotNull(CuratedField.parse(arrayOf("field", "director", "text"))) - - assertEquals("director", field.name) - assertFalse(field.isRequired) - assertEquals("", field.placeholder) - assertEquals("director", field.labelOrName()) - assertEquals(CuratedFieldConfig(), field.config) - } - - @Test - fun `a schema missing an identity tag is not usable`() { - mapOf( - "d" to CuratedSchemaProblem.IdentifierMissing, - "title" to CuratedSchemaProblem.TitleMissing, - "name" to CuratedSchemaProblem.NameMissing, - ).forEach { (tag, problem) -> - val tags = without(tag) - assertNull(CuratedSchemaEvent.parse(event(tags = tags)), "a schema without \"$tag\" was accepted") - assertEquals(listOf(problem), CuratedSchemaEvent.read(tags, description).problems()) - } - - // The description alone has a fallback: the content, which is where - // generic clients put it. Empty both and it is missing. - assertNull(CuratedSchemaEvent.parse(event(tags = without("description"), content = ""))) - assertEquals( - listOf(CuratedSchemaProblem.DescriptionMissing), - CuratedSchemaEvent.read(without("description"), " ").problems() - ) - } - - @Test - fun `the description falls back to the content and the tag wins when both are there`() { - val fromContent = assertNotNull( - CuratedSchemaEvent.parse(event(tags = without("description"), content = " What the content says. ")) - ) - assertEquals("What the content says.", fromContent.description) - - val fromTag = assertNotNull(CuratedSchemaEvent.parse(event(content = "Something else entirely"))) - assertEquals(description, fromTag.description) - } - - @Test - fun `visibility is never guessed`() { - assertNull(CuratedSchemaEvent.parse(event(tags = without("visibility")))) - assertEquals( - listOf(CuratedSchemaProblem.VisibilityMissing), - CuratedSchemaEvent.read(without("visibility"), description).problems() - ) - - assertNull(CuratedSchemaEvent.parse(event(tags = replacing("visibility", "friends")))) - assertNull(CuratedSchemaEvent.parse(event(tags = replacing("visibility", "")))) - - // Case and whitespace are forgiven; a fourth word is not. - assertEquals(CuratedVisibility.Closed, CuratedSchemaEvent.parse(event(tags = replacing("visibility", " Closed ")))?.visibility) - assertEquals(CuratedVisibility.Private, CuratedSchemaEvent.parse(event(tags = replacing("visibility", "PRIVATE")))?.visibility) - } - - @Test - fun `a schema with no fields is not usable`() { - val tags = bitcoinMov.filterNot { it[0] == "field" }.toTypedArray() - - assertNull(CuratedSchemaEvent.parse(event(tags = tags))) - assertEquals(listOf(CuratedSchemaProblem.NoFields), CuratedSchemaEvent.read(tags, description).problems()) - - // Checked before the mandatory fields are put back, which is the NIP's - // rule: "no field tags" is about what the publisher said. - val onlyUnparseable = tags.plus(arrayOf("field", "rating", "stars", "optional", "", "", "{}")) - assertNull(CuratedSchemaEvent.parse(event(tags = onlyUnparseable))) - } - - @Test - fun `a picture that is not https is not usable`() { - listOf("http://bitcoin.mov/icon.svg", "bitcoin.mov/icon.svg", "javascript:alert(1)", "https://").forEach { picture -> - assertNull( - CuratedSchemaEvent.parse(event(tags = replacing("picture", picture))), - "a schema with the picture \"$picture\" was accepted" - ) - } - - // Absent is fine; it is optional. - assertNull(CuratedSchemaEvent.parse(event(tags = without("picture")))?.picture) - assertTrue(CuratedSchemaEvent.read(without("picture"), description).isUsable()) - } - - @Test - fun `a domain that is not a hostname is not usable and one that is gets normalized`() { - listOf("bitcoin", "localhost", "bit coin.mov", "-bitcoin.mov", "bitcoin_mov.example").forEach { domain -> - assertNull( - CuratedSchemaEvent.parse(event(tags = replacing("domain", domain))), - "a schema with the domain \"$domain\" was accepted" - ) - } - - // Lenient on input, strict on what is kept: the things people paste - // around a hostname come off, and what is left is what is checked. - assertEquals("bitcoin.mov", CuratedSchemaEvent.parse(event(tags = replacing("domain", "https://Bitcoin.MOV/")))?.domain) - assertEquals("bitcoin.mov", CuratedSchemaEvent.parse(event(tags = replacing("domain", "bitcoin.mov:8080/x y")))?.domain) - assertEquals("bitcoin.mov", CuratedSchemaEvent.normalizeDomain("@Bitcoin.mov:443/path.")) - assertTrue(CuratedSchemaEvent.isDomain("sub.example.co.za")) - assertFalse(CuratedSchemaEvent.isDomain("example")) - } - - @Test - fun `a relay that is not a relay is not usable`() { - listOf("https://ephemeral.mantra.press", "ephemeral.mantra.press", "wss://").forEach { relay -> - assertNull( - CuratedSchemaEvent.parse(event(tags = replacing("relay", relay))), - "a schema naming the relay \"$relay\" was accepted" - ) - } - - // The NIP allows ws://, whatever this app will let a group sign. - assertEquals(listOf("ws://localhost:7777"), CuratedSchemaEvent.parse(event(tags = replacing("relay", "ws://localhost:7777")))?.relays) - - // Duplicates collapse; none at all is allowed. - assertEquals( - listOf("wss://ephemeral.mantra.press"), - CuratedSchemaEvent.parse(event(tags = bitcoinMov.plus(arrayOf("relay", "wss://ephemeral.mantra.press"))))?.relays - ) - assertEquals(emptyList(), CuratedSchemaEvent.parse(event(tags = without("relay")))?.relays) - } - - @Test - fun `an over-long identity tag is not usable`() { - assertNull(CuratedSchemaEvent.parse(event(tags = replacing("name", "n".repeat(101))))) - assertNull(CuratedSchemaEvent.parse(event(tags = replacing("d", "d".repeat(101))))) - assertNull(CuratedSchemaEvent.parse(event(tags = replacing("title", "t".repeat(201))))) - assertNull(CuratedSchemaEvent.parse(event(tags = replacing("description", "x".repeat(501))))) - - assertNotNull(CuratedSchemaEvent.parse(event(tags = replacing("name", "n".repeat(100))))) - } - - @Test - fun `the wrong kind is not a schema whatever its tags say`() { - assertNull(CuratedSchemaEvent.parse(event(kind = 31888))) - assertNull(CuratedSchemaEvent.parse(event(kind = 30023))) - } - - @Test - fun `the identifier and the title are forced in whatever the schema says`() { - // A schema fetched from a hostile relay cannot talk a client into - // accepting untitled or unaddressable entries. - val onlyAYear = arrayOf( - arrayOf("d", "years"), - arrayOf("title", "A year"), - arrayOf("name", "Years"), - arrayOf("description", "Just years."), - arrayOf("visibility", "public"), - arrayOf("field", "year", "year", "optional", "", "", "{}"), - ) - - val schema = assertNotNull(CuratedSchemaEvent.parse(event(tags = onlyAYear))) - - assertEquals(listOf("d", "title", "year"), schema.fields.map { it.tag() }) - assertTrue(schema.fields[0].isRequired) - assertTrue(schema.fields[1].isRequired) - assertEquals(CuratedField.IDENTIFIER, schema.fields[0]) - assertEquals(CuratedField.TITLE, schema.fields[1]) - - // And a title the publisher relaxed is made required again, in place. - val relaxed = replacing( - "field", - "title", - arrayOf("field", "title", "text", "optional", "The Rise and Rise of Bitcoin", "Title", "{\"max\":200}") - ) - val repaired = assertNotNull(CuratedSchemaEvent.parse(event(tags = relaxed))) - assertEquals(9, repaired.fields.size) - assertTrue(repaired.fields.first { it.name == "title" }.isRequired) - - // Running it again changes nothing. - assertEquals(repaired, repaired.normalized()) - } - - @Test - fun `a require-any naming fewer than two fields says nothing`() { - val schema = assertNotNull( - CuratedSchemaEvent.parse( - event( - tags = bitcoinMov.plus( - listOf( - arrayOf("require-any", "image"), - arrayOf("require-any"), - arrayOf("require-any", "year", " ", "type"), - ) - ) - ) - ) - ) - - assertEquals(listOf(listOf("watchUrl", "imdbUrl"), listOf("year", "type")), schema.requireAny) - } - - @Test - fun `suggesters are the p tags that are pubkeys`() { - val other = "eebb74ab6bfb8485722ab1d4acee856eee96f17a9e1721f9c7cc63376c40b860" - val schema = assertNotNull( - CuratedSchemaEvent.parse( - event( - tags = replacing("visibility", "closed").plus( - listOf( - arrayOf("p", other), - arrayOf("p", other.uppercase()), - arrayOf("p", "not a pubkey"), - ) - ) - ) - ) - ) - - assertEquals(listOf(other), schema.suggesters) - } - - @Test - fun `the coordinate is what a suggestion replies to`() { - assertEquals("31889:$curator:bitcoin.mov", CuratedSchemaEvent.coordinate(curator, "bitcoin.mov")) - - // An identifier may itself hold colons, so the coordinate does too. - assertEquals("31889:$curator:imdb:tt2821314", CuratedSchemaEvent.coordinate(curator, "imdb:tt2821314")) - } - - @Test - fun `an empty config is written as an empty object`() { - assertEquals("{}", CuratedFieldConfig().toJson()) - assertEquals("{\"tag\":\"d\",\"max\":80,\"derived\":true}", CuratedField.IDENTIFIER.config.toJson()) - } - - private fun event( - tags: Array> = bitcoinMov, - content: String = description, - kind: Int = CuratedSchemaEvent.KIND, - ): Event = Event( - id = "a".repeat(64), - pubKey = curator, - createdAt = 1735689600, - kind = kind, - tags = tags, - content = content, - sig = "b".repeat(128), - ) - - private fun without(tag: String): Array> = bitcoinMov.without(tag) - - private fun replacing(tag: String, value: String): Array> = bitcoinMov.replacing(tag, value) - - private fun replacing(tag: String, name: String, with: Array): Array> = - bitcoinMov.map { if (it[0] == tag && it[1] == name) with else it }.toTypedArray() - - private fun Array>.without(tag: String): Array> = - filter { it[0] != tag }.toTypedArray() - - private fun Array>.replacing(tag: String, value: String): Array> = - map { if (it[0] == tag) arrayOf(tag, value) else it }.toTypedArray() -} diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/curated/CuratedSchemaTemplateTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/curated/CuratedSchemaTemplateTest.kt deleted file mode 100644 index 7a164dfa..00000000 --- a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/curated/CuratedSchemaTemplateTest.kt +++ /dev/null @@ -1,155 +0,0 @@ -package com.machankura.bennu.compose.nostr.curated - -import com.vitorpamplona.quartz.nip01Core.core.Event -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertNotNull -import kotlin.test.assertSame -import kotlin.test.assertTrue - -/** - * The shapes a list can start from, held to what curare.to's own test holds - * its templates to: each one publishes a schema the module verifies, with its - * rule recorded and no derived `t` field. - * - * The rest is what this app's editor adds on top. A template is seeded - * straight into the working copy, so every field has to be one the editor - * would have let a member commit, and every rule has to name fields that are - * there -- a template that broke either would put the editor in a state the - * editor itself refuses to reach. - */ -class CuratedSchemaTemplateTest { - private val curator = "7c965d8c2acdfd635562da3bcb82596b595be28b008d8b54ec702ed4c67d9d25" - - /** A schema from a template, as the editor would propose it. */ - private fun schemaFrom(template: CuratedSchemaTemplate) = CuratedSchema( - identifier = template.key, - title = "${template.key} suggestion", - name = template.key, - description = "A list started from the ${template.key} template.", - visibility = CuratedVisibility.Public, - fields = template.fields, - requireAny = template.requireAny, - relays = listOf("wss://relay.example"), - ) - - @Test - fun `every template publishes a schema a reader accepts and reads back as itself`() { - for (template in CuratedSchemaTemplate.entries) { - val schema = schemaFrom(template) - assertEquals(emptyList(), schema.problems(), "${template.key} is not a usable schema") - - // The mandatory two are there and required, so the one repair a - // reader makes has nothing to do: what the member sees is what the - // group signs. - assertEquals(schema, schema.normalized(), "${template.key} is changed by normalizing") - - val built = CuratedSchemaEvent.template(schema, createdAt = 1_735_689_600) - val read = assertNotNull(CuratedSchemaEvent.parse(event(built.tags, built.content))) - assertEquals(schema, read, "${template.key} did not round trip") - } - } - - @Test - fun `every template records its rule on the identifier and declares no hashtag field`() { - for (template in CuratedSchemaTemplate.entries) { - val identifier = template.fields.single { it.tag() == "d" } - assertEquals(true, identifier.config.derived, "${template.key}'s identifier is prompted for") - assertTrue( - identifier.config.hint.orEmpty().endsWith("[rule:${template.rule.key}]"), - "${template.key}'s identifier does not record its rule: ${identifier.config.hint}" - ) - - // The hashtag rule is bitcoin.mov's own; a list is its own topic. - assertTrue(template.fields.none { it.tag() == "t" }, "${template.key} declares a t field") - } - } - - @Test - fun `the hint is the one curare_to writes`() { - // Byte for byte, because that site's `ruleOf` reads the mark back with a - // regular expression and a template started there and here should - // produce the same schema. - assertEquals( - "Derived by the client — the link, else the title and author. [rule:link-or-title]", - CuratedDeriveRule.LinkOrTitle.hint() - ) - assertEquals( - "Derived by the client — the title. [rule:title]", - CuratedDeriveRule.Title.hint() - ) - } - - @Test - fun `every template is one the editor would have let a member build`() { - for (template in CuratedSchemaTemplate.entries) { - val names = template.fields.map { it.name } - assertTrue( - names.all { it.isNotBlank() && it.none(Char::isWhitespace) }, - "${template.key} has a field name the editor refuses: $names" - ) - assertEquals(names.distinct(), names, "${template.key} names a field twice") - - for (group in template.requireAny) { - assertTrue(group.size > 1, "${template.key} has a rule that says nothing: $group") - assertTrue( - group.all { it in names }, - "${template.key} has a rule naming a field it does not have: $group" - ) - } - - template.fields.filter { it.type == CuratedFieldType.Enum }.forEach { field -> - assertTrue( - !field.config.options.isNullOrEmpty(), - "${template.key}'s ${field.name} is an enum with nothing to choose from" - ) - } - } - } - - @Test - fun `the templates are the site's four in its order`() { - assertEquals( - listOf("links", "discussion", "catalogue", "custom"), - CuratedSchemaTemplate.entries.map { it.key } - ) - - // The reddit-shaped default, by name: what an entry asks for and what - // it needs one of. - val links = CuratedSchemaTemplate.Links - assertEquals( - listOf("identifier", "title", "link", "body", "image", "flair"), - links.fields.map { it.name } - ) - assertEquals(listOf(listOf("link", "body")), links.requireAny) - assertEquals("r", links.fields.first { it.name == "link" }.tag()) - assertEquals(CuratedFieldConfig.CONTENT_TAG, links.fields.first { it.name == "body" }.tag()) - - // Custom is the two fields every list has and nothing else. - assertEquals(listOf("d", "title"), CuratedSchemaTemplate.Custom.fields.map { it.tag() }) - assertEquals(emptyList(), CuratedSchemaTemplate.Custom.requireAny) - } - - @Test - fun `a key finds its template and anything else is custom`() { - for (template in CuratedSchemaTemplate.entries) { - assertSame(template, CuratedSchemaTemplate.byKey(template.key)) - } - - // Custom rather than the first: the one shape that presumes nothing - // about a list it was not asked for. - assertSame(CuratedSchemaTemplate.Custom, CuratedSchemaTemplate.byKey(null)) - assertSame(CuratedSchemaTemplate.Custom, CuratedSchemaTemplate.byKey("gallery")) - assertSame(CuratedSchemaTemplate.Custom, CuratedSchemaTemplate.byKey("Links")) - } - - private fun event(tags: Array>, content: String): Event = Event( - id = "a".repeat(64), - pubKey = curator, - createdAt = 1_735_689_600, - kind = CuratedSchemaEvent.KIND, - tags = tags, - content = content, - sig = "b".repeat(128), - ) -} diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/text/ProposedEventTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/text/ProposedEventTest.kt index 29cc3904..62889d8b 100644 --- a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/text/ProposedEventTest.kt +++ b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/text/ProposedEventTest.kt @@ -1,7 +1,5 @@ package com.machankura.bennu.compose.text -import com.machankura.bennu.compose.nostr.curated.CuratedEntryEvent -import com.machankura.bennu.compose.nostr.curated.CuratedSchemaEvent import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent @@ -16,8 +14,8 @@ import kotlin.test.assertEquals * on the paste screen before proposing, and the same words in all three is the * point of there being one mapping. What is pinned is that each kind is said as * the thing it is and by the part of it a signer is actually deciding about -- - * a profile by its name, a post by its words, a relay list by its hosts, a - * schema by its list -- and never as "kind 0" over a wall of JSON. + * a profile by its name, a post by its words, a relay list by its hosts -- and + * never as "kind 0" over a wall of JSON. */ class ProposedEventTest { @@ -59,61 +57,6 @@ class ProposedEventTest { assertEquals("No relays", ProposedEvent.summarize(event(AdvertisedRelayListEvent.KIND)).detail) } - @Test - fun `a schema is said by its list who may suggest and how much an entry asks for`() { - val summary = ProposedEvent.summarize( - event( - CuratedSchemaEvent.KIND, - tags = arrayOf( - arrayOf("d", "films"), - arrayOf("title", "Film suggestion"), - arrayOf("name", "Films worth translating"), - arrayOf("description", "Films the group would subtitle."), - arrayOf("visibility", "closed"), - arrayOf("field", "title", "text", "required", "", "Title", "{}"), - arrayOf("field", "year", "year", "optional", "", "Year", "{}"), - ), - content = "Films the group would subtitle." - ) - ) - - assertEquals("Curated schema", summary.label) - assertEquals("Films worth translating · closed · 2 fields", summary.detail) - } - - @Test - fun `a curated entry is said by its title and who suggested it`() { - val suggester = "eebb74ab6bfb8485722ab1d4acee856eee96f17a9e1721f9c7cc63376c40b860" - - val summary = ProposedEvent.summarize( - event( - CuratedEntryEvent.CANONICAL_KIND, - tags = arrayOf( - arrayOf("d", "imdb:tt2821314"), - arrayOf("title", "The Rise and Rise of Bitcoin"), - arrayOf("year", "2014"), - arrayOf("a", "31889:${"7".repeat(64)}:bitcoin.mov", "", "root"), - arrayOf("a", "31888:$suggester:imdb:tt2821314", "", "mention"), - arrayOf("p", suggester), - ), - content = "Follows the early Bitcoin community." - ) - ) - - assertEquals("Curated entry", summary.label) - assertEquals("The Rise and Rise of Bitcoin · suggested by eebb74ab", summary.detail) - - // An entry the group added itself has nobody to credit. - val unprompted = ProposedEvent.summarize( - event( - CuratedEntryEvent.CANONICAL_KIND, - tags = arrayOf(arrayOf("d", "magic-money"), arrayOf("title", "Magic Money")), - content = "" - ) - ) - assertEquals("Magic Money", unprompted.detail) - } - @Test fun `a kind with no words of its own keeps its number`() { // Refusing to describe an event is better than describing it wrongly. diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/StringCatalogueJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/StringCatalogueJvmTest.kt index a5450928..2e0c0980 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/StringCatalogueJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/StringCatalogueJvmTest.kt @@ -8,7 +8,6 @@ import bennu.composeapp.generated.resources.something_went_wrong import bennu.composeapp.generated.resources.add_chapter_to import bennu.composeapp.generated.resources.chapter_words_characters import bennu.composeapp.generated.resources.sent_a_private_message_to -import bennu.composeapp.generated.resources.template_links import org.jetbrains.compose.resources.getString import kotlin.test.Test import kotlin.test.assertEquals @@ -66,15 +65,6 @@ class StringCatalogueJvmTest { ) } - @Test - fun `an ampersand entity comes back as an ampersand`() = runBlocking { - // `&` is the one character XML itself refuses in text, so it is the entity - // `&` in the catalogue -- an escape the parser handles rather than the - // resources library, and the first the app has depended on. The failure - // mode is a card offering "Links & text". - assertEquals("Links & text", getString(Res.string.template_links)) - } - @Test fun `a unicode escape was decoded into the catalogue`() = runBlocking { // `·` is Kotlin source syntax with no meaning in XML, so the extractor diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/AcceptCuratedSuggestionScreenJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/AcceptCuratedSuggestionScreenJvmTest.kt deleted file mode 100644 index 8529e38f..00000000 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/AcceptCuratedSuggestionScreenJvmTest.kt +++ /dev/null @@ -1,216 +0,0 @@ -package com.machankura.bennu.compose.ui.composable - -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.ui.Modifier -import androidx.compose.ui.test.ComposeUiTest -import androidx.compose.ui.test.ExperimentalTestApi -import androidx.compose.ui.test.assertCountEquals -import androidx.compose.ui.test.assertIsDisplayed -import androidx.compose.ui.test.assertIsNotEnabled -import androidx.compose.ui.test.onAllNodesWithText -import androidx.compose.ui.test.onNodeWithText -import androidx.compose.ui.test.performClick -import androidx.compose.ui.test.performTextReplacement -import androidx.compose.ui.test.runDesktopComposeUiTest -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.machankura.bennu.compose.database.model.NostrEvent -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.database.model.intermdiate.LocalNostrEvent -import com.machankura.bennu.compose.nostr.CuratedSuggestion -import com.machankura.bennu.compose.nostr.GroupCuratedSchema -import com.machankura.bennu.compose.nostr.curated.CuratedField -import com.machankura.bennu.compose.nostr.curated.CuratedFieldConfig -import com.machankura.bennu.compose.nostr.curated.CuratedFieldType -import com.machankura.bennu.compose.nostr.curated.CuratedSchema -import com.machankura.bennu.compose.nostr.curated.CuratedSchemaEvent -import com.machankura.bennu.compose.nostr.curated.CuratedVisibility -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.repository.NostrRepository -import com.machankura.bennu.compose.ui.composable.widgets.ProvideSnackbarHost -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.view.state.AcceptCuratedSuggestionUIState -import kotlin.test.Test -import kotlin.time.Instant - -/** - * What the accept form puts on the screen, for a schema it has never seen. - * - * Three things worth pinning. **The inputs are the schema's**: one per field - * the form asks for, labelled as the schema labels them and seeded with what - * was suggested, with an enum as its options rather than a box to misspell - * one in. **What is kept is shown, not hidden**: the identifier and the - * derived fields are on the screen under their own heading, so what the - * member sees is what the group will sign. And **a refusal is drawn under the - * input it is about**, since the button doing nothing is indistinguishable - * from a missed tap. - */ -@OptIn(ExperimentalTestApi::class) -class AcceptCuratedSuggestionScreenJvmTest { - - private val chatRoomId = "d4c3b2a1".repeat(8) - private val ada = "a".repeat(64) - private val bob = "b".repeat(64) - - private val schema = GroupCuratedSchema( - signedEvent = GroupSignedEvent( - id = "c".repeat(64), - chatRoomId = chatRoomId, - publicKey = chatRoomId, - kind = CuratedSchemaEvent.KIND, - tags = emptyArray(), - content = "", - signature = "f".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_000) - ), - schema = CuratedSchema( - identifier = "films", - title = "Film suggestion", - name = "Films worth translating", - description = "Films the group would subtitle.", - visibility = CuratedVisibility.Public, - domain = "films.example", - fields = listOf( - CuratedField.IDENTIFIER, - CuratedField.TITLE, - CuratedField("year", CuratedFieldType.Year, isRequired = false, label = "Year", config = CuratedFieldConfig(min = 1900, max = 2100)), - CuratedField("type", CuratedFieldType.Enum, isRequired = true, label = "Type", config = CuratedFieldConfig(options = listOf("movie", "documentary"))), - CuratedField("watchUrl", CuratedFieldType.Url, isRequired = false, label = "Watch URL", config = CuratedFieldConfig(tag = "r", marker = "watch", repeat = true)), - CuratedField("hashtags", CuratedFieldType.Token, isRequired = false, label = "Hashtags", config = CuratedFieldConfig(tag = "t", repeat = true, derived = true)), - CuratedField("review", CuratedFieldType.LongText, isRequired = false, label = "Review", config = CuratedFieldConfig(tag = CuratedFieldConfig.CONTENT_TAG, hint = "Why the group should watch it")), - ), - relays = listOf("wss://relay.one.example") - ).normalized() - ) - - private val suggestion: CuratedSuggestion = CuratedSuggestion.queueOf( - schema, - listOf( - LocalNostrEvent( - nostrEvent = NostrEvent( - id = "1".repeat(64), - pubKey = bob, - kind = CuratedSchemaEvent.SUGGESTION_KIND, - tags = arrayOf( - arrayOf("d", "magic-money"), - arrayOf("title", "Magic Money"), - arrayOf("year", "2018"), - arrayOf("type", "documentary"), - arrayOf("r", "https://example.com/watch", "watch"), - arrayOf("t", "bitcoin"), - arrayOf("a", schema.coordinate(), "", "root"), - ), - content = "Follows the early community.", - sig = "b".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_000), - ), - profile = null - ) - ) - ).single() - - private fun state(canSign: Boolean = true, isCurated: Boolean = false) = AcceptCuratedSuggestionUIState.Loaded( - localChatRoom = LocalChatRoom( - chatRoom = ChatRoom( - id = chatRoomId, - userPublicKey = ada, - subject = "Translation room", - description = null, - initialGiftWrapPayloadId = "sdfaer", - mlsGroupState = "state" - ) - ), - schema = schema, - suggestion = suggestion.copy(isCurated = isCurated), - canSign = canSign - ) - - @Test - fun `the inputs are the schema's, seeded from the suggestion, and what is kept is shown`() = render(state()) { - // Twice: the heading, and the title input seeded with it. - onAllNodesWithText("Magic Money").assertCountEquals(2) - onNodeWithText("Suggested by ${bob.take(8)} on ", substring = true).assertIsDisplayed() - onNodeWithText("Take this suggestion into films.example", substring = true).assertIsDisplayed() - - // The schema's labels over its values: a text field, a number, and the - // enum as chips with the suggested one among them. - onNodeWithText("Year").assertIsDisplayed() - onNodeWithText("2018").assertIsDisplayed() - onNodeWithText("Type").assertIsDisplayed() - onNodeWithText("movie").assertIsDisplayed() - onNodeWithText("documentary").assertIsDisplayed() - onNodeWithText("https://example.com/watch").assertIsDisplayed() - onNodeWithText("Follows the early community.").assertIsDisplayed() - // The schema's hint under the input it is for. - onNodeWithText("Why the group should watch it").assertIsDisplayed() - // A field that repeats can be given another value. - onNodeWithText("Add another").assertIsDisplayed() - - // Kept, and said to be: the identifier and the derived hashtags. - onNodeWithText("Kept from the suggestion").assertIsDisplayed() - onNodeWithText("Identifier").assertIsDisplayed() - onNodeWithText("magic-money").assertIsDisplayed() - onNodeWithText("Hashtags").assertIsDisplayed() - onNodeWithText("bitcoin").assertIsDisplayed() - - onNodeWithText("Propose entry").assertIsDisplayed() - onAllNodesWithText("The group already has an entry for this", substring = true).assertCountEquals(0) - } - - @Test - fun `a refusal is drawn under the input it is about`() = render(state()) { - // The suggested year is replaced with one the schema's range refuses, - // by way of the field: the test types where a member would. - onNodeWithText("2018").performTextReplacement("1850") - onNodeWithText("Propose entry").performClick() - - onNodeWithText("At least 1900.").assertIsDisplayed() - } - - @Test - fun `a device without a share sees why the button is inert`() = render(state(canSign = false)) { - onNodeWithText("This group has no shared key, so it cannot sign an entry", substring = true).assertIsDisplayed() - onNodeWithText("Propose entry").assertIsNotEnabled() - } - - @Test - fun `a suggestion the group already took up says so before the button`() = render(state(isCurated = true)) { - onNodeWithText("The group already has an entry for this", substring = true).assertIsDisplayed() - } - - /** - * The screen at a phone's width and a window tall enough to compose the - * whole of it. The state is passed in, so the NO_OP repositories are never - * asked for anything: `initiate` only runs for a screen that arrives loading. - */ - private fun render( - uiState: AcceptCuratedSuggestionUIState, - assertions: ComposeUiTest.() -> Unit - ) = runDesktopComposeUiTest(width = 400, height = 2400) { - setContent { - BennuTheme { - ProvideSnackbarHost { - Box(modifier = Modifier.fillMaxSize()) { - AcceptCuratedSuggestionScreen( - activeUserPublicKey = ada, - chatRoomId = chatRoomId, - relayHint = null, - identifier = "films", - suggestionId = suggestion.id, - initialAcceptCuratedSuggestionUIState = uiState, - nostrRepository = NostrRepository.NO_OP_NOSTR_REPOSITORY, - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, - onNavigateBack = {}, - onNavigateToRouteAndPopUpInclusive = {} - ) - } - } - } - } - - assertions() - } -} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/CuratedSuggestionListScreenJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/CuratedSuggestionListScreenJvmTest.kt deleted file mode 100644 index 5c960dd7..00000000 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/CuratedSuggestionListScreenJvmTest.kt +++ /dev/null @@ -1,333 +0,0 @@ -package com.machankura.bennu.compose.ui.composable - -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.ui.Modifier -import androidx.compose.ui.test.ComposeUiTest -import androidx.compose.ui.test.ExperimentalTestApi -import androidx.compose.ui.test.assertCountEquals -import androidx.compose.ui.test.assertIsDisplayed -import androidx.compose.ui.test.getBoundsInRoot -import androidx.compose.ui.test.onAllNodesWithText -import androidx.compose.ui.test.onNodeWithText -import androidx.compose.ui.test.performClick -import androidx.compose.ui.test.runDesktopComposeUiTest -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.machankura.bennu.compose.database.model.NostrEvent -import com.machankura.bennu.compose.database.model.Profile -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.CuratedSuggestion -import com.machankura.bennu.compose.nostr.GroupCuratedSchema -import com.machankura.bennu.compose.nostr.curated.CuratedEntry -import com.machankura.bennu.compose.nostr.curated.CuratedField -import com.machankura.bennu.compose.nostr.curated.CuratedFieldConfig -import com.machankura.bennu.compose.nostr.curated.CuratedFieldType -import com.machankura.bennu.compose.nostr.curated.CuratedSchema -import com.machankura.bennu.compose.nostr.curated.CuratedSchemaEvent -import com.machankura.bennu.compose.nostr.curated.CuratedVisibility -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.NostrRepository -import com.machankura.bennu.compose.ui.composable.widgets.ProvideSnackbarHost -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.view.state.CuratedSuggestionListUIState -import kotlin.test.Test -import kotlin.test.assertTrue -import kotlin.time.Instant - -/** - * What the queue screen says, in each of the states it can be in. - * - * Three things are worth pinning. **The row is driven by a schema the screen - * has never seen**, so what it puts on a row is a decision -- the fields that - * say what an entry is, labelled, and not the links -- and that decision is - * checked against a schema with one of each. **"Curated" is per row**, and a - * screen that marked the wrong row would send a member to re-curate what the - * group had already taken up. And **empty is not the same as still looking**: - * the screen has both and must say which, since a queue called empty a second - * before its rows arrive teaches a member not to believe it. - */ -@OptIn(ExperimentalTestApi::class) -class CuratedSuggestionListScreenJvmTest { - - private val chatRoomId = "d4c3b2a1".repeat(8) - private val ada = "a".repeat(64) - private val bob = "b".repeat(64) - - private val schema = GroupCuratedSchema( - signedEvent = GroupSignedEvent( - id = "c".repeat(64), - chatRoomId = chatRoomId, - publicKey = chatRoomId, - kind = CuratedSchemaEvent.KIND, - tags = emptyArray(), - content = "", - signature = "f".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_000) - ), - schema = CuratedSchema( - identifier = "films", - title = "Film suggestion", - name = "Films worth translating", - description = "Films the group would subtitle.", - visibility = CuratedVisibility.Public, - domain = "films.example", - fields = listOf( - CuratedField.IDENTIFIER, - CuratedField.TITLE, - CuratedField("year", CuratedFieldType.Year, isRequired = false, label = "Year"), - CuratedField("type", CuratedFieldType.Enum, isRequired = true, label = "Type"), - CuratedField( - "watchUrl", - CuratedFieldType.Url, - isRequired = false, - label = "Watch URL", - config = CuratedFieldConfig(tag = "r", marker = "watch") - ), - CuratedField( - "review", - CuratedFieldType.LongText, - isRequired = false, - label = "Review", - config = CuratedFieldConfig(tag = CuratedFieldConfig.CONTENT_TAG) - ), - ), - relays = listOf("wss://relay.one.example") - ) - ) - - @Test - fun `the queue is named after the list, counted, and read from where the schema says`() = render( - state( - suggestions = listOf( - suggestion("The Rise and Rise of Bitcoin", 1_700_000_900, isCurated = true), - suggestion("Magic Money", 1_700_000_000, isCurated = false) - ) - ) - ) { - // The domain, as the card on the group's screen names it. - onNodeWithText("films.example").assertIsDisplayed() - onNodeWithText("2 suggestions · 1 curated").assertIsDisplayed() - onNodeWithText("Read from relay.one.example").assertIsDisplayed() - - // Newest first. - val newest = onNodeWithText("The Rise and Rise of Bitcoin").getBoundsInRoot().top - val oldest = onNodeWithText("Magic Money").getBoundsInRoot().top - assertTrue(newest < oldest, "the queue was drawn oldest first") - } - - @Test - fun `a row shows what an entry is, not where to find it, and who suggested it`() = render( - state( - suggestions = listOf( - suggestion( - "Magic Money", - 1_700_000_000, - isCurated = false, - suggester = Profile( - publicKey = ada, - displayName = "Ada", - nostrEventId = "e".repeat(64), - createdAt = Instant.fromEpochSeconds(1_700_000_000) - ) - ) - ) - ) - ) { - // Labelled, because the screen does not know this list's fields any - // better than a stranger does; the link left to the sheet. - onNodeWithText("Year: 2018 · Type: documentary").assertIsDisplayed() - onNodeWithText("https://example.com/watch").assertDoesNotExist() - // The body, where the list has one. - onNodeWithText("Follows the early community.").assertIsDisplayed() - onNodeWithText("Suggested by Ada on", substring = true).assertIsDisplayed() - - onNodeWithText("1 suggestion").assertIsDisplayed() - onNodeWithText("Curated").assertDoesNotExist() - } - - @Test - fun `only the row the group has taken up is marked`() = render( - state( - suggestions = listOf( - suggestion("The Rise and Rise of Bitcoin", 1_700_000_900, isCurated = true), - suggestion("Magic Money", 1_700_000_000, isCurated = false) - ) - ) - ) { - onAllNodesWithText("Curated").assertCountEquals(1) - - val mark = onNodeWithText("Curated").getBoundsInRoot() - val curated = onNodeWithText("The Rise and Rise of Bitcoin").getBoundsInRoot() - val waiting = onNodeWithText("Magic Money").getBoundsInRoot() - - assertTrue(mark.top < waiting.top, "the mark fell onto the row still waiting") - assertTrue(mark.bottom > curated.top, "the mark floated above the row it is about") - } - - @Test - fun `a queue still being asked for is looking, not empty`() = render( - state(suggestions = emptyList(), isAsking = true) - ) { - onNodeWithText("Asking the list's relays…").assertIsDisplayed() - onNodeWithText("Nobody has suggested anything to this list yet.").assertDoesNotExist() - onNodeWithText("Ask again").assertDoesNotExist() - } - - @Test - fun `an empty queue says so, and offers to ask again`() = render( - state(suggestions = emptyList(), isAsking = false) - ) { - onNodeWithText("Nobody has suggested anything to this list yet.").assertIsDisplayed() - onNodeWithText("Ask again").assertIsDisplayed() - onNodeWithText("Asking the list's relays…").assertDoesNotExist() - onNodeWithText("0 suggestions").assertIsDisplayed() - } - - @Test - fun `the sheet has every field the entry answered, the link included, and the way in`() = - runDesktopComposeUiTest(width = 400, height = 2000) { - var accepted = false - - setContent { - BennuTheme { - ProvideSnackbarHost { - CuratedSuggestionSheetContent( - suggestion = suggestion("Magic Money", 1_700_000_000, isCurated = false), - schema = schema.schema, - onAccept = { accepted = true } - ) - } - } - } - - onNodeWithText("Magic Money").assertIsDisplayed() - - // As the schema labels them, in the schema's order. - onNodeWithText("Year").assertIsDisplayed() - onNodeWithText("2018").assertIsDisplayed() - onNodeWithText("Watch URL").assertIsDisplayed() - onNodeWithText("https://example.com/watch").assertIsDisplayed() - onNodeWithText("Review").assertIsDisplayed() - onNodeWithText("Follows the early community.").assertIsDisplayed() - - // The one thing to do with it, and not the event: the form shows - // the entry as fields, which is how the group will sign it. - onAllNodesWithText("\"kind\":31888", substring = true).assertCountEquals(0) - onAllNodesWithText("Copy the suggestion").assertCountEquals(0) - onNodeWithText("Accept this suggestion").assertIsDisplayed().performClick() - assertTrue(accepted, "the button did not open the form") - } - - @Test - fun `a suggestion the group already took up offers a revision, not a second acceptance`() = - runDesktopComposeUiTest(width = 400, height = 2000) { - setContent { - BennuTheme { - ProvideSnackbarHost { - CuratedSuggestionSheetContent( - suggestion = suggestion("Magic Money", 1_700_000_000, isCurated = true), - schema = schema.schema, - onAccept = {} - ) - } - } - } - - onNodeWithText("Taken up by the group into the list.").assertIsDisplayed() - onNodeWithText("Revise the list's entry").assertIsDisplayed() - onAllNodesWithText("Accept this suggestion").assertCountEquals(0) - } - - private fun suggestion( - title: String, - createdAt: Long, - isCurated: Boolean, - suggester: Profile? = null - ): CuratedSuggestion { - val id = createdAt.toString().padStart(64, 'e') - val identifier = title.lowercase().replace(' ', '-') - - return CuratedSuggestion( - entry = CuratedEntry( - kind = CuratedSchemaEvent.SUGGESTION_KIND, - id = id, - pubKey = suggester?.publicKey ?: bob, - createdAt = createdAt, - identifier = identifier, - title = title, - values = mapOf( - "identifier" to listOf(identifier), - "title" to listOf(title), - "year" to listOf("2018"), - "type" to listOf("documentary"), - "watchUrl" to listOf("https://example.com/watch"), - "review" to listOf("Follows the early community."), - ) - ), - event = NostrEvent( - id = id, - pubKey = suggester?.publicKey ?: bob, - kind = CuratedSchemaEvent.SUGGESTION_KIND, - tags = arrayOf(arrayOf("d", identifier), arrayOf("title", title)), - content = "Follows the early community.", - sig = "b".repeat(128), - createdAt = Instant.fromEpochSeconds(createdAt) - ), - suggester = suggester, - isCurated = isCurated - ) - } - - private fun state( - suggestions: List, - isAsking: Boolean = false - ) = CuratedSuggestionListUIState.Loaded( - localChatRoom = LocalChatRoom( - chatRoom = ChatRoom( - id = chatRoomId, - userPublicKey = ada, - subject = "Translation room", - description = null, - initialGiftWrapPayloadId = "sdfaer", - mlsGroupState = "state" - ) - ), - schema = schema, - relays = listOf("wss://relay.one.example"), - suggestions = suggestions, - isAsking = isAsking - ) - - /** - * The screen at a phone's width and a window tall enough to compose the - * whole of it. The state is passed in, so the NO_OP repositories are never - * asked for anything: `initiate` only runs for a screen that arrives loading. - */ - private fun render( - uiState: CuratedSuggestionListUIState, - assertions: ComposeUiTest.() -> Unit - ) = runDesktopComposeUiTest(width = 400, height = 2000) { - setContent { - BennuTheme { - ProvideSnackbarHost { - Box(modifier = Modifier.fillMaxSize()) { - CuratedSuggestionListScreen( - activeUserPublicKey = ada, - chatRoomId = chatRoomId, - relayHint = null, - identifier = "films", - initialCuratedSuggestionListUIState = uiState, - nostrRepository = NostrRepository.NO_OP_NOSTR_REPOSITORY, - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - onNavigateBack = {}, - onNavigateToRoute = {} - ) - } - } - } - } - - assertions() - } -} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/EditGroupCuratedSchemaScreenJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/EditGroupCuratedSchemaScreenJvmTest.kt deleted file mode 100644 index fdd41e05..00000000 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/EditGroupCuratedSchemaScreenJvmTest.kt +++ /dev/null @@ -1,306 +0,0 @@ -package com.machankura.bennu.compose.ui.composable - -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.ui.Modifier -import androidx.compose.ui.test.ComposeUiTest -import androidx.compose.ui.test.ExperimentalTestApi -import androidx.compose.ui.test.assertIsDisplayed -import androidx.compose.ui.test.assertIsNotEnabled -import androidx.compose.ui.test.assertIsOn -import androidx.compose.ui.test.assertCountEquals -import androidx.compose.ui.test.assertIsNotSelected -import androidx.compose.ui.test.assertIsSelected -import androidx.compose.ui.test.onAllNodesWithText -import androidx.compose.ui.test.getBoundsInRoot -import androidx.compose.ui.test.onNodeWithContentDescription -import androidx.compose.ui.test.onNodeWithText -import androidx.compose.ui.test.performClick -import androidx.compose.ui.test.runDesktopComposeUiTest -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.extensions.hexToNpubHrp -import com.machankura.bennu.compose.nostr.GroupCuratedSchema -import com.machankura.bennu.compose.nostr.curated.CuratedField -import com.machankura.bennu.compose.nostr.curated.CuratedFieldConfig -import com.machankura.bennu.compose.nostr.curated.CuratedFieldType -import com.machankura.bennu.compose.nostr.curated.CuratedSchema -import com.machankura.bennu.compose.nostr.curated.CuratedSchemaEvent -import com.machankura.bennu.compose.nostr.curated.CuratedSchemaTemplate -import com.machankura.bennu.compose.nostr.curated.CuratedVisibility -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.ui.composable.widgets.ProvideSnackbarHost -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.view.model.EditGroupCuratedSchemaViewModel -import com.machankura.bennu.compose.ui.view.state.EditGroupCuratedSchemaUIState -import kotlin.test.Test -import kotlin.test.assertTrue -import kotlin.time.Instant - -/** - * What the schema editor puts in front of a member, in the two states it opens in. - * - * **A new list starts filled in.** The two fields every list has and the group's - * own relays are on the form before anything is typed, because they are what the - * group will sign whether or not the member adds to them -- and a form that - * showed an empty list and then signed two fields would be lying about what it - * proposed. A new list from a template starts at the template: its fields as - * rows and its rules as chips, since the picker before this screen promised - * that shape and the form is where the promise is kept. - * - * **An existing list opens as an edit.** Its identifier is locked and the form - * says why, its rules show which fields they name, and the suggesters a closed - * list admits are there to be read and removed. The rows are what a member - * checks before proposing, and each is an intention a later change to the - * `LazyColumn` could drop without anything else noticing. - * - * **The sheet offers a type its own settings.** A url field gets "https only" - * and a year field does not, because a setting the event gives no meaning to - * would be written into the schema and mean nothing. - */ -@OptIn(ExperimentalTestApi::class) -class EditGroupCuratedSchemaScreenJvmTest { - - private val chatRoomId = "d4c3b2a1".repeat(8) - - private val suggester = "eebb74ab6bfb8485722ab1d4acee856eee96f17a9e1721f9c7cc63376c40b860" - - private val films = CuratedSchema( - identifier = "films", - title = "Film suggestion", - name = "Films worth translating", - description = "Films the group would subtitle, with a link to watch each one.", - visibility = CuratedVisibility.Closed, - fields = listOf( - CuratedField.IDENTIFIER, - CuratedField.TITLE, - CuratedField( - name = "watchUrl", - type = CuratedFieldType.Url, - isRequired = false, - label = "Where to watch", - config = CuratedFieldConfig(tag = "r", marker = "watch", max = 500), - ), - CuratedField( - name = "imdbUrl", - type = CuratedFieldType.Url, - isRequired = false, - label = "IMDb page", - config = CuratedFieldConfig(tag = "r", marker = "imdb", max = 500), - ), - ), - requireAny = listOf(listOf("watchUrl", "imdbUrl")), - suggesters = listOf(suggester), - relays = listOf("wss://relay.one.example"), - ) - - @Test - fun `a new list starts with the two fields every list has and the group's relays`() = render( - state(existing = null, defaultRelays = listOf("wss://relay.one.example/")) - ) { - // By their supporting line: "Identifier" is also the label over the - // identifier field above, and the row is the one that says what it is. - onNodeWithText("identifier · Token · Required · Derived").assertIsDisplayed() - onNodeWithText("title · Text · Required").assertIsDisplayed() - onNodeWithText("wss://relay.one.example/").assertIsDisplayed() - - onNodeWithText("Public").assertIsSelected() - // A public list admits anyone, so there is no list of who it admits. - onNodeWithText("Suggesters").assertDoesNotExist() - - onNodeWithText("Add field").assertIsDisplayed() - onNodeWithText("Add rule").assertIsDisplayed() - onNodeWithText("Propose schema").assertIsDisplayed() - - // Nothing locks a new identifier: the member is choosing it. - onNodeWithText("The identifier names this list in every reply", substring = true) - .assertDoesNotExist() - } - - @Test - fun `a new list from a template starts at the template's fields and rules`() = render( - state(existing = null, defaultRelays = listOf("wss://relay.one.example/")), - template = CuratedSchemaTemplate.Links.key - ) { - // The template's fields, in its order, the mandatory two included -- - // and the identifier still marked derived, since the template records - // its rule in the hint rather than prompting for the value. - onNodeWithText("identifier · Token · Required · Derived").assertIsDisplayed() - val title = onNodeWithText("title · Text · Required").getBoundsInRoot().top - val link = onNodeWithText("link · Url · Optional").getBoundsInRoot().top - val body = onNodeWithText("body · Long text · Optional").getBoundsInRoot().top - val image = onNodeWithText("image · Image · Optional").getBoundsInRoot().top - val flair = onNodeWithText("flair · One of a list · Optional").getBoundsInRoot().top - assertTrue(title < link && link < body && body < image && image < flair, "the fields were drawn out of order") - - // The rule the template carries, as a row of chips with its two fields - // selected. The chip is the one node saying exactly "link": the row - // above is headed by the label, "Link", and its supporting line says more. - onNodeWithText("At least one of").assertIsDisplayed() - onAllNodesWithText("link").assertCountEquals(1) - onNodeWithText("link").assertIsSelected() - onNodeWithText("body").assertIsSelected() - onNodeWithText("flair").assertIsNotSelected() - - // Everything else is as a new list is. - onNodeWithText("wss://relay.one.example/").assertIsDisplayed() - onNodeWithText("Public").assertIsSelected() - onNodeWithText("Propose schema").assertIsDisplayed() - } - - @Test - fun `an existing list opens as an edit with its identifier locked`() = render( - state(existing = existing(films)) - ) { - onNodeWithText("films").assertIsDisplayed() - onNodeWithText("The identifier names this list in every reply", substring = true) - .assertIsDisplayed() - - onNodeWithText("Closed").assertIsSelected() - - // Every field, in the order it will be written. - val identifier = onNodeWithText("identifier · Token · Required · Derived").getBoundsInRoot().top - val watch = onNodeWithText("Where to watch").getBoundsInRoot().top - val imdb = onNodeWithText("IMDb page").getBoundsInRoot().top - assertTrue(identifier < watch && watch < imdb, "the fields were drawn out of order") - - // The rule names its fields, and the suggesters are readable as npubs. - onNodeWithText("At least one of").assertIsDisplayed() - onNodeWithText("Suggesters").assertIsDisplayed() - onNodeWithText(suggester.hexToNpubHrp()).assertIsDisplayed() - onNodeWithText("wss://relay.one.example").assertIsDisplayed() - } - - @Test - fun `a member holding no share of the key is told so and the button is inert`() = render( - state(existing = existing(films), canSign = false) - ) { - onNodeWithText("This group has no shared key, so it cannot sign a curated schema.", substring = true) - .assertIsDisplayed() - onNodeWithContentDescription("Propose schema").assertIsNotEnabled() - } - - @Test - fun `the sheet offers a type its own settings and pins a mandatory field`() { - // A url field: https is a thing it can be told, options are not. - renderSheet(field = films.fields[2], index = 2, isMandatory = false) { - onNodeWithText("Edit field").assertIsDisplayed() - onNodeWithText("Url").assertIsSelected() - onNodeWithText("https only").assertIsDisplayed() - onNodeWithText("Options").assertDoesNotExist() - onNodeWithText("Minimum value").assertDoesNotExist() - onNodeWithText("Remove field").assertIsDisplayed() - - // Changing the type changes what is offered. - onNodeWithText("One of a list").performClick() - onNodeWithText("Options").assertIsDisplayed() - onNodeWithText("https only").assertDoesNotExist() - } - - // The identifier: required whatever the switch says, and not removable. - renderSheet(field = films.fields[0], index = 0, isMandatory = true) { - onNodeWithContentDescription("An entry must have this field").assertIsOn() - onNodeWithContentDescription("An entry must have this field").assertIsNotEnabled() - onNodeWithText("Remove field").assertDoesNotExist() - } - } - - private fun existing(schema: CuratedSchema) = GroupCuratedSchema( - signedEvent = GroupSignedEvent( - id = "c".repeat(64), - chatRoomId = chatRoomId, - publicKey = chatRoomId, - kind = CuratedSchemaEvent.KIND, - tags = CuratedSchemaEvent.template(schema, createdAt = 1_700_000_000).tags, - content = schema.description, - signature = "f".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_000), - ), - schema = schema.normalized(), - ) - - private fun state( - existing: GroupCuratedSchema?, - defaultRelays: List = emptyList(), - canSign: Boolean = true, - ) = EditGroupCuratedSchemaUIState.Loaded( - localChatRoom = LocalChatRoom( - chatRoom = ChatRoom( - id = chatRoomId, - userPublicKey = "a".repeat(64), - subject = "Translation room", - description = "A group translating hard books.", - initialGiftWrapPayloadId = "sdfaer", - mlsGroupState = "state" - ) - ), - existing = existing, - defaultRelays = defaultRelays, - canSign = canSign, - ) - - /** - * The screen at a phone's width and a window tall enough to compose the whole - * of it, since a `LazyColumn` does not lay out what it would not show. - */ - private fun render( - uiState: EditGroupCuratedSchemaUIState, - template: String? = null, - assertions: ComposeUiTest.() -> Unit - ) = runDesktopComposeUiTest(width = 400, height = 3000) { - setContent { - BennuTheme { - ProvideSnackbarHost { - Box(modifier = Modifier.fillMaxSize()) { - EditGroupCuratedSchemaScreen( - activeUserPublicKey = "a".repeat(64), - chatRoomId = chatRoomId, - relayHint = null, - identifier = (uiState as? EditGroupCuratedSchemaUIState.Loaded) - ?.existing?.identifier, - template = template, - initialEditGroupCuratedSchemaUIState = uiState, - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - frostSigningRepository = - FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, - onNavigateToRouteAndPopUpInclusive = {}, - onNavigateBack = {}, - ) - } - } - } - } - - assertions() - } - - /** - * The sheet's content on its own: a bottom sheet is a popup with its own - * window, which a layout test cannot reach into. - */ - private fun renderSheet( - field: CuratedField, - index: Int, - isMandatory: Boolean, - assertions: ComposeUiTest.() -> Unit - ) = runDesktopComposeUiTest(width = 400, height = 2000) { - setContent { - BennuTheme { - ProvideSnackbarHost { - Box(modifier = Modifier.fillMaxSize()) { - FieldEditorSheetContent( - edit = EditGroupCuratedSchemaViewModel.FieldEdit(index = index, field = field), - isMandatory = isMandatory, - onCommit = { null }, - onRemove = {} - ) - } - } - } - } - - assertions() - } -} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupCuratedEntriesScreenJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupCuratedEntriesScreenJvmTest.kt deleted file mode 100644 index 606a5ce5..00000000 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupCuratedEntriesScreenJvmTest.kt +++ /dev/null @@ -1,240 +0,0 @@ -package com.machankura.bennu.compose.ui.composable - -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.ui.Modifier -import androidx.compose.ui.test.ComposeUiTest -import androidx.compose.ui.test.ExperimentalTestApi -import androidx.compose.ui.test.assertCountEquals -import androidx.compose.ui.test.assertIsDisplayed -import androidx.compose.ui.test.getBoundsInRoot -import androidx.compose.ui.test.onAllNodesWithText -import androidx.compose.ui.test.onNodeWithText -import androidx.compose.ui.test.performClick -import androidx.compose.ui.test.runDesktopComposeUiTest -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.flowOf -import com.machankura.bennu.compose.database.model.NostrEvent -import com.machankura.bennu.compose.exceptions.NostrPublishException -import com.machankura.bennu.compose.network.dto.RelayDTO -import com.machankura.bennu.compose.network.relays.EventPublishTransport -import com.machankura.bennu.compose.network.relays.NostrPublishResult -import com.machankura.bennu.compose.network.sockets.NostrIncomingMessage -import com.machankura.bennu.compose.nostr.GroupCuratedEntry -import com.machankura.bennu.compose.nostr.GroupRelay -import com.machankura.bennu.compose.nostr.GroupRelayList -import com.machankura.bennu.compose.nostr.GroupRelaySet -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.activeUserPublicKey -import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.chatRoomId -import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.entry -import com.machankura.bennu.compose.ui.composable.navigation.routes.BroadcastGroupSignedEventRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.widgets.ProvideSnackbarHost -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.view.state.GroupCuratedEntriesUIState -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertTrue - -/** - * The entries the group has accepted on their own screen: one card per entry, - * most recently signed first, each with its broadcast, and one button at the - * bottom that broadcasts all of them -- there is no way in to add one here. - */ -@OptIn(ExperimentalTestApi::class) -class GroupCuratedEntriesScreenJvmTest { - - private val newest = entry("The Rise and Rise of Bitcoin", 1_700_000_900) - private val oldest = entry("Magic Money", 1_700_000_300, suggestedBy = null) - - private val one = RelayUrlNormalizer.normalize("wss://relay.one.example") - private val two = RelayUrlNormalizer.normalize("wss://relay.two.example") - - /** A pool that answers each event as [answers] says and never opens a socket. */ - private class FakeTransport( - private val answers: (NostrEvent) -> List = { emptyList() } - ) : EventPublishTransport { - override suspend fun publishEvent( - nostrEvent: NostrEvent, - relays: Set - ): Flow = flowOf(*answers(nostrEvent).toTypedArray()) - } - - @Test - fun `the entries are drawn most recently signed first, one card per entry`() = render( - state(entries = listOf(newest, oldest)) - ) { - val first = onNodeWithText("The Rise and Rise of Bitcoin").getBoundsInRoot().top - val second = onNodeWithText("Magic Money").getBoundsInRoot().top - assertTrue(first < second, "the entries were drawn oldest first") - - // Which list, what the entry is -- labelled as the schema labels it -- - // and who suggested it, where somebody did. - onAllNodesWithText("In Films worth translating").assertCountEquals(2) - onAllNodesWithText("Year: 2014", substring = true).assertCountEquals(2) - onAllNodesWithText("Suggested by eebb74ab · ", substring = true).assertCountEquals(1) - // Dated like every signed statement the group makes, once per entry. - onAllNodesWithText("Signed by the group on", substring = true).assertCountEquals(2) - } - - @Test - fun `every accepted entry offers a broadcast under its own card`() { - var opened: Route? = null - - render(state(entries = listOf(newest, oldest)), onNavigateToRoute = { opened = it }) { - // The entry is the one event the group signs whose broadcast the - // queue screen depends on, since that is where the "Curated" mark is - // read back from. - val buttons = onAllNodesWithText("Broadcast") - buttons.assertCountEquals(2) - - val firstCard = onNodeWithText("The Rise and Rise of Bitcoin").getBoundsInRoot().top - val secondCard = onNodeWithText("Magic Money").getBoundsInRoot().top - val first = buttons[0].getBoundsInRoot().top - val second = buttons[1].getBoundsInRoot().top - - assertTrue(firstCard < first && first < secondCard, "the first entry's broadcast is not under its card") - assertTrue(secondCard < second, "the second entry's broadcast is not under its card") - - buttons[0].performClick() - } - - assertEquals( - BroadcastGroupSignedEventRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = null, - signedEventId = newest.signedEvent.id - ), - opened - ) - } - - @Test - fun `a group that has accepted nothing says so, and offers no way to add one here`() = render( - state(entries = emptyList()) - ) { - onNodeWithText("This group hasn't accepted anything into a list yet.", substring = true) - .assertIsDisplayed() - - // An entry is accepted from the queue on its schema's card, on the - // schemas screen, so this screen has no button of its own -- and - // nothing to broadcast, so no button for that either. - onAllNodesWithText("Add entry").assertCountEquals(0) - onAllNodesWithText("Broadcast").assertCountEquals(0) - onAllNodesWithText("Broadcast all").assertCountEquals(0) - } - - @Test - fun `the button at the bottom sends every entry, and each card says what its relays answered`() { - val ok = { relay: String, event: NostrEvent -> - NostrPublishResult( - result = NostrIncomingMessage.OkMessage(eventId = event.id, success = true), - relayUrl = relay, - ) - } - val transport = FakeTransport { event -> - if (event.id == newest.signedEvent.id) { - listOf(ok(two.url, event), ok(one.url, event)) - } else { - listOf( - ok(two.url, event), - NostrPublishResult( - result = NostrIncomingMessage.OkMessage( - eventId = event.id, - success = false, - message = "blocked: not on the allow list", - ), - error = NostrPublishException(message = "blocked: not on the allow list"), - relayUrl = one.url, - ), - ) - } - } - - render(state(entries = listOf(newest, oldest)), transport = transport) { - onNodeWithText("Broadcast all").performClick() - - // The sum above the cards, once the last has settled. - waitUntil(timeoutMillis = 5_000) { - onAllNodesWithText("Accepted by every relay for 1 of 2 entries.") - .fetchSemanticsNodes().isNotEmpty() - } - - // Each entry's count, and the one relay that refused named with its - // reason -- the relay that said OK is in the count and nowhere else. - onNodeWithText("Accepted by 2 of 2 relays.").assertIsDisplayed() - onNodeWithText("Accepted by 1 of 2 relays.").assertIsDisplayed() - onNodeWithText("relay.one.example · Rejected: blocked: not on the allow list") - .assertIsDisplayed() - onAllNodesWithText("relay.two.example", substring = true).assertCountEquals(0) - - // The sum above every card; each answer under its own card and - // above that card's broadcast, which is what a refusal calls for. - val sum = onNodeWithText("Accepted by every relay for 1 of 2 entries.").getBoundsInRoot().top - val firstCard = onNodeWithText("The Rise and Rise of Bitcoin").getBoundsInRoot().top - val firstAnswer = onNodeWithText("Accepted by 2 of 2 relays.").getBoundsInRoot().top - val secondCard = onNodeWithText("Magic Money").getBoundsInRoot().top - val secondAnswer = onNodeWithText("Accepted by 1 of 2 relays.").getBoundsInRoot().top - val buttons = onAllNodesWithText("Broadcast") - val firstButton = buttons[0].getBoundsInRoot().top - val secondButton = buttons[1].getBoundsInRoot().top - - assertTrue(sum < firstCard, "the sum is not above the cards") - assertTrue(firstCard < firstAnswer && firstAnswer < firstButton, "the first answer is not between its card and its broadcast") - assertTrue(firstButton < secondCard, "the second card climbed above the first's broadcast") - assertTrue(secondCard < secondAnswer && secondAnswer < secondButton, "the second answer is not between its card and its broadcast") - } - } - - /** - * A General list of [two] agreed, so each entry goes to one relay of the - * group's and one of its list's -- [one], which the fixture's schema names. - */ - private fun relayLists(): List = - GroupRelayList.allAmong(emptyList(), chatRoomId).map { list -> - if (list.set != GroupRelaySet.General) return@map list - - GroupRelayList( - set = list.set, - signedEvent = GroupSignedWorkFixtures.relaySignedEvent(list.set), - relays = listOf(GroupRelay(two)), - ) - } - - private fun state(entries: List) = GroupCuratedEntriesUIState.Loaded( - localChatRoom = GroupSignedWorkFixtures.localChatRoom(), - groupCuratedEntries = entries, - relayLists = relayLists(), - ) - - private fun render( - uiState: GroupCuratedEntriesUIState, - onNavigateToRoute: (Route) -> Unit = {}, - transport: EventPublishTransport = FakeTransport(), - assertions: ComposeUiTest.() -> Unit - ) = runDesktopComposeUiTest(width = 400, height = 2000) { - setContent { - BennuTheme { - ProvideSnackbarHost { - Box(modifier = Modifier.fillMaxSize()) { - GroupCuratedEntriesScreen( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = null, - initialGroupCuratedEntriesUIState = uiState, - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - publishTransport = transport, - onNavigateToRoute = onNavigateToRoute, - onNavigateBack = {}, - ) - } - } - } - } - - assertions() - } -} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupCuratedSchemasScreenJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupCuratedSchemasScreenJvmTest.kt deleted file mode 100644 index 3ff0e362..00000000 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupCuratedSchemasScreenJvmTest.kt +++ /dev/null @@ -1,235 +0,0 @@ -package com.machankura.bennu.compose.ui.composable - -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.ui.Modifier -import androidx.compose.ui.test.ComposeUiTest -import androidx.compose.ui.test.ExperimentalTestApi -import androidx.compose.ui.test.assertCountEquals -import androidx.compose.ui.test.assertIsDisplayed -import androidx.compose.ui.test.getBoundsInRoot -import androidx.compose.ui.test.onAllNodesWithText -import androidx.compose.ui.test.onNodeWithContentDescription -import androidx.compose.ui.test.onNodeWithText -import androidx.compose.ui.test.performClick -import androidx.compose.ui.test.runDesktopComposeUiTest -import com.machankura.bennu.compose.nostr.GroupCuratedSchema -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.activeUserPublicKey -import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.chatRoomId -import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.schema -import com.machankura.bennu.compose.ui.composable.navigation.routes.BroadcastGroupSignedEventRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.CuratedSuggestionListRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.EditGroupCuratedSchemaRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.navigation.routes.SelectCuratedSchemaTemplateRoute -import com.machankura.bennu.compose.ui.composable.widgets.ProvideSnackbarHost -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.view.state.GroupCuratedSchemasUIState -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertNull -import kotlin.test.assertTrue - -/** - * The schemas of the lists the group curates on their own screen: one card per - * list, most recently signed first, each with its queue and its broadcast, and - * two ways on -- the card into the editor for a revision, the button into the - * template picker for a new list -- for a member holding a share. - */ -@OptIn(ExperimentalTestApi::class) -class GroupCuratedSchemasScreenJvmTest { - - private val films = schema("films", "Films worth translating", 1_700_000_900) - private val books = schema("books", "Books worth translating", 1_700_000_000) - - @Test - fun `the schemas are drawn most recently signed first, one card per list`() = render( - state(schemas = listOf(films, books)) - ) { - val newest = onNodeWithText("Films worth translating").getBoundsInRoot().top - val oldest = onNodeWithText("Books worth translating").getBoundsInRoot().top - assertTrue(newest < oldest, "the schemas were drawn oldest first") - - // What an entry asks for, and who may suggest one. - onAllNodesWithText("Fields: Identifier, Title", substring = true).assertCountEquals(2) - onAllNodesWithText("Public · ", substring = true).assertCountEquals(2) - onNodeWithText("Add schema").assertIsDisplayed() - } - - @Test - fun `every schema offers its own queue, under its own card`() { - var opened: Route? = null - - render(state(schemas = listOf(films, books)), onNavigateToRoute = { opened = it }) { - // One per list, because each list has its own queue -- and under the - // card it belongs to rather than once for the screen, since a button - // between two cards would say nothing about which it opened. - val buttons = onAllNodesWithText("View suggestions") - buttons.assertCountEquals(2) - - val filmsCard = onNodeWithText("Films worth translating").getBoundsInRoot().top - val booksCard = onNodeWithText("Books worth translating").getBoundsInRoot().top - val first = buttons[0].getBoundsInRoot().top - val second = buttons[1].getBoundsInRoot().top - - assertTrue(filmsCard < first && first < booksCard, "the first queue button is not under its card") - assertTrue(booksCard < second, "the second queue button is not under its card") - - buttons[1].performClick() - } - - assertEquals( - CuratedSuggestionListRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = null, - identifier = "books" - ), - opened - ) - } - - @Test - fun `every schema offers a broadcast, beside its queue`() { - var opened: Route? = null - - render(state(schemas = listOf(films, books)), onNavigateToRoute = { opened = it }) { - val buttons = onAllNodesWithText("Broadcast") - buttons.assertCountEquals(2) - - val filmsCard = onNodeWithText("Films worth translating").getBoundsInRoot().top - val booksCard = onNodeWithText("Books worth translating").getBoundsInRoot().top - assertTrue(filmsCard < buttons[0].getBoundsInRoot().top, "the first broadcast is not under its card") - assertTrue(booksCard < buttons[1].getBoundsInRoot().top, "the second broadcast is not under its card") - - buttons[0].performClick() - } - - assertEquals( - BroadcastGroupSignedEventRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = null, - signedEventId = films.signedEvent.id - ), - opened - ) - } - - @Test - fun `a card opens the editor on its own schema, for a member holding a share of the key`() { - var opened: Route? = null - - render(state(schemas = listOf(films, books)), onNavigateToRoute = { opened = it }) { - onNodeWithText("Books worth translating").performClick() - } - - assertEquals( - EditGroupCuratedSchemaRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = null, - identifier = "books", - // A revision starts from the schema itself, not from a shape. - template = null - ), - opened - ) - } - - @Test - fun `the button opens the template picker, not the editor`() { - var opened: Route? = null - - render(state(schemas = listOf(films)), onNavigateToRoute = { opened = it }) { - onNodeWithText("Add schema").performClick() - } - - // A new list has a shape to choose before it has a form to fill, and - // the picker is what opens the editor, on the shape chosen there. - assertEquals( - SelectCuratedSchemaTemplateRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = null - ), - opened - ) - } - - @Test - fun `a member holding no share of the key reads the schemas and is offered no editor`() { - var opened: Route? = null - - render(state(schemas = listOf(films), canSign = false), onNavigateToRoute = { opened = it }) { - // A schema exists to be read by people who were never in the room, so - // a member without a share reads it like anybody else and simply - // cannot propose a revision -- neither a new one nor an edit. - onNodeWithText("Films worth translating").assertIsDisplayed() - onNodeWithText("Add schema").assertDoesNotExist() - onNodeWithContentDescription("Edit schema").assertDoesNotExist() - - // The queue is the one thing on the screen the group did not write, - // and reading it takes no share of the key. - onNodeWithText("View suggestions").assertIsDisplayed() - - // A card that cannot be opened goes nowhere when tapped. - onNodeWithText("Films worth translating").performClick() - } - - assertNull(opened, "a card with no editor behind it opened something") - } - - @Test - fun `a group that curates nothing says so, and offers to add a schema`() { - var opened: Route? = null - - render(state(schemas = emptyList()), onNavigateToRoute = { opened = it }) { - onNodeWithText("This group hasn't published a curated schema yet.", substring = true) - .assertIsDisplayed() - onAllNodesWithText("View suggestions").assertCountEquals(0) - onNodeWithText("Add schema").assertIsDisplayed().performClick() - } - - assertEquals( - SelectCuratedSchemaTemplateRoute(activeUserPublicKey, chatRoomId, relayHint = null), - opened - ) - } - - private fun state( - schemas: List, - canSign: Boolean = true - ) = GroupCuratedSchemasUIState.Loaded( - localChatRoom = GroupSignedWorkFixtures.localChatRoom(), - groupCuratedSchemas = schemas, - canSign = canSign - ) - - private fun render( - uiState: GroupCuratedSchemasUIState, - onNavigateToRoute: (Route) -> Unit = {}, - assertions: ComposeUiTest.() -> Unit - ) = runDesktopComposeUiTest(width = 400, height = 2000) { - setContent { - BennuTheme { - ProvideSnackbarHost { - Box(modifier = Modifier.fillMaxSize()) { - GroupCuratedSchemasScreen( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = null, - initialGroupCuratedSchemasUIState = uiState, - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - onNavigateToRoute = onNavigateToRoute, - onNavigateBack = {}, - ) - } - } - } - } - - assertions() - } -} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupSignedWorkFixtures.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupSignedWorkFixtures.kt index 023fec93..f1ab7895 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupSignedWorkFixtures.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupSignedWorkFixtures.kt @@ -8,21 +8,11 @@ import com.machankura.bennu.compose.database.model.ChatRoom import com.machankura.bennu.compose.database.model.GroupKeyState import com.machankura.bennu.compose.database.model.GroupSignedEvent import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.GroupCuratedEntry -import com.machankura.bennu.compose.nostr.GroupCuratedSchema import com.machankura.bennu.compose.nostr.GroupNostrProfile import com.machankura.bennu.compose.nostr.GroupPost import com.machankura.bennu.compose.nostr.GroupRelay import com.machankura.bennu.compose.nostr.GroupRelayList import com.machankura.bennu.compose.nostr.GroupRelaySet -import com.machankura.bennu.compose.nostr.curated.CuratedEntry -import com.machankura.bennu.compose.nostr.curated.CuratedEntryEvent -import com.machankura.bennu.compose.nostr.curated.CuratedField -import com.machankura.bennu.compose.nostr.curated.CuratedFieldType -import com.machankura.bennu.compose.nostr.curated.CuratedSchema -import com.machankura.bennu.compose.nostr.curated.CuratedSchemaEvent -import com.machankura.bennu.compose.nostr.curated.CuratedSuggestionRef -import com.machankura.bennu.compose.nostr.curated.CuratedVisibility import kotlin.time.Instant /** @@ -39,8 +29,6 @@ internal object GroupSignedWorkFixtures { val activeUserPublicKey = "a".repeat(64) - val suggester = "eebb74ab6bfb8485722ab1d4acee856eee96f17a9e1721f9c7cc63376c40b860" - /** * The room, as this device names it. * @@ -137,83 +125,4 @@ internal object GroupSignedWorkFixtures { createdAt = Instant.fromEpochSeconds(createdAt) ) ) - - /** A list the group curates, as the schema it signed for it. */ - fun schema(identifier: String, name: String, createdAt: Long) = GroupCuratedSchema( - signedEvent = GroupSignedEvent( - id = createdAt.toString().padStart(64, 'c'), - chatRoomId = chatRoomId, - publicKey = chatRoomId, - kind = CuratedSchemaEvent.KIND, - tags = emptyArray(), - content = "", - signature = "f".repeat(128), - createdAt = Instant.fromEpochSeconds(createdAt) - ), - schema = CuratedSchema( - identifier = identifier, - title = "$name suggestion", - name = name, - description = "Things the group would translate, with a link to each.", - visibility = CuratedVisibility.Public, - fields = listOf(CuratedField.IDENTIFIER, CuratedField.TITLE), - relays = listOf("wss://relay.one.example") - ) - ) - - /** - * An entry the group accepted into the films list. The list's schema has a - * year, so the card has a glance to give. - */ - fun entry( - title: String, - createdAt: Long, - suggestedBy: String? = suggester - ): GroupCuratedEntry { - val list = schema("films", "Films worth translating", 1_700_000_000).let { films -> - films.copy( - schema = films.schema.copy( - fields = films.schema.fields + CuratedField("year", CuratedFieldType.Year, isRequired = false, label = "Year") - ) - ) - } - val identifier = title.lowercase().replace(' ', '-') - - return GroupCuratedEntry( - signedEvent = GroupSignedEvent( - id = createdAt.toString().padStart(64, 'd'), - chatRoomId = chatRoomId, - publicKey = chatRoomId, - kind = CuratedEntryEvent.CANONICAL_KIND, - // The root names the list, as a real entry's does: it is how - // the reading matched the entry to its schema, and how the - // broadcast finds the list's relays. - tags = arrayOf( - arrayOf("a", list.coordinate(), "", "root"), - arrayOf("d", identifier), - arrayOf("title", title) - ), - content = "", - signature = "f".repeat(128), - createdAt = Instant.fromEpochSeconds(createdAt) - ), - list = list, - entry = CuratedEntry( - kind = CuratedEntryEvent.CANONICAL_KIND, - id = createdAt.toString().padStart(64, 'd'), - pubKey = chatRoomId, - createdAt = createdAt, - identifier = identifier, - title = title, - values = mapOf( - "identifier" to listOf(identifier), - "title" to listOf(title), - "year" to listOf("2014"), - ), - source = suggestedBy?.let { - CuratedSuggestionRef(id = "a".repeat(64), coordinate = "31888:$it:$identifier", pubKey = it) - } - ) - ) - } } diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupSignedWorkRowsJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupSignedWorkRowsJvmTest.kt index ae73a17e..d652b4f6 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupSignedWorkRowsJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupSignedWorkRowsJvmTest.kt @@ -13,8 +13,6 @@ import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.compose.ui.test.runDesktopComposeUiTest import com.vitorpamplona.quartz.nip01Core.metadata.UserMetadata -import com.machankura.bennu.compose.nostr.GroupCuratedEntry -import com.machankura.bennu.compose.nostr.GroupCuratedSchema import com.machankura.bennu.compose.nostr.GroupNostrProfile import com.machankura.bennu.compose.nostr.GroupPost import com.machankura.bennu.compose.nostr.GroupRelayList @@ -23,13 +21,9 @@ import com.machankura.bennu.compose.repository.MantraRepository import com.machankura.bennu.compose.repository.NostrRepository import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.activeUserPublicKey import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.chatRoomId -import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.entry import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.post import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.profile -import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.schema import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.signedRelayLists -import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupCuratedEntriesRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupCuratedSchemasRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupNostrProfileRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupPostsRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupRelaysRoute @@ -42,7 +36,7 @@ import kotlin.test.assertEquals import kotlin.test.assertTrue /** - * The five rows on the group's screen that stand for its signed work, and what + * The three rows on the group's screen that stand for its signed work, and what * each one opens. * * The rows' contents need little testing -- a name and a count in a `ListItem` @@ -53,12 +47,12 @@ import kotlin.test.assertTrue * signs as and whose child it is -- and above what the room has *made*, because * the group's account of itself is part of its identity rather than part of its * work; and among themselves they read as a chain, from who the group says it is - * to what it has decided. That ordering is an intention a later `item {}` in + * to what it has said. That ordering is an intention a later `item {}` in * the wrong place would silently undo, and the screen is long enough that * nobody would notice. * - * **What they open.** A row is a promise about the screen behind it, and five - * rows that look alike are five chances to wire one to the wrong route. + * **What they open.** A row is a promise about the screen behind it, and three + * rows that look alike are three chances to wire one to the wrong route. * * **Their absence in a NIP-17 room.** A NIP-17 room's id is a conversation, not * a key it can sign as, so it has no nostr identity and never will. A row there @@ -75,16 +69,12 @@ class GroupSignedWorkRowsJvmTest { val nostrProfile = onNodeWithText("Nostr profile").getBoundsInRoot().top val relays = onNodeWithText("Relays").getBoundsInRoot().top val posts = onNodeWithText("Posts").getBoundsInRoot().top - val schemas = onNodeWithText("Curated schemas").getBoundsInRoot().top - val entries = onNodeWithText("Curated entries").getBoundsInRoot().top val subgroups = onNodeWithText("Subgroups").getBoundsInRoot().top assertTrue(signingKey < nostrProfile, "the nostr profile row climbed above the signing key row") assertTrue(nostrProfile < relays, "the relays row climbed above the profile") assertTrue(relays < posts, "the posts row climbed above the relays") - assertTrue(posts < schemas, "the curated schemas row climbed above the posts") - assertTrue(schemas < entries, "the curated entries row climbed above the schemas") - assertTrue(entries < subgroups, "the identity block fell below the group's work") + assertTrue(posts < subgroups, "the identity block fell below the group's work") } @Test @@ -93,7 +83,6 @@ class GroupSignedWorkRowsJvmTest { groupNostrProfile = profile, relayLists = signedRelayLists(), posts = listOf(post("The second thing", 1_700_000_900), post("The first thing", 1_700_000_000)), - schemas = listOf(schema("films", "Films worth translating", 1_700_000_000)) ) ) { // The group's own name and address, not the room's subject: the row is @@ -103,8 +92,6 @@ class GroupSignedWorkRowsJvmTest { // empty list is a decision, and the row counts decisions. onNodeWithText("2 of 4 lists agreed").assertIsDisplayed() onNodeWithText("2 posts").assertIsDisplayed() - onNodeWithText("1 schema").assertIsDisplayed() - onNodeWithText("No entries yet").assertIsDisplayed() } @Test @@ -114,8 +101,6 @@ class GroupSignedWorkRowsJvmTest { onNodeWithText("Not described yet").assertIsDisplayed() onNodeWithText("0 of 4 lists agreed").assertIsDisplayed() onNodeWithText("No posts yet").assertIsDisplayed() - onNodeWithText("No schemas yet").assertIsDisplayed() - onNodeWithText("No entries yet").assertIsDisplayed() } @Test @@ -138,8 +123,6 @@ class GroupSignedWorkRowsJvmTest { "Nostr profile" to GroupNostrProfileRoute(activeUserPublicKey, chatRoomId, relayHint = null), "Relays" to GroupRelaysRoute(activeUserPublicKey, chatRoomId, relayHint = null), "Posts" to GroupPostsRoute(activeUserPublicKey, chatRoomId, relayHint = null), - "Curated schemas" to GroupCuratedSchemasRoute(activeUserPublicKey, chatRoomId, relayHint = null), - "Curated entries" to GroupCuratedEntriesRoute(activeUserPublicKey, chatRoomId, relayHint = null), ) expected.forEach { (row, route) -> @@ -159,8 +142,6 @@ class GroupSignedWorkRowsJvmTest { groupNostrProfile = profile, relayLists = signedRelayLists(), posts = listOf(post("Something the group said", 1_700_000_000)), - schemas = listOf(schema("films", "Films worth translating", 1_700_000_000)), - entries = listOf(entry("The Rise and Rise of Bitcoin", 1_700_000_900)) ) ) { // The rows summarise; the cards, their broadcasts and the gated ways in @@ -169,13 +150,10 @@ class GroupSignedWorkRowsJvmTest { onNodeWithText("A group translating hard books into Sesotho.").assertDoesNotExist() onNodeWithText("relay.one.example").assertDoesNotExist() onNodeWithText("Something the group said").assertDoesNotExist() - onNodeWithText("The Rise and Rise of Bitcoin").assertDoesNotExist() onAllNodesWithText("Broadcast").assertCountEquals(0) onNodeWithText("Edit Nostr profile").assertDoesNotExist() onNodeWithText("Edit relays").assertDoesNotExist() onNodeWithText("Add post").assertDoesNotExist() - onNodeWithText("Add schema").assertDoesNotExist() - onNodeWithText("View suggestions").assertDoesNotExist() } @Test @@ -184,11 +162,11 @@ class GroupSignedWorkRowsJvmTest { ) { // Last in the identity block: after the rows and before the divider, // because it is about the whole block rather than any one row of it. - val entries = onNodeWithText("Curated entries").getBoundsInRoot().top + val posts = onNodeWithText("Posts").getBoundsInRoot().top val propose = onNodeWithText("Propose event").getBoundsInRoot().top val subgroups = onNodeWithText("Subgroups").getBoundsInRoot().top - assertTrue(entries < propose, "the paste entry climbed above the rows") + assertTrue(posts < propose, "the paste entry climbed above the rows") assertTrue(propose < subgroups, "the paste entry fell out of the identity block") } @@ -201,7 +179,7 @@ class GroupSignedWorkRowsJvmTest { // The rows themselves stay, because reading takes no share. onNodeWithText("Propose event").assertDoesNotExist() onNodeWithText("Nostr profile").assertIsDisplayed() - onNodeWithText("Curated entries").assertIsDisplayed() + onNodeWithText("Posts").assertIsDisplayed() } @Test @@ -211,12 +189,10 @@ class GroupSignedWorkRowsJvmTest { onNodeWithText("Nostr profile").assertDoesNotExist() onNodeWithText("Not described yet").assertDoesNotExist() - // The other four go with it: all five describe a nostr identity this + // The other two go with it: all three describe a nostr identity this // room does not have, and so does the paste. onNodeWithText("Relays").assertDoesNotExist() onNodeWithText("Posts").assertDoesNotExist() - onNodeWithText("Curated schemas").assertDoesNotExist() - onNodeWithText("Curated entries").assertDoesNotExist() onNodeWithText("Propose event").assertDoesNotExist() // The rest of the screen is untouched, so the rows' absence is an @@ -228,8 +204,6 @@ class GroupSignedWorkRowsJvmTest { groupNostrProfile: GroupNostrProfile?, relayLists: List = GroupRelayList.allAmong(emptyList(), chatRoomId), posts: List = emptyList(), - schemas: List = emptyList(), - entries: List = emptyList(), canEditNostrProfile: Boolean = true, mlsGroupState: String? = "state" ) = ChatRoomDetailUIState.Loaded( @@ -238,8 +212,6 @@ class GroupSignedWorkRowsJvmTest { groupNostrProfile = groupNostrProfile, groupRelayLists = relayLists, groupPosts = posts, - groupCuratedSchemas = schemas, - groupCuratedEntries = entries, canEditNostrProfile = canEditNostrProfile ) diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/ProposeGroupEventScreenJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/ProposeGroupEventScreenJvmTest.kt index dceea08e..522e622e 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/ProposeGroupEventScreenJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/ProposeGroupEventScreenJvmTest.kt @@ -25,7 +25,7 @@ import kotlin.test.Test * * The screen's one job beyond a text field is to tell a member, before a quorum * is asked, what the group would be signing or why it will not be asked. Both - * are read live off the paste, so both are tested by typing: a schema reads back + * are read live off the paste, so both are tested by typing: a relay list reads back * as the signing screen would describe it, junk is named as junk, and a kind * with no section to land in is refused with the kinds that have one. */ @@ -34,18 +34,16 @@ class ProposeGroupEventScreenJvmTest { private val chatRoomId = "d4c3b2a1".repeat(8) - private val schema = """{"kind":31889,"created_at":1735689600,"tags":[["d","bitcoin.mov"],""" + - """["title","bitcoin.mov suggestion"],["name","bitcoin.mov"],""" + - """["description","Fields for a bitcoin.mov entry."],["visibility","public"],""" + - """["field","title","text","required","","Title","{}"]],"content":"Fields for a bitcoin.mov entry."}""" + private val relayList = """{"kind":10002,"created_at":1735689600,""" + + """"tags":[["r","wss://relay.one.example"],["r","wss://relay.two.example","read"]],"content":""}""" @Test - fun `a pasted schema is read back as the signing screen would say it`() = render(state()) { - onNodeWithText("Unsigned event").performTextInput(schema) + fun `a pasted relay list is read back as the signing screen would say it`() = render(state()) { + onNodeWithText("Unsigned event").performTextInput(relayList) onNodeWithText("What the group would sign").assertIsDisplayed() - onNodeWithText("Kind 31889 · Curated schema").assertIsDisplayed() - onNodeWithText("bitcoin.mov · public · 1 field").assertIsDisplayed() + onNodeWithText("Kind 10002 · General relay list").assertIsDisplayed() + onNodeWithText("relay.one.example, relay.two.example").assertIsDisplayed() } @Test @@ -62,7 +60,7 @@ class ProposeGroupEventScreenJvmTest { onNodeWithText("Kind 30023 has nowhere to go on the group's screen.", substring = true) .assertIsDisplayed() - onNodeWithText("0, 1, 10002, 10006, 10007, 10050, 31889", substring = true).assertIsDisplayed() + onNodeWithText("0, 1, 10002, 10006, 10007, 10050", substring = true).assertIsDisplayed() } @Test diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/SelectCuratedSchemaTemplateScreenJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/SelectCuratedSchemaTemplateScreenJvmTest.kt deleted file mode 100644 index f6343208..00000000 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/SelectCuratedSchemaTemplateScreenJvmTest.kt +++ /dev/null @@ -1,115 +0,0 @@ -package com.machankura.bennu.compose.ui.composable - -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.ui.Modifier -import androidx.compose.ui.test.ComposeUiTest -import androidx.compose.ui.test.ExperimentalTestApi -import androidx.compose.ui.test.assertIsDisplayed -import androidx.compose.ui.test.getBoundsInRoot -import androidx.compose.ui.test.onNodeWithContentDescription -import androidx.compose.ui.test.onNodeWithText -import androidx.compose.ui.test.performClick -import androidx.compose.ui.test.runDesktopComposeUiTest -import com.machankura.bennu.compose.nostr.curated.CuratedSchemaTemplate -import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.activeUserPublicKey -import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.chatRoomId -import com.machankura.bennu.compose.ui.composable.navigation.routes.EditGroupCuratedSchemaRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.widgets.ProvideSnackbarHost -import com.machankura.bennu.compose.ui.theme.BennuTheme -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertTrue - -/** - * The first step of adding a schema: the shapes a list can start from, one - * card each, and the editor opened on the one tapped. - * - * **Every shape is offered, in the site's order, saying what it asks for.** A - * member choosing a shape reads the fields to choose, so the card lists them, - * and the list is the template's own -- a card that summarised a template in - * its own words could drift from what the editor then opens on. - * - * **A card opens the editor on its template and nothing else.** The route - * carries the key and no identifier, which is the whole of what the picker - * decides; the editor seeds from the key, so a wrong one here is a form that - * opens on the wrong fields with nothing saying so. - */ -@OptIn(ExperimentalTestApi::class) -class SelectCuratedSchemaTemplateScreenJvmTest { - - @Test - fun `every shape is offered, in the site's order, with what an entry in it asks for`() = render { - onNodeWithText("Start a list").assertIsDisplayed() - onNodeWithText("A list is a schema", substring = true).assertIsDisplayed() - - val links = onNodeWithText("Links & text").assertIsDisplayed().getBoundsInRoot().top - val discussion = onNodeWithText("Discussion").assertIsDisplayed().getBoundsInRoot().top - val catalogue = onNodeWithText("Catalogue").assertIsDisplayed().getBoundsInRoot().top - val custom = onNodeWithText("Custom").assertIsDisplayed().getBoundsInRoot().top - assertTrue( - links < discussion && discussion < catalogue && catalogue < custom, - "the shapes were drawn out of order" - ) - - // What each asks for, by label, the identifier included: the editor's - // row for it is there too and says it is derived. - onNodeWithText("Fields: Identifier, Title, Link, Text, Picture, Flair").assertIsDisplayed() - onNodeWithText("Fields: Identifier, Title, Text, Flair").assertIsDisplayed() - onNodeWithText( - "Fields: Identifier, Title, Year, Type, External id, Where to see it, Reference, " + - "Picture, Language, Description" - ).assertIsDisplayed() - onNodeWithText("Fields: Identifier, Title").assertIsDisplayed() - - // And what each is for, in the site's words. - onNodeWithText("Reddit’s default", substring = true).assertIsDisplayed() - onNodeWithText("bitcoin.mov’s shape", substring = true).assertIsDisplayed() - - onNodeWithContentDescription("Back").assertIsDisplayed() - } - - @Test - fun `a card opens the editor on its template, and on no schema`() { - var opened: Route? = null - - render(onNavigateToRoute = { opened = it }) { - onNodeWithText("Catalogue").performClick() - } - - assertEquals( - EditGroupCuratedSchemaRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = null, - identifier = null, - template = CuratedSchemaTemplate.Catalogue.key - ), - opened - ) - } - - private fun render( - onNavigateToRoute: (Route) -> Unit = {}, - assertions: ComposeUiTest.() -> Unit - ) = runDesktopComposeUiTest(width = 400, height = 1600) { - setContent { - BennuTheme { - ProvideSnackbarHost { - Box(modifier = Modifier.fillMaxSize()) { - SelectCuratedSchemaTemplateScreen( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = null, - onNavigateToRoute = onNavigateToRoute, - onNavigateBack = {}, - ) - } - } - } - } - - assertions() - } -} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/AcceptCuratedSuggestionViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/AcceptCuratedSuggestionViewModelJvmTest.kt deleted file mode 100644 index 322e8664..00000000 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/AcceptCuratedSuggestionViewModelJvmTest.kt +++ /dev/null @@ -1,442 +0,0 @@ -package com.machankura.bennu.compose.ui.view.model - -import androidx.compose.foundation.text.input.setTextAndPlaceCursorAtEnd -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.Kind -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.flowOf -import kotlinx.coroutines.runBlocking -import kotlinx.coroutines.test.UnconfinedTestDispatcher -import kotlinx.coroutines.test.resetMain -import kotlinx.coroutines.test.setMain -import kotlinx.coroutines.withTimeout -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.FrostSigningSession -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.machankura.bennu.compose.database.model.NostrEvent -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.database.model.intermdiate.LocalNostrEvent -import com.machankura.bennu.compose.database.model.types.SynchronizationFilter -import com.machankura.bennu.compose.nostr.CuratedSuggestion -import com.machankura.bennu.compose.nostr.GroupCuratedSchema -import com.machankura.bennu.compose.nostr.curated.CuratedEntryEvent -import com.machankura.bennu.compose.nostr.curated.CuratedEntryProblem -import com.machankura.bennu.compose.nostr.curated.CuratedField -import com.machankura.bennu.compose.nostr.curated.CuratedFieldConfig -import com.machankura.bennu.compose.nostr.curated.CuratedFieldType -import com.machankura.bennu.compose.nostr.curated.CuratedSchema -import com.machankura.bennu.compose.nostr.curated.CuratedSchemaEvent -import com.machankura.bennu.compose.nostr.curated.CuratedUnsupportedField -import com.machankura.bennu.compose.nostr.curated.CuratedVisibility -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.repository.NostrRepository -import com.machankura.bennu.compose.ui.view.state.AcceptCuratedSuggestionUIState -import kotlin.test.AfterTest -import kotlin.test.BeforeTest -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFalse -import kotlin.test.assertNotNull -import kotlin.test.assertNull -import kotlin.test.assertTrue -import kotlin.time.Instant - -/** - * The decisions the accept form makes that nothing else can check. - * - * **What is opened and what is kept.** The form asks for what the schema's - * form asks for, and keeps the `d` and the derived fields as they were - * suggested; getting that wrong in one direction lets a member invent a - * hashtag the app was supposed to derive, and in the other loses the - * coordinate that makes a re-curation a revision. - * - * **What the button refuses.** An entry the queue would not count is refused - * with the field named, before a quorum is asked for it -- and the entry it - * does propose is the one the queue screen will read back, source and all. - * - * **What the loader finds.** The suggestion is looked up by the queue's own - * reading, so what is accepted is what was shown. - */ -@OptIn(ExperimentalCoroutinesApi::class) -class AcceptCuratedSuggestionViewModelJvmTest { - private val chatRoomId = "d4c3b2a1".repeat(8) - private val ada = "a".repeat(64) - private val bob = "b".repeat(64) - - private val schema = GroupCuratedSchema( - signedEvent = GroupSignedEvent( - id = "c".repeat(64), - chatRoomId = chatRoomId, - publicKey = chatRoomId, - kind = CuratedSchemaEvent.KIND, - tags = emptyArray(), - content = "", - signature = "f".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_000), - ), - schema = CuratedSchema( - identifier = "films", - title = "Film suggestion", - name = "Films worth translating", - description = "Films the group would subtitle.", - visibility = CuratedVisibility.Public, - fields = listOf( - CuratedField.IDENTIFIER, - CuratedField.TITLE, - CuratedField("year", CuratedFieldType.Year, isRequired = false, label = "Year", config = CuratedFieldConfig(min = 1900, max = 2100)), - CuratedField("type", CuratedFieldType.Enum, isRequired = true, label = "Type", config = CuratedFieldConfig(options = listOf("movie", "documentary"))), - CuratedField("watchUrl", CuratedFieldType.Url, isRequired = false, label = "Watch URL", config = CuratedFieldConfig(tag = "r", marker = "watch", repeat = true)), - CuratedField("imdbUrl", CuratedFieldType.Url, isRequired = false, label = "IMDb URL", config = CuratedFieldConfig(tag = "r", marker = "imdb")), - CuratedField("hashtags", CuratedFieldType.Token, isRequired = false, label = "Hashtags", config = CuratedFieldConfig(tag = "t", repeat = true, derived = true)), - CuratedField("review", CuratedFieldType.LongText, isRequired = false, label = "Review", config = CuratedFieldConfig(tag = CuratedFieldConfig.CONTENT_TAG)), - ), - requireAny = listOf(listOf("watchUrl", "imdbUrl")), - relays = listOf("wss://relay.one.example"), - ).normalized(), - ) - - private val localChatRoom = LocalChatRoom( - chatRoom = ChatRoom( - id = chatRoomId, - userPublicKey = ada, - subject = "Translation room", - description = null, - initialGiftWrapPayloadId = "sdfaer", - mlsGroupState = "state" - ) - ) - - /** *Magic Money* as Bob suggested it: two watch links, and hashtags his client derived. */ - private val suggestedEvent = NostrEvent( - id = "1".repeat(64), - pubKey = bob, - kind = CuratedSchemaEvent.SUGGESTION_KIND, - tags = arrayOf( - arrayOf("d", "magic-money"), - arrayOf("title", "Magic Money"), - arrayOf("year", "2018"), - arrayOf("type", "documentary"), - arrayOf("r", "https://example.com/watch", "watch"), - arrayOf("r", "https://mirror.example/watch", "watch"), - arrayOf("t", "bitcoin"), - arrayOf("t", "documentary"), - arrayOf("a", schema.coordinate(), "", "root"), - ), - content = "Follows the early community.", - sig = "b".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_000), - ) - - private val suggestion: CuratedSuggestion = CuratedSuggestion.queueOf( - schema, - listOf(LocalNostrEvent(nostrEvent = suggestedEvent, profile = null)) - ).single() - - private fun loaded(canSign: Boolean = true) = AcceptCuratedSuggestionUIState.Loaded( - localChatRoom = localChatRoom, - schema = schema, - suggestion = suggestion, - canSign = canSign, - ) - - /** What was asked of the signing repository, and the session it answers with. */ - private class RecordingSigning(private val session: FrostSigningSession?) : - FrostSigningRepository by FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY { - var kind: Kind? = null - var tags: Array>? = null - var content: String? = null - - override suspend fun canSign(chatRoomId: String): Boolean = true - - override suspend fun proposeSigning( - localChatRoom: LocalChatRoom, - userPublicKey: HexKey, - kind: Kind, - tags: Array>, - content: String - ): FrostSigningSession? { - this.kind = kind - this.tags = tags - this.content = content - return session - } - } - - private fun session() = FrostSigningSession( - id = "session-1", - chatRoomId = chatRoomId, - coordinatorPublicKey = ada, - userPublicKey = ada, - dkgSessionId = "dkg-1", - threshold = 2, - participantCount = 3, - signerId = 1, - ) - - private fun viewModel( - signing: FrostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, - nostrRepository: NostrRepository = NostrRepository.NO_OP_NOSTR_REPOSITORY, - chatRepository: ChatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - suggestionId: String = suggestion.id, - ) = AcceptCuratedSuggestionViewModel( - chatRoomId = chatRoomId, - activeUserPublicKey = ada, - relayHint = null, - identifier = "films", - suggestionId = suggestionId, - initialAcceptCuratedSuggestionUIState = AcceptCuratedSuggestionUIState.Loading, - nostrRepository = nostrRepository, - chatRepository = chatRepository, - frostSigningRepository = signing, - ) - - @BeforeTest - fun setUp() { - Dispatchers.setMain(UnconfinedTestDispatcher()) - } - - @AfterTest - fun tearDown() { - Dispatchers.resetMain() - } - - @Test - fun `the form opens what the schema asks for, one input per value, and keeps the rest`() { - val state = loaded() - val viewModel = viewModel() - viewModel.seedWorkingCopy(state) - - // Not the identifier -- it writes to `d` -- and not the derived hashtags. - assertEquals( - listOf("title", "year", "type", "watchUrl", "imdbUrl", "review"), - AcceptCuratedSuggestionViewModel.editableFields(state).map { it.name } - ) - assertEquals( - listOf("identifier", "hashtags"), - AcceptCuratedSuggestionViewModel.keptFields(state).map { it.name } - ) - - assertEquals(listOf("Magic Money"), viewModel.inputs["title"]?.map { it.text.toString() }) - assertEquals(listOf("2018"), viewModel.inputs["year"]?.map { it.text.toString() }) - // A field that repeats gets an input per value the suggestion carried. - assertEquals( - listOf("https://example.com/watch", "https://mirror.example/watch"), - viewModel.inputs["watchUrl"]?.map { it.text.toString() } - ) - // A field the suggestion has nothing for gets one blank to type into. - assertEquals(listOf(""), viewModel.inputs["imdbUrl"]?.map { it.text.toString() }) - assertNull(viewModel.inputs["identifier"], "the identifier was opened for editing") - assertNull(viewModel.inputs["hashtags"], "a derived field was opened for editing") - } - - @Test - fun `seeding again leaves an edit alone`() { - val state = loaded() - val viewModel = viewModel() - viewModel.seedWorkingCopy(state) - viewModel.inputs["year"]!![0].setTextAndPlaceCursorAtEnd("2019") - - viewModel.seedWorkingCopy(state) - - assertEquals("2019", viewModel.inputs["year"]!![0].text.toString()) - } - - @Test - fun `the draft is what was typed plus what was kept, and the d is the suggestion's`() { - val state = loaded() - val viewModel = viewModel() - viewModel.seedWorkingCopy(state) - - viewModel.inputs["year"]!![0].setTextAndPlaceCursorAtEnd("2019") - viewModel.addValue("watchUrl") - viewModel.inputs["watchUrl"]!![2].setTextAndPlaceCursorAtEnd("https://third.example/watch") - viewModel.removeValue("watchUrl", 0) - - val draft = viewModel.draft(state) - - assertEquals(listOf("magic-money"), draft["identifier"]) - assertEquals(listOf("2019"), draft["year"]) - assertEquals(listOf("https://mirror.example/watch", "https://third.example/watch"), draft["watchUrl"]) - assertEquals(listOf("bitcoin", "documentary"), draft["hashtags"]) - // A blank input comes through; the builder is what drops it. - assertEquals(listOf(""), draft["imdbUrl"]) - } - - @Test - fun `removing the last input leaves a blank one rather than nothing`() { - val state = loaded() - val viewModel = viewModel() - viewModel.seedWorkingCopy(state) - - viewModel.removeValue("year", 0) - - assertEquals(listOf(""), viewModel.inputs["year"]?.map { it.text.toString() }) - } - - @Test - fun `an entry the queue would refuse is refused with the field named, and nothing is proposed`() { - val state = loaded() - val signing = RecordingSigning(session()) - val viewModel = viewModel(signing) - viewModel.seedWorkingCopy(state) - - viewModel.inputs["year"]!![0].setTextAndPlaceCursorAtEnd("1850") - viewModel.inputs["type"]!![0].setTextAndPlaceCursorAtEnd("musical") - - var invalid = false - viewModel.proposeEntry(state, onSuccess = { error("proposed") }, onInvalid = { invalid = true }, onFailure = { error("failed") }) - - assertTrue(invalid) - assertEquals(listOf(CuratedEntryProblem.Reason.BelowMinimum), viewModel.problemsFor("year").map { it.reason }) - assertEquals(listOf(CuratedEntryProblem.Reason.NotAnOption), viewModel.problemsFor("type").map { it.reason }) - assertEquals(emptyList(), viewModel.problemsAboutTheEntry(state)) - assertNull(signing.kind, "a refused entry was proposed anyway") - assertFalse(viewModel.isActionPending.value) - } - - @Test - fun `a list with a required field this build cannot write is refused before a quorum is spent`() { - // The schema was written by a client that knows a type this build does - // not. The reading is fine without it; an entry written without it is - // not, and the refusal has no input to sit under, so it goes at the top - // with the field's own label. - val stars = listOf("field", "rating", "stars", "required", "5", "Rating", "{}") - val state = loaded().copy( - schema = schema.copy( - schema = schema.schema.copy( - unsupportedFields = listOf(CuratedUnsupportedField("rating", "stars", isRequired = true, label = "Rating", tag = stars)) - ) - ) - ) - val signing = RecordingSigning(session()) - val viewModel = viewModel(signing) - viewModel.seedWorkingCopy(state) - - var invalid = false - viewModel.proposeEntry(state, onSuccess = { error("proposed") }, onInvalid = { invalid = true }, onFailure = { error("failed") }) - - assertTrue(invalid) - assertEquals( - listOf(CuratedEntryProblem("rating", CuratedEntryProblem.Reason.UnsupportedType)), - viewModel.problemsAboutTheEntry(state) - ) - assertNull(signing.kind, "an entry the list's other readers would refuse was proposed anyway") - } - - @Test - fun `a require-any rule the edit broke is filed under its first field`() { - val state = loaded() - val viewModel = viewModel() - viewModel.seedWorkingCopy(state) - - viewModel.removeValue("watchUrl", 0) - viewModel.removeValue("watchUrl", 0) - - viewModel.proposeEntry(state, onSuccess = {}, onInvalid = {}, onFailure = {}) - - assertEquals(listOf(CuratedEntryProblem.Reason.RequireAnyUnmet), viewModel.problemsFor("watchUrl").map { it.reason }) - } - - @Test - fun `the entry proposed is the canonical one the queue will read back`() { - val state = loaded() - val signing = RecordingSigning(session()) - val viewModel = viewModel(signing) - viewModel.seedWorkingCopy(state) - viewModel.inputs["year"]!![0].setTextAndPlaceCursorAtEnd("2019") - - var sessionId: String? = null - viewModel.proposeEntry(state, onSuccess = { sessionId = it }, onInvalid = { error("invalid") }, onFailure = { error("failed") }) - - runBlocking { - withTimeout(5_000) { - while (sessionId == null) kotlinx.coroutines.delay(10) - } - } - - assertEquals("session-1", sessionId) - assertEquals(CuratedEntryEvent.CANONICAL_KIND, signing.kind) - assertEquals("Follows the early community.", signing.content) - - val tags = assertNotNull(signing.tags).map { it.toList() } - assertTrue(listOf("d", "magic-money") in tags, "the entry lost the suggestion's d") - assertTrue(listOf("year", "2019") in tags, "the edit was not signed") - assertTrue(listOf("t", "bitcoin") in tags && listOf("t", "documentary") in tags, "the derived hashtags were dropped") - assertTrue(listOf("a", schema.coordinate(), "wss://relay.one.example", "root") in tags, "the entry does not reply to the list") - assertTrue(listOf("a", "31888:$bob:magic-money", "", "mention") in tags, "the entry does not point at the suggestion") - assertTrue(listOf("e", suggestion.id, "", "mention") in tags, "the entry does not pin the version read") - assertTrue(listOf("p", bob) in tags, "the suggester is not credited") - - // And it is what the queue counts as the group's entry for that suggestion. - val signed = NostrEvent( - id = "2".repeat(64), - pubKey = chatRoomId, - kind = CuratedEntryEvent.CANONICAL_KIND, - tags = signing.tags!!, - content = signing.content!!, - sig = "b".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_900), - ) - val queue = CuratedSuggestion.queueOf( - schema, - listOf(LocalNostrEvent(suggestedEvent, null), LocalNostrEvent(signed, null)) - ) - assertTrue(queue.single().isCurated, "the queue does not count the proposed entry as curating the suggestion") - } - - @Test - fun `a session that could not be opened is a failure, and the form stays`() { - val state = loaded() - val viewModel = viewModel(RecordingSigning(session = null)) - viewModel.seedWorkingCopy(state) - - var failed = false - viewModel.proposeEntry(state, onSuccess = { error("proposed") }, onInvalid = { error("invalid") }, onFailure = { failed = true }) - - runBlocking { - withTimeout(5_000) { - while (!failed) kotlinx.coroutines.delay(10) - } - } - - assertEquals(emptyList(), viewModel.problems) - assertEquals("Magic Money", viewModel.inputs["title"]!![0].text.toString()) - } - - @Test - fun `the loader finds the suggestion by the queue's reading, and says when it cannot`() { - val nostrRepository = object : NostrRepository by NostrRepository.NO_OP_NOSTR_REPOSITORY { - override suspend fun observeNostrEventsMatching(synchronizationFilter: SynchronizationFilter): Flow> = - flowOf(listOf(LocalNostrEvent(nostrEvent = suggestedEvent, profile = null))) - } - val chatRepository = object : ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY { - override suspend fun getChatRoomByIdentifier(id: HexKey): LocalChatRoom? = localChatRoom - override suspend fun groupCuratedSchemas(chatRoomId: String): List = listOf(schema) - } - - val found = viewModel(RecordingSigning(null), nostrRepository, chatRepository) - found.initiate() - val loaded = await { found.acceptCuratedSuggestionUIState as? AcceptCuratedSuggestionUIState.Loaded } - assertEquals("Magic Money", loaded.suggestion.entry.title) - assertTrue(loaded.canSign) - - val missing = viewModel(RecordingSigning(null), nostrRepository, chatRepository, suggestionId = "9".repeat(64)) - missing.initiate() - val error = await { missing.acceptCuratedSuggestionUIState as? AcceptCuratedSuggestionUIState.Error } - assertEquals("Couldn't find that suggestion", error.message) - } - - private fun await(read: () -> T?): T = runBlocking { - withTimeout(5_000) { - var value = read() - while (value == null) { - kotlinx.coroutines.delay(10) - value = read() - } - value - } - } -} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/BroadcastGroupSignedEventViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/BroadcastGroupSignedEventViewModelJvmTest.kt index 51d8340d..8a721014 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/BroadcastGroupSignedEventViewModelJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/BroadcastGroupSignedEventViewModelJvmTest.kt @@ -27,11 +27,6 @@ import com.machankura.bennu.compose.nostr.GroupRelayList import com.machankura.bennu.compose.nostr.GroupRelaySet import com.machankura.bennu.compose.nostr.Relays import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent -import com.machankura.bennu.compose.nostr.GroupCuratedSchema -import com.machankura.bennu.compose.nostr.curated.CuratedEntryEvent -import com.machankura.bennu.compose.nostr.curated.CuratedSchema -import com.machankura.bennu.compose.nostr.curated.CuratedSchemaEvent -import com.machankura.bennu.compose.nostr.curated.CuratedVisibility import com.machankura.bennu.compose.repository.ChatRepository import com.machankura.bennu.compose.ui.view.model.BroadcastGroupSignedEventViewModel.RelayOutcome import com.machankura.bennu.compose.ui.view.state.BroadcastGroupSignedEventUIState @@ -51,7 +46,7 @@ import kotlin.time.Instant * **Where an event goes before anyone says otherwise.** The seeded list is what a * member who reads nothing and presses the button sends to, so it has to be the * group's own answer where the group has given one, has to leave out what the - * group has blocked, and has to widen for the two kinds whose readers would not + * group has blocked, and has to widen for relay lists, whose readers would not * otherwise find them. * * **What each relay's answer becomes.** The pool answers once per relay in three @@ -219,83 +214,18 @@ class BroadcastGroupSignedEventViewModelJvmTest { } } - @Test - fun `a curated schema also goes to the relays it names for its own replies`() { - val relayLists = agreed(GroupRelaySet.General to listOf(GroupRelay(one))) - - val seeded = BroadcastGroupSignedEventViewModel.defaultRelaysFor( - relayLists = relayLists, - kind = CuratedSchemaEvent.KIND, - tags = arrayOf( - arrayOf("d", "films"), - arrayOf("relay", three.url), - ), - content = "Films worth translating.", - ) - - // The group's relay first, then the list's own -- a client reading - // suggestions on the list's relay finds the schema they answer. - assertEquals(listOf(one, three), seeded) - } - - @Test - fun `an entry into a curated list goes to the list's relays, found by the coordinate it replies to`() { - val relayLists = agreed(GroupRelaySet.General to listOf(GroupRelay(one))) - - val films = GroupCuratedSchema( - signedEvent = relaySignedEvent(GroupRelaySet.General).copy(kind = CuratedSchemaEvent.KIND), - schema = CuratedSchema( - identifier = "films", - title = "Film suggestion", - name = "Films worth translating", - description = "Films the group would subtitle.", - visibility = CuratedVisibility.Public, - relays = listOf(three.url), - ).normalized(), - ) - val books = films.copy(schema = films.schema.copy(identifier = "books", relays = listOf(two.url))) - - val seeded = BroadcastGroupSignedEventViewModel.defaultRelaysFor( - relayLists = relayLists, - kind = CuratedEntryEvent.CANONICAL_KIND, - tags = arrayOf( - arrayOf("d", "magic-money"), - arrayOf("title", "Magic Money"), - arrayOf("a", films.coordinate(), "", "root"), - ), - content = "", - schemas = listOf(books, films), - ) - - // The group's relay, then the relays of the list replied to -- and not - // the other list's: the NIP sends an entry where its own schema says. - assertEquals(listOf(one, three), seeded) - - // An entry whose schema this device does not hold goes where the group - // publishes, since there is nothing else to go on. - assertEquals( - listOf(one), - BroadcastGroupSignedEventViewModel.defaultRelaysFor( - relayLists = relayLists, - kind = CuratedEntryEvent.CANONICAL_KIND, - tags = arrayOf(arrayOf("a", "31889:${"0".repeat(64)}:elsewhere", "", "root")), - schemas = listOf(books, films), - ) - ) - } - @Test fun `seeding happens once, so an emptied list stays empty`() { val viewModel = viewModel() val relayLists = agreed(GroupRelaySet.General to listOf(GroupRelay(one))) val event = signedEvent() - viewModel.seedRelays(relayLists, event.kind, event.tags, event.content) - viewModel.seedRelays(relayLists, event.kind, event.tags, event.content) + viewModel.seedRelays(relayLists, event.kind) + viewModel.seedRelays(relayLists, event.kind) assertEquals(listOf(one), viewModel.relays.toList()) viewModel.removeRelay(one) - viewModel.seedRelays(relayLists, event.kind, event.tags, event.content) + viewModel.seedRelays(relayLists, event.kind) assertEquals(emptyList(), viewModel.relays.toList()) } diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/CuratedSuggestionListViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/CuratedSuggestionListViewModelJvmTest.kt deleted file mode 100644 index 195650ec..00000000 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/CuratedSuggestionListViewModelJvmTest.kt +++ /dev/null @@ -1,335 +0,0 @@ -package com.machankura.bennu.compose.ui.view.model - -import androidx.lifecycle.viewModelScope -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer -import kotlinx.coroutines.cancel -import kotlinx.coroutines.delay -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.flowOf -import kotlinx.coroutines.runBlocking -import kotlinx.coroutines.withTimeout -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.machankura.bennu.compose.database.model.NostrEvent -import com.machankura.bennu.compose.database.model.SynchronizeNostrEventRequest -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.database.model.intermdiate.LocalNostrEvent -import com.machankura.bennu.compose.database.model.types.SynchronizationFilter -import com.machankura.bennu.compose.nostr.CuratedSuggestion -import com.machankura.bennu.compose.nostr.GroupCuratedSchema -import com.machankura.bennu.compose.nostr.GroupRelay -import com.machankura.bennu.compose.nostr.GroupRelayList -import com.machankura.bennu.compose.nostr.GroupRelaySet -import com.machankura.bennu.compose.nostr.Relays -import com.machankura.bennu.compose.nostr.curated.CuratedEntry -import com.machankura.bennu.compose.nostr.curated.CuratedField -import com.machankura.bennu.compose.nostr.curated.CuratedSchema -import com.machankura.bennu.compose.nostr.curated.CuratedSchemaEvent -import com.machankura.bennu.compose.nostr.curated.CuratedVisibility -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.NostrRepository -import com.machankura.bennu.compose.ui.view.state.CuratedSuggestionListUIState -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFalse -import kotlin.test.assertIs -import kotlin.test.assertTrue -import kotlin.time.Instant - -/** - * The decisions the queue screen's view model makes that nothing else can check. - * - * **Where the queue is read from.** The schema's relays, then the group's, then - * the default -- and getting the order wrong is quiet, because a queue read - * from the wrong relay is an empty queue with no error attached. - * - * **What is asked for.** One request per relay carrying the NIP's two queries, - * and the local watch over the same rows, so that what comes back is what is - * shown. - * - * **When looking stops.** Rows arriving end it; nothing arriving leaves it to - * the timer. A screen that stopped looking on an empty first read of the local - * table would call every list empty before its relays had been asked. - */ -class CuratedSuggestionListViewModelJvmTest { - private val chatRoomId = "d4c3b2a1".repeat(8) - private val ada = "a".repeat(64) - - private val one = RelayUrlNormalizer.normalize("wss://relay.one.example") - private val two = RelayUrlNormalizer.normalize("wss://relay.two.example") - - private fun schema(relays: List) = GroupCuratedSchema( - signedEvent = GroupSignedEvent( - id = "c".repeat(64), - chatRoomId = chatRoomId, - publicKey = chatRoomId, - kind = CuratedSchemaEvent.KIND, - tags = emptyArray(), - content = "", - signature = "f".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_000), - ), - schema = CuratedSchema( - identifier = "films", - title = "Film suggestion", - name = "Films worth translating", - description = "Films the group would subtitle.", - visibility = CuratedVisibility.Public, - fields = listOf(CuratedField.IDENTIFIER, CuratedField.TITLE), - relays = relays, - ).normalized(), - ) - - private val localChatRoom = LocalChatRoom( - chatRoom = ChatRoom( - id = chatRoomId, - userPublicKey = ada, - subject = "Translation room", - description = null, - initialGiftWrapPayloadId = "sdfaer", - mlsGroupState = "state" - ) - ) - - private fun general(relays: List, agreed: Boolean = true) = GroupRelayList( - set = GroupRelaySet.General, - signedEvent = if (agreed) { - GroupSignedEvent( - id = "a".repeat(64), - chatRoomId = chatRoomId, - publicKey = chatRoomId, - kind = GroupRelaySet.General.kind, - tags = emptyArray(), - content = "", - signature = "f".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_000), - ) - } else { - null - }, - relays = relays, - ) - - @Test - fun `the schema's own relays come first, and two spellings of one are one`() { - val asked = CuratedSuggestionListViewModel.relaysToAsk( - schema(listOf("wss://relay.one.example", "wss://relay.two.example/", "wss://relay.one.example/")), - general = general(listOf(GroupRelay(RelayUrlNormalizer.normalize("wss://relay.three.example")))), - ) - - assertEquals(listOf(one.url, two.url), asked) - assertEquals(2, asked.size, "one relay spelled two ways was asked twice") - } - - @Test - fun `a schema naming no relays is read from where the group reads`() { - val three = RelayUrlNormalizer.normalize("wss://relay.three.example") - val four = RelayUrlNormalizer.normalize("wss://relay.four.example") - - // The group's read relays, and not its write-only one: this is a read. - assertEquals( - listOf(three.url), - CuratedSuggestionListViewModel.relaysToAsk( - schema(emptyList()), - general = general(listOf(GroupRelay(three), GroupRelay(four, read = false, write = true))), - ) - ) - - // Nothing agreed, or agreed empty: the build's own relay rather than nobody. - assertEquals( - listOf(Relays.ephemeral.url), - CuratedSuggestionListViewModel.relaysToAsk(schema(emptyList()), general = null) - ) - assertEquals( - listOf(Relays.ephemeral.url), - CuratedSuggestionListViewModel.relaysToAsk(schema(emptyList()), general = general(emptyList())) - ) - assertEquals( - listOf(Relays.ephemeral.url), - CuratedSuggestionListViewModel.relaysToAsk( - schema(emptyList()), - general = general(listOf(GroupRelay(three)), agreed = false) - ) - ) - } - - @Test - fun `one request per relay, carrying the NIP's two queries for the coordinate`() { - val schema = schema(listOf(one.url)) - val requests = CuratedSuggestionListViewModel.requestsFor(schema, listOf(one.url, two.url)) - - assertEquals(listOf(one.url, two.url), requests.map { it.relayURL }) - assertTrue(requests.all { it.purpose == CuratedSuggestionListViewModel.PURPOSE }) - - val (suggestions, canonical) = requests.first().synchronizationFilters - val coordinate = "31889:$chatRoomId:films" - - assertEquals(listOf(31888), suggestions.kinds?.toList()) - assertEquals(mapOf("a" to listOf(coordinate)), suggestions.tags) - assertEquals(null, suggestions.authors, "suggestions are not scoped by author: anyone may make one") - - assertEquals(listOf(31890), canonical.kinds?.toList()) - assertEquals(listOf(chatRoomId), canonical.authors?.toList(), "canonical entries are the group's alone") - assertEquals(mapOf("a" to listOf(coordinate)), canonical.tags) - - // And the watch covers both, so what is asked for is what is shown. - val watched = schema.queueReadFilter() - assertEquals(listOf(31888, 31890), watched.kinds?.toList()) - assertEquals(mapOf("a" to listOf(coordinate)), watched.tags) - } - - @Test - fun `rows arriving end the looking, and an empty read does not`() { - val asking = CuratedSuggestionListUIState.Loaded( - localChatRoom = localChatRoom, - schema = schema(listOf(one.url)), - relays = listOf(one.url), - isAsking = true, - ) - - val stillEmpty = CuratedSuggestionListViewModel.withQueue(asking, emptyList()) - assertTrue(stillEmpty.isAsking, "an empty first read of the local table was taken as the relays' answer") - - val arrived = CuratedSuggestionListViewModel.withQueue(asking, listOf(row("Magic Money", 1_700_000_000))) - assertFalse(arrived.isAsking) - assertEquals(listOf("Magic Money"), arrived.suggestions.map { it.entry.title }) - - // Once the timer has called it empty, a later arrival is still shown. - val late = CuratedSuggestionListViewModel.withQueue(stillEmpty.copy(isAsking = false), listOf(row("Late", 1_700_000_900))) - assertFalse(late.isAsking) - assertEquals(listOf("Late"), late.suggestions.map { it.entry.title }) - } - - @Test - fun `opening the screen asks the schema's relays and shows what the table holds for them`() { - val schema = schema(listOf(one.url)) - val queued = mutableListOf() - val watched = mutableListOf() - - val stored = NostrEvent( - id = "1".repeat(64), - pubKey = ada, - kind = CuratedSchemaEvent.SUGGESTION_KIND, - tags = arrayOf( - arrayOf("d", "magic-money"), - arrayOf("title", "Magic Money"), - arrayOf("a", schema.coordinate(), "", "root"), - ), - content = "", - sig = "b".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_000), - ) - - val nostrRepository = object : NostrRepository by NostrRepository.NO_OP_NOSTR_REPOSITORY { - override suspend fun queueSynchronizeNostrEvent(synchronizeNostrEventRequests: List) { - queued += synchronizeNostrEventRequests - } - - override suspend fun observeNostrEventsMatching(synchronizationFilter: SynchronizationFilter): Flow> { - watched += synchronizationFilter - return flowOf(listOf(LocalNostrEvent(nostrEvent = stored, profile = null))) - } - } - - val chatRepository = object : ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY { - override suspend fun getChatRoomByIdentifier(id: HexKey): LocalChatRoom? = localChatRoom - override suspend fun groupCuratedSchemas(chatRoomId: String): List = listOf(schema) - override suspend fun groupRelayLists(chatRoomId: String): List = emptyList() - } - - val viewModel = CuratedSuggestionListViewModel( - chatRoomId = chatRoomId, - activeUserPublicKey = ada, - relayHint = null, - identifier = "films", - initialCuratedSuggestionListUIState = CuratedSuggestionListUIState.Loading, - nostrRepository = nostrRepository, - chatRepository = chatRepository, - ) - - try { - viewModel.initiate() - - // The read runs on IO and lands on the state when it lands; the - // assertion waits for the rows rather than for a fixed time. - val loaded = runBlocking { - withTimeout(5_000) { - while (true) { - val state = viewModel.curatedSuggestionListUIState - if (state is CuratedSuggestionListUIState.Loaded && state.suggestions.isNotEmpty()) break - delay(20) - } - assertIs(viewModel.curatedSuggestionListUIState) - } - } - - assertEquals(listOf(one.url), loaded.relays) - assertEquals(listOf(one.url), queued.map { it.relayURL }) - assertEquals(listOf(schema.queueReadFilter()), watched) - assertEquals(listOf("Magic Money"), loaded.suggestions.map { it.entry.title }) - assertFalse(loaded.isAsking, "rows arrived and the screen is still looking") - } finally { - // The timer would otherwise run on for ten seconds after the test. - viewModel.viewModelScope.cancel() - } - } - - @Test - fun `a schema this device does not hold is an error rather than an empty queue`() { - val chatRepository = object : ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY { - override suspend fun getChatRoomByIdentifier(id: HexKey): LocalChatRoom? = localChatRoom - override suspend fun groupCuratedSchemas(chatRoomId: String): List = emptyList() - } - - val viewModel = CuratedSuggestionListViewModel( - chatRoomId = chatRoomId, - activeUserPublicKey = ada, - relayHint = null, - identifier = "films", - initialCuratedSuggestionListUIState = CuratedSuggestionListUIState.Loading, - nostrRepository = NostrRepository.NO_OP_NOSTR_REPOSITORY, - chatRepository = chatRepository, - ) - - try { - viewModel.initiate() - - runBlocking { - withTimeout(5_000) { - while (viewModel.curatedSuggestionListUIState == CuratedSuggestionListUIState.Loading) delay(20) - } - } - - assertEquals( - CuratedSuggestionListUIState.Error("Couldn't find that schema"), - viewModel.curatedSuggestionListUIState - ) - } finally { - viewModel.viewModelScope.cancel() - } - } - - private fun row(title: String, createdAt: Long) = CuratedSuggestion( - entry = CuratedEntry( - kind = CuratedSchemaEvent.SUGGESTION_KIND, - id = createdAt.toString().padStart(64, 'e'), - pubKey = ada, - createdAt = createdAt, - identifier = title.lowercase().replace(' ', '-'), - title = title, - values = mapOf("title" to listOf(title)), - ), - event = NostrEvent( - id = createdAt.toString().padStart(64, 'e'), - pubKey = ada, - kind = CuratedSchemaEvent.SUGGESTION_KIND, - tags = emptyArray(), - content = "", - sig = "b".repeat(128), - createdAt = Instant.fromEpochSeconds(createdAt), - ), - suggester = null, - isCurated = false, - ) -} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/EditGroupCuratedSchemaViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/EditGroupCuratedSchemaViewModelJvmTest.kt deleted file mode 100644 index 0e05c5b1..00000000 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/EditGroupCuratedSchemaViewModelJvmTest.kt +++ /dev/null @@ -1,454 +0,0 @@ -package com.machankura.bennu.compose.ui.view.model - -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.extensions.hexToNpubHrp -import com.machankura.bennu.compose.nostr.GroupCuratedSchema -import com.machankura.bennu.compose.nostr.curated.CuratedField -import com.machankura.bennu.compose.nostr.curated.CuratedFieldConfig -import com.machankura.bennu.compose.nostr.curated.CuratedFieldType -import com.machankura.bennu.compose.nostr.curated.CuratedSchema -import com.machankura.bennu.compose.nostr.curated.CuratedSchemaEvent -import com.machankura.bennu.compose.nostr.curated.CuratedSchemaProblem -import com.machankura.bennu.compose.nostr.curated.CuratedSchemaTemplate -import com.machankura.bennu.compose.nostr.curated.CuratedUnsupportedField -import com.machankura.bennu.compose.nostr.curated.CuratedVisibility -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.ui.view.state.EditGroupCuratedSchemaUIState -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFalse -import kotlin.test.assertNull -import kotlin.test.assertTrue -import kotlin.time.Instant - -/** - * The decisions the schema editor makes that nothing else can check. - * - * **What a new list starts as.** Its template's fields and rules -- the two - * fields every list has, when no shape was chosen -- and the group's own relays, - * so that what the member sees is what the group will sign rather than what - * `CuratedSchema.normalized` will quietly add. - * - * **What cannot be taken away.** A field writing to `d` or `title` cannot be - * removed, because the event would only grow it back -- so the editor has to - * refuse rather than let a member believe they removed it. - * - * **What counts as a change.** The button proposes only when the schema differs - * from the one the group signed, and getting that wrong is quiet in both - * directions: too eager and every visit re-dates a decision the group did not - * make; too shy and an edit is dropped on a screen that said it had been sent. - */ -class EditGroupCuratedSchemaViewModelJvmTest { - private val chatRoomId = "d4c3b2a1".repeat(8) - - private val films = CuratedSchema( - identifier = "films", - title = "Film suggestion", - name = "Films worth translating", - description = "Films the group would subtitle.", - visibility = CuratedVisibility.Closed, - fields = listOf( - CuratedField.IDENTIFIER, - CuratedField.TITLE, - CuratedField("watchUrl", CuratedFieldType.Url, isRequired = false, config = CuratedFieldConfig(tag = "r", marker = "watch")), - CuratedField("imdbUrl", CuratedFieldType.Url, isRequired = false, config = CuratedFieldConfig(tag = "r", marker = "imdb")), - ), - requireAny = listOf(listOf("watchUrl", "imdbUrl")), - suggesters = listOf("e".repeat(64)), - relays = listOf("wss://relay.one.example"), - ) - - private fun viewModel(identifier: String? = null, template: String? = null) = EditGroupCuratedSchemaViewModel( - chatRoomId = chatRoomId, - activeUserPublicKey = "a".repeat(64), - relayHint = null, - identifier = identifier, - template = template, - initialEditGroupCuratedSchemaUIState = EditGroupCuratedSchemaUIState.Loading, - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, - ) - - private val localChatRoom = LocalChatRoom( - chatRoom = ChatRoom( - id = chatRoomId, - userPublicKey = "a".repeat(64), - subject = "Translation room", - description = null, - initialGiftWrapPayloadId = "sdfaer", - mlsGroupState = "state" - ) - ) - - /** The schema as the group signed it. Not verified here: the editor does not. */ - private fun existing(schema: CuratedSchema = films) = GroupCuratedSchema( - signedEvent = GroupSignedEvent( - id = "c".repeat(64), - chatRoomId = chatRoomId, - publicKey = chatRoomId, - kind = CuratedSchemaEvent.KIND, - tags = CuratedSchemaEvent.template(schema, createdAt = 1_700_000_000).tags, - content = schema.description, - signature = "f".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_000), - ), - schema = schema.normalized(), - ) - - private fun newSchema(defaultRelays: List = listOf("wss://relay.one.example")) = - EditGroupCuratedSchemaUIState.Loaded( - localChatRoom = localChatRoom, - existing = null, - defaultRelays = defaultRelays, - canSign = true, - ) - - private fun editing(schema: CuratedSchema = films) = EditGroupCuratedSchemaUIState.Loaded( - localChatRoom = localChatRoom, - existing = existing(schema), - defaultRelays = listOf("wss://relay.two.example"), - canSign = true, - ) - - @Test - fun `a new schema starts with the two fields every list has and the group's relays`() { - val viewModel = viewModel() - viewModel.seedWorkingCopy(newSchema()) - - assertEquals(listOf("d", "title"), viewModel.fields.map { it.tag() }) - assertTrue(viewModel.fields.all { it.isRequired }) - assertEquals(CuratedVisibility.Public, viewModel.visibility) - assertEquals(listOf("wss://relay.one.example"), viewModel.relays) - assertEquals(emptyList(), viewModel.requireAny) - assertEquals(emptyList(), viewModel.suggesters) - } - - @Test - fun `a new schema from a template starts at the template's fields and rules`() { - val viewModel = viewModel(template = CuratedSchemaTemplate.Links.key) - viewModel.seedWorkingCopy(newSchema()) - - assertEquals(CuratedSchemaTemplate.Links.fields, viewModel.fields.toList()) - assertEquals(CuratedSchemaTemplate.Links.requireAny, viewModel.requireAny.toList()) - // The identifier is the template's: derived, with its rule in the hint. - assertTrue(viewModel.isMandatory(viewModel.fields[0])) - assertTrue(viewModel.fields[0].config.hint.orEmpty().endsWith("[rule:link-or-title]")) - // What the template does not decide is as any new list's. - assertEquals(CuratedVisibility.Public, viewModel.visibility) - assertEquals(listOf("wss://relay.one.example"), viewModel.relays) - assertEquals(emptyList(), viewModel.suggesters) - - // And the draft it makes is a usable schema as it stands, so a member - // who fills in the identity and presses the button proposes the shape. - val draft = viewModel.draft("links", "Link suggestion", "Links", "Things worth a look.", "", "") - assertTrue(draft.isUsable()) - assertEquals(listOf(listOf("link", "body")), draft.requireAny) - } - - @Test - fun `a template key this build does not know starts at the two fields every list has`() { - val viewModel = viewModel(template = "gallery") - viewModel.seedWorkingCopy(newSchema()) - - assertEquals(CuratedSchemaTemplate.Custom.fields, viewModel.fields.toList()) - assertEquals(listOf("d", "title"), viewModel.fields.map { it.tag() }) - assertEquals(emptyList(), viewModel.requireAny) - } - - @Test - fun `an existing schema starts as itself, and its relays are its own`() { - // A template beside an identifier is ignored: an edit starts from the - // schema the group signed, whatever shape the route also names. - val viewModel = viewModel("films", template = CuratedSchemaTemplate.Catalogue.key) - viewModel.seedWorkingCopy(editing()) - - assertEquals(films.fields, viewModel.fields.toList()) - assertEquals(films.requireAny, viewModel.requireAny.toList()) - assertEquals(films.suggesters, viewModel.suggesters.toList()) - assertEquals(CuratedVisibility.Closed, viewModel.visibility) - // Not the defaults the state also carries: those are for a new list. - assertEquals(listOf("wss://relay.one.example"), viewModel.relays) - } - - @Test - fun `seeding again leaves an edit alone`() { - // The effect that seeds is keyed on a state the view model can re-emit, so - // running twice has to be harmless -- otherwise a reload halfway through an - // edit throws the edit away. - val viewModel = viewModel("films") - viewModel.seedWorkingCopy(editing()) - assertTrue(viewModel.addRelay("wss://relay.two.example")) - - viewModel.seedWorkingCopy(editing()) - - // The added relay is normalized, which is how the group's other relay - // lists are written; the signed one is kept as the group wrote it. - assertEquals(listOf("wss://relay.one.example", "wss://relay.two.example/"), viewModel.relays) - } - - @Test - fun `a relay already signed into the schema is a duplicate with or without the slash`() { - val viewModel = viewModel("films") - viewModel.seedWorkingCopy(editing()) - - assertFalse(viewModel.addRelay("wss://relay.one.example")) - assertFalse(viewModel.addRelay("wss://relay.one.example/")) - assertEquals(EditGroupCuratedSchemaViewModel.AddRelayFailure.AlreadyListed, viewModel.addRelayFailure) - assertEquals(listOf("wss://relay.one.example"), viewModel.relays) - } - - @Test - fun `a mandatory field cannot be removed and another one can`() { - val viewModel = viewModel("films") - viewModel.seedWorkingCopy(editing()) - - assertTrue(viewModel.isMandatory(viewModel.fields[0])) - assertTrue(viewModel.isMandatory(viewModel.fields[1])) - assertFalse(viewModel.isMandatory(viewModel.fields[2])) - - viewModel.removeField(0) - viewModel.removeField(1) - assertEquals(listOf("identifier", "title", "watchUrl", "imdbUrl"), viewModel.fields.map { it.name }) - - // A field that goes takes its place in the rules with it: a rule naming a - // field that no longer exists would silently never be satisfied. - viewModel.removeField(2) - assertEquals(listOf("identifier", "title", "imdbUrl"), viewModel.fields.map { it.name }) - assertEquals(listOf(listOf("imdbUrl")), viewModel.requireAny.toList()) - } - - @Test - fun `renaming a field follows through to the rules that named it`() { - val viewModel = viewModel("films") - viewModel.seedWorkingCopy(editing()) - - viewModel.startEditingField(2) - assertNull(viewModel.commitField(viewModel.fields[2].copy(name = "watch"))) - - assertEquals(listOf("identifier", "title", "watch", "imdbUrl"), viewModel.fields.map { it.name }) - assertEquals(listOf(listOf("watch", "imdbUrl")), viewModel.requireAny.toList()) - assertNull(viewModel.editingField, "the sheet stayed open after a commit") - } - - @Test - fun `a field name is one word and belongs to one field`() { - val viewModel = viewModel("films") - viewModel.seedWorkingCopy(editing()) - - viewModel.startAddingField() - val draft = viewModel.editingField!!.field - - assertEquals(EditGroupCuratedSchemaViewModel.FieldProblem.NameMissing, viewModel.commitField(draft.copy(name = " "))) - assertEquals(EditGroupCuratedSchemaViewModel.FieldProblem.NameHasSpaces, viewModel.commitField(draft.copy(name = "watch url"))) - assertEquals(EditGroupCuratedSchemaViewModel.FieldProblem.NameTaken, viewModel.commitField(draft.copy(name = "imdbUrl"))) - assertEquals(4, viewModel.fields.size, "a refused field went in anyway") - - assertNull(viewModel.commitField(draft.copy(name = " year "))) - assertEquals("year", viewModel.fields.last().name) - - // Editing a field back to its own name is not taking it from anybody. - viewModel.startEditingField(4) - assertNull(viewModel.commitField(viewModel.fields[4].copy(label = "Year"))) - } - - @Test - fun `a rule with fewer than two names is dropped from the draft rather than refused`() { - val viewModel = viewModel() - viewModel.seedWorkingCopy(newSchema()) - - viewModel.addRequireAnyGroup() - viewModel.toggleRequireAny(0, "title") - viewModel.addRequireAnyGroup() - - val draft = viewModel.draft("d", "t", "n", "desc", "", "") - - assertEquals(2, viewModel.requireAny.size, "the editor lost a rule being built") - assertEquals(emptyList(), draft.requireAny) - } - - @Test - fun `a pubkey is an npub or hex and nothing else`() { - val hex = "eebb74ab6bfb8485722ab1d4acee856eee96f17a9e1721f9c7cc63376c40b860" - // Encoded rather than typed, so the checksum is right by construction. - val npub = hex.hexToNpubHrp() - - assertEquals(hex, EditGroupCuratedSchemaViewModel.pubkeyOrNull(hex)) - assertEquals(hex, EditGroupCuratedSchemaViewModel.pubkeyOrNull(" ${hex.uppercase()} ")) - assertEquals(hex, EditGroupCuratedSchemaViewModel.pubkeyOrNull(npub)) - assertEquals(hex, EditGroupCuratedSchemaViewModel.pubkeyOrNull("nostr:$npub")) - - listOf("", "npub1notanpub", hex.dropLast(1), "group@example.com", "nsec1" + npub.drop(5)).forEach { - assertNull(EditGroupCuratedSchemaViewModel.pubkeyOrNull(it), "\"$it\" was taken for a pubkey") - } - - val viewModel = viewModel() - viewModel.seedWorkingCopy(newSchema()) - assertFalse(viewModel.addSuggester("group@example.com")) - assertEquals(EditGroupCuratedSchemaViewModel.AddSuggesterFailure.NotAPubkey, viewModel.addSuggesterFailure) - assertTrue(viewModel.addSuggester(npub)) - assertFalse(viewModel.addSuggester(hex)) - assertEquals(EditGroupCuratedSchemaViewModel.AddSuggesterFailure.AlreadyListed, viewModel.addSuggesterFailure) - assertEquals(listOf(hex), viewModel.suggesters) - } - - @Test - fun `a url that is not a relay is refused and named`() { - val viewModel = viewModel() - viewModel.seedWorkingCopy(newSchema(defaultRelays = emptyList())) - - assertFalse(viewModel.addRelay("http://relay.one.example")) - assertEquals(EditGroupCuratedSchemaViewModel.AddRelayFailure.NotARelay, viewModel.addRelayFailure) - // The NIP allows ws://; what the group signs is held to the app's rule. - assertFalse(viewModel.addRelay("ws://relay.one.example")) - - assertTrue(viewModel.addRelay("wss://relay.one.example")) - assertFalse(viewModel.addRelay("wss://relay.one.example")) - assertEquals(EditGroupCuratedSchemaViewModel.AddRelayFailure.AlreadyListed, viewModel.addRelayFailure) - } - - @Test - fun `opening a schema and pressing the button proposes nothing`() { - // The case that has to be silent. A member opening the editor, reading it - // and pressing the button must not spend a quorum on an identical schema. - val viewModel = viewModel("films") - viewModel.seedWorkingCopy(editing()) - - var outcome = "" - viewModel.proposeSchema( - localChatRoom = localChatRoom, - existing = existing(), - identifier = films.identifier, - title = films.title, - name = films.name, - description = films.description, - picture = "", - domain = "", - onSuccess = { outcome = "proposed" }, - onInvalid = { outcome = "invalid" }, - onNothingToPropose = { outcome = "nothing" }, - onFailure = { outcome = "failed" }, - ) - - assertEquals("nothing", outcome) - assertEquals(emptyList(), viewModel.problems) - } - - @Test - fun `a field of a type this build cannot show survives an edit, and is not an edit by itself`() { - // A schema another client wrote may use a type this build does not know. - // The editor cannot show it, and must neither sign it away nor mistake - // its own blind spot for a change the member made. - val stars = listOf("field", "rating", "stars", "required", "5", "Rating", "{\"max\":5}") - val withStars = films.copy( - unsupportedFields = listOf(CuratedUnsupportedField("rating", "stars", isRequired = true, label = "Rating", tag = stars)) - ) - val viewModel = viewModel("films") - viewModel.seedWorkingCopy(editing(withStars)) - - var outcome = "" - viewModel.proposeSchema( - localChatRoom = localChatRoom, - existing = existing(withStars), - identifier = films.identifier, - title = films.title, - name = films.name, - description = films.description, - picture = "", - domain = "", - onSuccess = { outcome = "proposed" }, - onInvalid = { outcome = "invalid" }, - onNothingToPropose = { outcome = "nothing" }, - onFailure = { outcome = "failed" }, - ) - assertEquals("nothing", outcome) - - // And what an edit would sign carries the tag as it came. - val draft = viewModel.draft(films.identifier, films.title, films.name, films.description, picture = "", domain = "") - assertEquals(stars, GroupCuratedSchema.template(draft).tags.first { it[0] == "field" && it[1] == "rating" }.toList()) - } - - @Test - fun `an edit keeps the identifier whatever the field says`() { - val viewModel = viewModel("films") - viewModel.seedWorkingCopy(editing()) - - var outcome = "" - viewModel.proposeSchema( - localChatRoom = localChatRoom, - existing = existing(), - // A different identifier would be a different list, not an edit. - identifier = "books", - title = films.title, - name = films.name, - description = films.description, - picture = "", - domain = "", - onSuccess = { outcome = "proposed" }, - onInvalid = { outcome = "invalid" }, - onNothingToPropose = { outcome = "nothing" }, - onFailure = { outcome = "failed" }, - ) - - assertEquals("nothing", outcome, "a changed identifier was taken as an edit") - } - - @Test - fun `a schema a reader would refuse is refused here, and the reasons are kept`() { - val viewModel = viewModel() - viewModel.seedWorkingCopy(newSchema()) - - var outcome = "" - viewModel.proposeSchema( - localChatRoom = localChatRoom, - existing = null, - identifier = " ", - title = "t".repeat(201), - name = "Films", - description = "", - picture = "http://example.com/x.png", - domain = "not a domain", - onSuccess = { outcome = "proposed" }, - onInvalid = { outcome = "invalid" }, - onNothingToPropose = { outcome = "nothing" }, - onFailure = { outcome = "failed" }, - ) - - assertEquals("invalid", outcome) - assertEquals( - listOf( - CuratedSchemaProblem.IdentifierMissing, - CuratedSchemaProblem.TitleTooLong, - CuratedSchemaProblem.DescriptionMissing, - CuratedSchemaProblem.PictureNotHttps, - CuratedSchemaProblem.DomainInvalid, - ), - viewModel.problems, - ) - } - - @Test - fun `the draft trims what was typed and normalizes the domain`() { - val viewModel = viewModel() - viewModel.seedWorkingCopy(newSchema()) - - val draft = viewModel.draft( - identifier = " films ", - title = " Film suggestion ", - name = " Films ", - description = " Films. ", - picture = " ", - domain = " https://Example.COM/ ", - ) - - assertEquals("films", draft.identifier) - assertEquals("Film suggestion", draft.title) - assertEquals("Films", draft.name) - assertEquals("Films.", draft.description) - assertNull(draft.picture) - assertEquals("example.com", draft.domain) - assertTrue(draft.isUsable()) - } -} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupCuratedEntriesViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupCuratedEntriesViewModelJvmTest.kt deleted file mode 100644 index 26c05e14..00000000 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupCuratedEntriesViewModelJvmTest.kt +++ /dev/null @@ -1,309 +0,0 @@ -package com.machankura.bennu.compose.ui.view.model - -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer -import kotlinx.coroutines.CompletableDeferred -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.flowOf -import kotlinx.coroutines.runBlocking -import kotlinx.coroutines.test.UnconfinedTestDispatcher -import kotlinx.coroutines.test.resetMain -import kotlinx.coroutines.test.setMain -import kotlinx.coroutines.withTimeout -import com.machankura.bennu.compose.database.model.NostrEvent -import com.machankura.bennu.compose.exceptions.NostrPublishException -import com.machankura.bennu.compose.network.dto.RelayDTO -import com.machankura.bennu.compose.network.relays.EventPublishTransport -import com.machankura.bennu.compose.network.relays.NostrPublishResult -import com.machankura.bennu.compose.network.sockets.NostrIncomingMessage -import com.machankura.bennu.compose.nostr.GroupCuratedEntry -import com.machankura.bennu.compose.nostr.GroupRelay -import com.machankura.bennu.compose.nostr.GroupRelayList -import com.machankura.bennu.compose.nostr.GroupRelaySet -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures -import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.chatRoomId -import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.entry -import com.machankura.bennu.compose.ui.view.model.BroadcastGroupSignedEventViewModel.RelayOutcome -import com.machankura.bennu.compose.ui.view.model.GroupCuratedEntriesViewModel.BroadcastAllProgress -import com.machankura.bennu.compose.ui.view.model.GroupCuratedEntriesViewModel.EntryBroadcast -import com.machankura.bennu.compose.ui.view.state.GroupCuratedEntriesUIState -import kotlin.test.AfterTest -import kotlin.test.BeforeTest -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFalse -import kotlin.test.assertIs -import kotlin.test.assertNull -import kotlin.test.assertTrue - -/** - * What "Broadcast all" decides that nothing else can check. - * - * **Where each entry goes.** The same relays its own broadcast screen would - * have filled in -- the group's General list plus the list the entry is in, - * minus what the group has blocked -- because the button is the member - * trusting that seed rather than editing it, and a rule that sent to - * anywhere else would make the two buttons disagree. - * - * **One after another, in the order shown.** The transport is asked once per - * entry, and the next is not asked until the last has settled. - * - * **What the answers become.** The count under each card and the sum above - * them, with a relay that refused named against its reason, and an entry with - * nowhere to go marked so rather than sent to nobody. - */ -@OptIn(ExperimentalCoroutinesApi::class) -class GroupCuratedEntriesViewModelJvmTest { - - private val one = RelayUrlNormalizer.normalize("wss://relay.one.example") - private val two = RelayUrlNormalizer.normalize("wss://relay.two.example") - - /** - * Answers every event with [answers] and remembers each send in the order - * it was asked for. Holds every answer back until [gate] is completed, - * where a test hands one in, so a batch can be caught while it is out; - * [arrived] says when the first send has reached it. - */ - private class FakeTransport( - private val gate: CompletableDeferred? = null, - private val answers: (NostrEvent) -> List, - ) : EventPublishTransport { - val sends = mutableListOf>>() - - val arrived = CompletableDeferred() - - override suspend fun publishEvent( - nostrEvent: NostrEvent, - relays: Set - ): Flow { - sends += nostrEvent to relays - arrived.complete(Unit) - gate?.await() - return flowOf(*answers(nostrEvent).toTypedArray()) - } - } - - @BeforeTest - fun setUp() { - Dispatchers.setMain(UnconfinedTestDispatcher()) - } - - @AfterTest - fun tearDown() { - Dispatchers.resetMain() - } - - private val newest = entry("The Rise and Rise of Bitcoin", 1_700_000_900) - private val oldest = entry("Magic Money", 1_700_000_300, suggestedBy = null) - - /** - * A General list of [two] agreed, so each entry has one relay of the - * group's and one of its list's ([one], which the fixture's schema names), - * plus whatever [blocked] takes away. - */ - private fun relayLists(blocked: List = emptyList()): List = - GroupRelayList.allAmong(emptyList(), chatRoomId).map { list -> - when (list.set) { - GroupRelaySet.General -> GroupRelayList( - set = list.set, - signedEvent = GroupSignedWorkFixtures.relaySignedEvent(list.set), - relays = listOf(GroupRelay(two)), - ) - GroupRelaySet.Blocked -> GroupRelayList( - set = list.set, - signedEvent = GroupSignedWorkFixtures.relaySignedEvent(list.set), - relays = blocked.map { GroupRelay(it) }, - ) - else -> list - } - } - - private fun viewModel( - transport: EventPublishTransport, - entries: List = listOf(newest, oldest), - relayLists: List = relayLists(), - ) = GroupCuratedEntriesViewModel( - chatRoomId = chatRoomId, - initialGroupCuratedEntriesUIState = GroupCuratedEntriesUIState.Loaded( - localChatRoom = GroupSignedWorkFixtures.localChatRoom(), - groupCuratedEntries = entries, - relayLists = relayLists, - ), - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - publishTransport = transport, - ) - - private fun ok(relay: NormalizedRelayUrl, event: NostrEvent) = NostrPublishResult( - result = NostrIncomingMessage.OkMessage(eventId = event.id, success = true), - relayUrl = relay.url, - ) - - private fun rejected(relay: NormalizedRelayUrl, event: NostrEvent, reason: String) = NostrPublishResult( - result = NostrIncomingMessage.OkMessage(eventId = event.id, success = false, message = reason), - error = NostrPublishException(message = reason), - relayUrl = relay.url, - ) - - private fun GroupCuratedEntriesViewModel.broadcastAllAndWait() { - val job = broadcastAll() - runBlocking { withTimeout(5_000) { job!!.join() } } - } - - // -- where each entry goes ---------------------------------------------------- - - @Test - fun `each entry goes where its own broadcast would, one after another, in the order shown`() { - val transport = FakeTransport { event -> listOf(ok(two, event), ok(one, event)) } - val viewModel = viewModel(transport) - - viewModel.broadcastAllAndWait() - - // The newest first, as the screen lists them, and nothing twice. - assertEquals( - listOf(newest.signedEvent.id, oldest.signedEvent.id), - transport.sends.map { it.first.id }, - ) - - // The group's General relay and the list's own, asked as write relays - // -- the pool would otherwise read from them too -- and what went was - // the event as the group signed it. - transport.sends.forEach { (event, relays) -> - assertEquals( - setOf(two, one).map { RelayDTO(url = it.url, read = false, write = true) }.toSet(), - relays, - ) - assertEquals("f".repeat(128), event.sig) - assertEquals(chatRoomId, event.pubKey) - } - } - - @Test - fun `a relay the group has blocked is left out, and an entry with nowhere to go is marked so`() { - val transport = FakeTransport { event -> listOf(ok(two, event)) } - - // Everything the seed would name is blocked, so nothing is asked. - val nowhere = viewModel(transport, relayLists = relayLists(blocked = listOf(one, two))) - nowhere.broadcastAllAndWait() - - assertTrue(transport.sends.isEmpty(), "an entry with nowhere to go was sent somewhere") - assertEquals(EntryBroadcast.NoRelays, nowhere.entryBroadcasts[newest.signedEvent.id]) - assertEquals(EntryBroadcast.NoRelays, nowhere.entryBroadcasts[oldest.signedEvent.id]) - assertEquals( - BroadcastAllProgress.Done(acceptedEverywhere = 0, total = 2), - nowhere.broadcastAllProgress, - ) - - // Only the list's relay blocked: the group's own is still asked. - val partly = viewModel(transport, relayLists = relayLists(blocked = listOf(one))) - partly.broadcastAllAndWait() - - assertEquals(2, transport.sends.size) - transport.sends.forEach { (_, relays) -> - assertEquals(setOf(two.url), relays.map { it.url }.toSet()) - } - } - - // -- what the answers become --------------------------------------------------- - - @Test - fun `each entry's count sits under it, a refusal is named with its reason, and the sum counts only the entries accepted everywhere`() { - val transport = FakeTransport { event -> - if (event.id == newest.signedEvent.id) { - listOf(ok(two, event), ok(one, event)) - } else { - listOf(ok(two, event), rejected(one, event, "blocked: not on the allow list")) - } - } - val viewModel = viewModel(transport) - - viewModel.broadcastAllAndWait() - - val first = assertIs(viewModel.entryBroadcasts[newest.signedEvent.id]) - assertEquals(2, first.accepted) - assertEquals(2, first.asked) - assertTrue(first.isAcceptedEverywhere) - assertEquals(emptyList(), first.refusals) - - val second = assertIs(viewModel.entryBroadcasts[oldest.signedEvent.id]) - assertEquals(1, second.accepted) - assertEquals(2, second.asked) - assertFalse(second.isAcceptedEverywhere) - assertEquals( - listOf(one to RelayOutcome.Rejected("blocked: not on the allow list")), - second.refusals, - ) - - assertEquals( - BroadcastAllProgress.Done(acceptedEverywhere = 1, total = 2), - viewModel.broadcastAllProgress, - ) - assertFalse(viewModel.isActionPending.value) - } - - @Test - fun `a relay that never answers counts against the entry, which is not the same as refused`() { - // The pool answers for one relay and then the flow ends, which is what - // a send that ran out of time looks like from here. - val transport = FakeTransport { event -> listOf(ok(two, event)) } - val viewModel = viewModel(transport, entries = listOf(newest)) - - viewModel.broadcastAllAndWait() - - val sent = assertIs(viewModel.entryBroadcasts[newest.signedEvent.id]) - assertEquals(listOf(one to RelayOutcome.NoAnswer), sent.refusals) - assertEquals( - BroadcastAllProgress.Done(acceptedEverywhere = 0, total = 1), - viewModel.broadcastAllProgress, - ) - } - - // -- when nothing is sent ---------------------------------------------------------- - - @Test - fun `the next entry waits for the last to settle, and a second press while one is out is refused`() { - val gate = CompletableDeferred() - val transport = FakeTransport(gate) { event -> listOf(ok(two, event), ok(one, event)) } - val viewModel = viewModel(transport) - - // The first press is held at the transport, so the second meets the - // guard however fast the dispatcher is. - val first = viewModel.broadcastAll() - val second = viewModel.broadcastAll() - assertNull(second) - assertTrue(viewModel.isActionPending.value) - - // One entry out and held; the other has not been asked for, and the - // held one is marked as out while the rest are marked as nothing. - runBlocking { withTimeout(5_000) { transport.arrived.await() } } - assertEquals(listOf(newest.signedEvent.id), transport.sends.map { it.first.id }) - assertEquals(EntryBroadcast.Sending, viewModel.entryBroadcasts[newest.signedEvent.id]) - assertNull(viewModel.entryBroadcasts[oldest.signedEvent.id]) - assertEquals(BroadcastAllProgress.Sending(entry = 1, total = 2), viewModel.broadcastAllProgress) - - gate.complete(Unit) - runBlocking { withTimeout(5_000) { first!!.join() } } - - assertEquals(2, transport.sends.size) - assertFalse(viewModel.isActionPending.value) - } - - @Test - fun `nothing is sent from a screen with no entries, or one that has not loaded`() { - val transport = FakeTransport { event -> listOf(ok(two, event)) } - - assertNull(viewModel(transport, entries = emptyList()).broadcastAll()) - - val loading = GroupCuratedEntriesViewModel( - chatRoomId = chatRoomId, - initialGroupCuratedEntriesUIState = GroupCuratedEntriesUIState.Loading, - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - publishTransport = transport, - ) - assertNull(loading.broadcastAll()) - - assertTrue(transport.sends.isEmpty()) - } -}