From cce0bdcd9cff9d172b73441015dfa5f35fa31289 Mon Sep 17 00:00:00 2001 From: bchanot Date: Sat, 10 Oct 2026 11:06:53 +0200 Subject: [PATCH 01/16] test(app): freeze golden v2 PDFs exported by the current pipeline (step 5.0, synthetic reports) --- apps/app/tests/fixtures/README.md | 1 + apps/app/tests/fixtures/report-v2.full.pdf | Bin 0 -> 8960 bytes apps/app/tests/fixtures/report-v2.minimal.pdf | Bin 0 -> 2360 bytes 3 files changed, 1 insertion(+) create mode 100644 apps/app/tests/fixtures/report-v2.full.pdf create mode 100644 apps/app/tests/fixtures/report-v2.minimal.pdf diff --git a/apps/app/tests/fixtures/README.md b/apps/app/tests/fixtures/README.md index 61f198d5..d7fc8c97 100644 --- a/apps/app/tests/fixtures/README.md +++ b/apps/app/tests/fixtures/README.md @@ -7,6 +7,7 @@ the Report v2 document as the current application produces it. |---|---| | `report-v2.full.json` | One report exercising every zone kind the editor can produce: plain hinge point, bilateral joint with both sides, spine zone with vertebrae, detail-popup zone, catalog findings (with and without vet referral and side), free text, severity, comment, conclusion, recommendations, dated next appointment. `boneId` values are the real `data-anno-id` of `public/species/equine/*.svg`; `zoneId`/`path` values exist in `pathologies.json`. | | `report-v2.minimal.json` | Smallest valid v2 report (no observations). | +| `report-v2.full.pdf`, `report-v2.minimal.pdf` | The two reports exported by the v2 pipeline (commit 199e328, Step 5.0, rasteriser stubbed to a 1×1 PNG, no logos): the archive-like PDFs the v3 importer must read and migrate. Synthetic data only. | Do not edit these files to make a test pass: they are the behavioural oracle for the Report v2 → v3 adapter and for PDF regression. Add a new fixture instead. diff --git a/apps/app/tests/fixtures/report-v2.full.pdf b/apps/app/tests/fixtures/report-v2.full.pdf new file mode 100644 index 0000000000000000000000000000000000000000..fd45984fdc91a0df83dc1eece026326b6dde6247 GIT binary patch literal 8960 zcmdU!bx>UGwxRq*;wSLcL(2$kq;NcVmFa+O!001FsZfdv{ z6d)=J;F56!=pTQ?LPwhDN>sEZ=xe@aF!dzscA!LfM zzqeOmBw*X@qX-4zg#jT+$?f~+O{5Z{em^%?4&&iV^Q|{G+Y4FR99n%U`^V*H*Kq~r zcM~fQ{IuSebIIQNjQg{#4$&ps7#mdYI7Ep!yH~%7oP|OQI{ArM;0^V>6s8mS%ElSpmMA9V)Ha za0tqN<4r@A1Qoj(e~YEE99$f%RQ>1)X+yrG4G+)f!dvGbSf7SopB8il-o*Hi>gVdp zvJfjf*2)eBIgA91v}lGfvBlTLSs;hz{O~0XSAaL2li!kn0r=sjyBWbU@1g`jWl9)& z;t4EFl1|SjaBCDzZ$3RqW;!?XkAJp*w{LbA<=M6y@{IP@woNh#opXG+=pb#@adZDE zrg$x8cGwr3n?{2`D>OGtCyB;>1c*v;5>sp?q$r* z{#&Gg_5u>e=e?yiEmbVT8!xfpzP+W8hAh{X_5F=X^4%-Po7eoH>>9po_V|xjY3=TZ z7h?tD;^juH1rsTKF4zOoPJQ?q(si;V#k+FEV%SH_FBQd~7riUIaESXDy;o5&5O{`2 zRQ%`8jJCcBU4ka$6vHEytS`BgNbDYGwn!32T)A%LJPz%5yVyFp@#PAbZ@D^h z>V3fw1~6>Dxw*6EV`8R!YPN()NWG!8I>yp*z04=HNL0+UHc^wCU*Pq=*sc%a<_7FA-%57fOx39uP;yC&@VvAC!#4ceY z04Os7cZ>uEQu*n|2r}x&Xu=EA76~)_z_cMpVIr!iq5YDd`YVssyuf4gu(MOE7EvC`K&2z@Y}29BtE z1X5Xrnh|}>^nlyAFNcD@5*cs@y@}HOd|7cu8<2uO*N2o6lxI>-zg@pXQx{!})8WyK$0GAkkLgfKxd& zTjxeWUoj=vGcumGx9{j2#m&)=tdAG3&V!{z$GuSCv$CRDrUE3tmDwv(kEBYRBz9c( zlx4w_4%%PESL8Vt50AI?6sB5uC+zGMUaYs)8paT1;lv`;`s{sB2l1%XBny=-^Z`I& zx$G?YHn}jhn#__J;+nk7T<@WG8^D@uKLIhOH}mGp#I6uErNJgD(s6tN7m~-}?PX0S za{M0cfytwuY*Nt2rq^ZGChXEP(QR+1gAh-l5S?$XM5w3^2mDx5xw>b<{1F`?QP0f1pPe+TIO>Nj=)pg-|f$J+@^ z&1Il&1qEBX0l2i?t=#_hi;|6yL=i&KN`Tw$ga0B`OY1b@0B#cgu!2f+kx*h$fhiS91wBm>tj$%vYCGIi7zHOQu z&lqaR(&mIvTQ|&(CvyG(g7hzWk=5jPa3Ekx@!FUD6~pAO`1pm4Ln^AffXm(S=IbvD zy)#M zfK%g7S0xz&3-Jq^&)U%2CJgp)mZEJ+S(1O$MP{nZ(qJFWl&ZrFL9zVW0u?Ra+*8Z6 z&(6wc*bCpantd4&x4w@2ga|S}stxI-Yl#>YO3V{LeXttOgaD0VZeiN$vGpyF8jB=HGpx{ZZRCh^MY72o<> z!Ign+&aQx#UhmYWv#fj6S=y^4#!zsFoq|YwQ3& z7xU0NP%UdqeC5-vueYGQW;pXuq6 z7yPaAC44I?aS@$d7n&ddpE)^5U6c+J?8l5{DGkZC0?>MYywN6p59+ zp#6`S9hNPO4YroAL3Y(s**rZ#&m#H5U-@a>@VtB258*r>ahCV`Jj09eJus2269Y5* z<$Tif+_u3hMFfB|!>OWDH;NfOBt+UJ_9MM-8T*!-_#2IBIe(Uw7l{T4e}?_&K_z`9 zF6=?J*2-M7A|l*&IjkQ*8;*1~vvXU5Cjtr`x!A7IsxHm5;cN0chg7Xj6RZ4vNqVxV zJiCdOOt~lH);1KclGxPaBG-G`;_0OfKj_tkm84*Z{VXBb57;zUjY+qLq%wqQROPZZ z%hF|{|+er9)kZ1p~&~A^8XbSL7;yoZI+%I94SxGda8e9 zA~|&6cYrE|VwgLJ+R8UszSXHXPaUR9=QwtA+ma*QpQP_W^wfkSZLRICAl&v`+p}i> zTf&Fl1fKl4yVD%sv+;%7JI_0RKhNd{?}os3rx96B<%#d*`|qDAwci$WVO)-i8JlbE zd}=&I6@yA4S zo?ZlWutYVq9jSRSgt-6V%sI zWDMabZ zYYpw))aAxy5S3Ht_{zQn;nawa@)YKHFQ)FzDvw#!#f@Qn*5iMJ$LN}>l zXiM&d6;61E!7kH{_5?J1rYK)c=LI*Bin*pg=mQ-dM2MQ2^b1=oI=ShrS#+Mvmq}T< zV6wHXQu~SU*1*T)TLKEZ@dJ+)@IQS$oP2lc_Ej2hst~sz{HyJg^P@QJQOsrgQ|tW4 zLk8-0Yqmb3GLq-HilRqys^=Y9{H|An0U zJxl(dxC0P3=zp61)Z(8g5VVd~q`T(xFPzPCt3v z)R@@@b*3W4#GY5|oR#XIRyB*cL6ZN0xq9D|>xJ8P&-Y8M0q(BXE5C+u4Of#&z4x6b zS1RK2C2q!6(EVITr|yTpt}0*FRarC!OQd1_j!hJu^O;Q^E@%6B#Kpo&8cfJ-v?-p+ z56kZ(&la5@tK=Jm%g!!)b()K`?Q){-Q&m&u{SrI<(%Q7KS#Yty$L>@u*;2YI28U1K zj`-DY9^QoHiSaJd_^!nen`MER3o;dl?m0)%RIS6HDL0k*Hr>!*cBav3eQ=KQ*M-Mo zr0aU7=9hL>*)!x7|kqR5O zmz?sm%I~aIY8{vhSVoit5d{5PJX1MV6`UpO9INxRw%wt#i`7p?WGvaNOR+3Jps%Vr zAlzk?NqL;nA0ZQ99ag)mcJb8DSH$jc+2-!1TfHLf+P0b`f!t?8-Le-dde(TDLYNc5MT7HVnc4^R999rczYd(n1cY!ubwl=jMkF{ z)qzu%m%Wg4*9RNSCoyDPKT@aUxAmYcgLvUM2aARk;`UM}p9^VgU~9gmuDvRf7h47J z!=~ehr}hAuN`at&BnRJIY(xr}u~zr=y>I!u5cKDOT*H|($SUrw~N+> z_<*T_+HMq_H_Tas<{+D7K zbbpCId+j>CVc5I?LEAM8W|omf-J5A=lg){a5n3z@qDtK7gqM<0idOFP2PChb>M>9qlv#u-;@3UFEJH?U6%j7ZvQ;)FG ztX|OrXl;Xp`xb@c)9I6^okQ9ePS=jql9u6_^!-KX2pXr?(2=^FA?FCZ&g>iX(IcI2 zyxH-?>6BOlxC!5t*|tNHE>yKSX)eW};!3xhx?jF8m6z(5gysO|F1SgCZqTufpbxAu z>VdYJ1l-NZt@_s$_yJ<7H~O!>AqnW;wB%boc{kZ1G=rbR8w6u0b1bKmSeYW9fW&K~ z5q!0yewgqfr}|fhOLOYD;a6dLow-=^v$Mq#zlW^-Sp0E=R04Gt8x#89Xt!K7AVke7 zvZ^h}rtYqn>_5?wy@EV>4N979oTer_KXzUE@$&H8M0}bGYd9n2{ZrNr6%`~8%;pML zYI5PVw@rI4qm4rinPLgQ+&2@Rb;CTj6twkmbh;oYJ+t37-q;MQ#e`#G*AONoTNwx4 z5+88xJTu2L0U$!s5kRFn4xQ!QT3uRl0x2xE;>4C;y^?PFr&)V1102xkJ#T+)p$eQa zHv}m26P#Ochz1)n6wi{7?WuKzYGq;@h<;)(dg_mwZuN4t3ZeRxa=S5*(DKj)JL8s; z1m^R+*9lc|P@7W-k5!tDH?OC7WU(jeQD*l%M{BPZ_-tUJbok4vJ)2mvblX|fh|r6U zc2R6T;wJEyxyy#C#l<}_8Osx{@DPljoF;pu(fySgWDTJc8Vxd08J+D;(={7ak#Y6* z%V;U&>>Blg1oLrb9c!gI{o<`=Q0TJIhC}IiAfJ$tgJ}9HvZhNH%=*>8EcRPC8~WTa zNVHUNBvB6X1#q-hwMH7!Jpht9{}H>z{h(IzpD+IR-vHT<=3hNe}L=hS=8u-hVS)0@BGLC+X$&-5^I>p-=oG9bxd1btF2`-n4dfs4FK2~NKGphcSd>pny$pJ4g zI5l!WKB7?xDU%Ob=ww^|K){{xYd*q=Om z@r4*>GqpWA=u*e3AHCz^^)0?tBc8MpV00 zch}=GhWdweCS6N=_7847pGPee?b^E6uumIzWm)m;_=f&^sQ>wq%;h-IvDmqMv&w}$ zc@JdFT>J-b)+z5a?#b%fRHwJZbdM#CakJHK?X=YMQzlDYb;M+gy~>%zuh)Fu`SDX& zJh|pnR<2XvF@d|KFYdqe)x_F9Z|eFQ!lvyY38Z3$pX89Lc@cWf}#3T*lyJ>j!_cU?sc}L}~6Xn=ENznJFg@)J3DGrlG?9EXzl3#22Sj$$eO`0pd)R$2NC9BZBYNB8 zf#wzRKpAE}BW#aHbd%0K)jd`<4O+qMrtLJLsEMJOtyaALY$FCY&W~!!%>o}_Qk=XbOZ$@IX~Cj;uM^Nf*T%tRy)U*c zc)jt{MRr3+Em1KaQkETCzl~^{!0y$E3zqaT^I-p!sED%9*E=MCF3H#96GUrE-q*$6 z_n^+{Rj}WlbfU+@b8$3KoSBxVgLDEBfB(7=0Oz}+!rrSFGCIVh^RdUz%Y(O>(U}hf&WR;d6^WgD-EWbrjA2hAs-=SUZ z%~2jWi@=GyLgQRK3;R2i8}>2HNgmo3X+4P>p@d=b#n13leQ5)Fp0~zqx<&(Tymfd& zW=GhdMuH9XCDS@{aRo9`lUoaueE;zzR*QrDZh}(TTTLq1Pzr%-!{fDGtxzN^vKLj)5q&VYGT<7PsfOe4?HiH6YewNgvWm#peaMO zE7%`_<4H)J>>xeXm(57)sTJhLxLQmnpU3gcF+4KyQL!9o#GRRpx+a}Ql9Gl_h@eq$ z3Xwy=18NTaZaR^zbpCC+b5j(W;7Ri4l^-Kn99kZs5|dccbfTDau4!Rgh_|2WSj<(d zYq?B)4&xeIdgcR@xMn9P%Bx5qapzN_x(?=DkZKS!2QrhggvDqmAy0-NwFR!oxkht* z^>)clu+d~A!eqlU*K;IwN%!n9>Dp;44ArX$Co5a2p3hy&vcXX`|AS+siSYJH($oB?o{ABQJU_x?N8*-mC6})H{6F}Uq&!n zo9V|c9pErHyhyhd5`F6K%x@~7U$eXF0W2@^@zE@+K>Qq*a64A{(I$JS^5a+D*sfWZ zd76rj$65AlE!ee^vm(P?#J>)*6H!^&&`WxneI~agZ(+B{d)G40zSKr=)-|Xm*wQyd zKI!@H?SjDt<%#M7+g;5`wQp!kWAVpH2eaBRgX^cX3$N||st^8Ir2jEd0|8uGaJU=w z?<4mrNC{>Orw0D9{!3N;_XMQ{w*Akp$bCPQ>))p~p8H*Rf9EzOm<`zLZ!r!Cy#M~^ zahhRB1W!_fAZ!J=2v5uYiiu2|3Hj_nl$u@16ZVZFJsIiuRsuwhvb1S|@|qx`p_@(| z>mfS9U1hUIh#audK|TqFScd^gfJinPmVU(-04+ipRxK6acIbxQoc6X}L14=9qk#4z doV36A`>t-5E^b~f_oWL72=N0L806ID{|9rl7lr@; literal 0 HcmV?d00001 diff --git a/apps/app/tests/fixtures/report-v2.minimal.pdf b/apps/app/tests/fixtures/report-v2.minimal.pdf new file mode 100644 index 0000000000000000000000000000000000000000..e3ebfd6ad118db956efc7fe3130527dad84331ea GIT binary patch literal 2360 zcmaKuc{tSDAIB+MUs+>lV>urk+>$%#YYuy31LeQs_pKkB~)tWNv-1%_OFLN9@wP|}(#{>to3=s@p3*Aj16 zDTnd?jRnJ`2M{=CGkhsmySp_*xgDMpaDQ4uS|Q|&LJgrh)x`c-NW~lhf2K*h<>)v= z61Rs?OzGclq?!XRBNiJ*%HC449$LExWvAkj!yYfAUJ1sAyCU!fj0oxURQG)0^Q6(; zEB7VL822AUuA~OvP9t;A>eP*6iab>H{3u4?*8Cq_fdzrNiNmE{-zP%8T{q~{J2>bt zKt|h?8FaGzhMV5L^nWrD-a@SL89HlOxmsJpeHxfFB-fSWAR>Q*)D+JmtDI&+1f}TJnyt#O)9gIHfxf)R0&TNCGLapqQPvt?OU|p% z_}X>#?qYlg$!aPXm8fHHZwk{Z%jqqr@>=ES!{n*%*ghj?ttld- z_dC!;lMy9jof+n*1-d_d_zZi9O$K#+F5=X=Y}YrcKRcX3TikOyV+FS%pnkPT3LsHE z{>L6a+5#3pAb&#FK7dXF!%QgdBo7ag2OnfUxpo)bS%0R9bh@wic_Pc3MpZ$Y`Y>r! z0EQznh!iGx3wt~7KoVF(Qxkw0^Womwh2irLR>SBb;Ybt$j)22;;3zE(Cv^aZrFs0{ zMZP@#Q9?*K>TeRF#2JWhL+reE>59qptVPp_ek|Rlw%5Y1s7XvPEz^5Wu6>jG;818- z9He*c19o7|Tzx{&Y-gTA$-Wg@DRlTyWB#4&dGjf5-PEZJhfcz-q3$8$e09&L_*80d zFfq2hU9oC!zf+5wPZ8SJm2*%d+@#qOTjCK?fY-OVU$Z0Wkr?|o;-aK73iVF0F;~%F^+)5U{`}Hf{@XNbcON?z1%O$B5%8@CWH4D^l-6IyqXYlD@eH4Frj4WI zLRZS)o&Qd_k!ODMNQ8iuFQx5O8QqTM*e~kvUiM&04_cfzF2H5lP|jIKF8Mtmp4UC4|6sS21? zmVG(5*jhc_A*t8d3fFabnOz@2B802ds*lW<<_=bPv7Ew~=bq+w742%tEj|5Rj3G)_ zB1Kt+&#vc`n>=bg9^GkV-{+!N-URhrEKFxSRm&Y}*)4y?AUs9m^;m;4x;Ctt`J+&! z@ymMGm-oB$r*rp%LcY2dMbGDZWBu!J_Cd3W0bv1$OsCMw8UD;MWJ@u?yXS zkDftR`}}$Lc&>KFQOmb3G;G}YP+lMUial|AJ{eS)LLCl8SB>mv#Y_*B&1}R_+z)fE zX*$m0D^-qir)rE71926%q}VprmOh$!jADsLFS1tR!_^?h%zfG845IR;|hr6i|wGl}ZL0BGh zRA(n!mQ@pX0vq%M&i&M3nnu(9j z*yuZM%gu=9zR%d4j_L%-?l2D`k3V?Anj;*<)#kIv;X?4CCN8ow`*3uR)Tl4oirJBj$ zvw9>8=1W^c#g;8L7^~evo6klwR?@zDXKvEgt~}}A3b|_ymGa_#=)l*Sv_uNH7$6H8xSt}U06z4*|Gts@@q2#&TS@?ZMb z;`=fl>;5AZH^r7zOD+hLzoD}I zllK0|9SSEf@fcJG%*6g>58Ba%tvk7`IbMkQi;FN>L Date: Sat, 10 Oct 2026 11:11:25 +0200 Subject: [PATCH 02/16] =?UTF-8?q?feat(domain):=20report=20document=20v3=20?= =?UTF-8?q?(annotation=20ids,=20sheet=20ref,=20severity=20codes,=20unresol?= =?UTF-8?q?ved=20findings),=20v2=20schema=20as=20input,=20v2=E2=86=92v3=20?= =?UTF-8?q?migration=20with=20map;=20annotation=20colour=20override?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/domain/package.json | 5 +- .../domain/src/anatomical-sheet/schema.ts | 2 + packages/domain/src/index.ts | 1 + packages/domain/src/report/identity.ts | 37 +++ packages/domain/src/report/index.ts | 27 +++ packages/domain/src/report/migrate.ts | 159 ++++++++++++ packages/domain/src/report/migration-map.ts | 40 ++++ packages/domain/src/report/v2.ts | 72 ++++++ packages/domain/src/report/v3.ts | 97 ++++++++ .../tests/anatomical-sheet.validate.test.ts | 2 + .../domain/tests/fixtures/report-v2.full.json | 89 +++++++ .../tests/fixtures/report-v2.minimal.json | 12 + packages/domain/tests/report.migrate.test.ts | 226 ++++++++++++++++++ 13 files changed, 767 insertions(+), 2 deletions(-) create mode 100644 packages/domain/src/report/identity.ts create mode 100644 packages/domain/src/report/index.ts create mode 100644 packages/domain/src/report/migrate.ts create mode 100644 packages/domain/src/report/migration-map.ts create mode 100644 packages/domain/src/report/v2.ts create mode 100644 packages/domain/src/report/v3.ts create mode 100644 packages/domain/tests/fixtures/report-v2.full.json create mode 100644 packages/domain/tests/fixtures/report-v2.minimal.json create mode 100644 packages/domain/tests/report.migrate.test.ts diff --git a/packages/domain/package.json b/packages/domain/package.json index 9eee014e..187daae2 100644 --- a/packages/domain/package.json +++ b/packages/domain/package.json @@ -2,14 +2,15 @@ "name": "@faunosteo/domain", "version": "0.1.0", "private": true, - "description": "Faunosteo pure domain model: canonical anatomical sheet document, Zod schemas and integrity rules", + "description": "Faunosteo pure domain model: canonical anatomical sheet document, report document (v3 + v2 migration), Zod schemas and integrity rules", "license": "MIT", "type": "module", "main": "./src/index.ts", "types": "./src/index.ts", "exports": { ".": "./src/index.ts", - "./anatomical-sheet": "./src/anatomical-sheet/index.ts" + "./anatomical-sheet": "./src/anatomical-sheet/index.ts", + "./report": "./src/report/index.ts" }, "scripts": { "typecheck": "tsc -p tsconfig.json --noEmit", diff --git a/packages/domain/src/anatomical-sheet/schema.ts b/packages/domain/src/anatomical-sheet/schema.ts index 25e354b6..9cf27a2e 100644 --- a/packages/domain/src/anatomical-sheet/schema.ts +++ b/packages/domain/src/anatomical-sheet/schema.ts @@ -149,6 +149,8 @@ const annotationCommon = { laterality: LateralitySchema, geometry: GeometrySchema.nullable(), review_status: ReviewStatusSchema.default('inherited'), + /** Marker colour of this annotation; null = the category colour. */ + color: HexColorSchema.nullable().default(null), } /** Observable annotations link to findings through one explicit field. */ diff --git a/packages/domain/src/index.ts b/packages/domain/src/index.ts index 12ac5d72..9fb87034 100644 --- a/packages/domain/src/index.ts +++ b/packages/domain/src/index.ts @@ -1 +1,2 @@ export * from './anatomical-sheet' +export * from './report' diff --git a/packages/domain/src/report/identity.ts b/packages/domain/src/report/identity.ts new file mode 100644 index 00000000..a472c925 --- /dev/null +++ b/packages/domain/src/report/identity.ts @@ -0,0 +1,37 @@ +import { z } from 'zod' + +/** + * Identity snapshots carried by every report version: who wrote it, on + * which animal, for which owner. Copied into the report at creation so a + * report stays readable when the underlying records change (BDR-010). + */ + +export const PractitionerSchema = z.object({ + name: z.string().min(1), + cabinet: z.string().optional(), + contact: z.string().optional(), + /** SIRET, 14-digit French business identifier (not validated). */ + siret: z.string().optional(), +}) +export type Practitioner = z.infer + +export const AnimalSchema = z.object({ + /** Species of the animal; the sheet the report references matches it. */ + speciesId: z.string().min(1), + name: z.string().min(1), + breed: z.string().optional(), + age: z.string().optional(), +}) +export type Animal = z.infer + +export const OwnerSchema = z.object({ name: z.string().min(1) }) +export type Owner = z.infer + +export const NextAppointmentSchema = z.discriminatedUnion('kind', [ + z.object({ kind: z.literal('date'), date: z.string() }), + z.object({ kind: z.literal('period'), text: z.string() }), +]) +export type NextAppointment = z.infer + +export const LateralSideSchema = z.enum(['left', 'right']) +export type LateralSide = z.infer diff --git a/packages/domain/src/report/index.ts b/packages/domain/src/report/index.ts new file mode 100644 index 00000000..2fae55c0 --- /dev/null +++ b/packages/domain/src/report/index.ts @@ -0,0 +1,27 @@ +export * from './identity' +export * from './v3' +export { + FindingV2Schema, + ObservationV2Schema, + ObservationZoneV2Schema, + ReportV2Schema, + SeverityV2Schema, + VertebraV2Schema, + VertebralRegionV2Schema, + type FindingV2, + type ObservationV2, + type ObservationZoneV2, + type ReportV2, + type SeverityV2, +} from './v2' +export { + ReportMigrationMapSchema, + findingPathKey, + type ReportMigrationMap, +} from './migration-map' +export { + migrateReportV2ToV3, + readReportDocument, + UnsupportedReportVersionError, + type MigrationOutcome, +} from './migrate' diff --git a/packages/domain/src/report/migrate.ts b/packages/domain/src/report/migrate.ts new file mode 100644 index 00000000..c98de8a1 --- /dev/null +++ b/packages/domain/src/report/migrate.ts @@ -0,0 +1,159 @@ +import { findingPathKey, type ReportMigrationMap } from './migration-map' +import { + ReportV2Schema, + type FindingV2, + type ObservationV2, + type ObservationZoneV2, + type ReportV2, + type SeverityV2, +} from './v2' +import { + REPORT_VERSION, + ReportSchema, + type Finding, + type Observation, + type Report, + type ReportZone, + type Severity, +} from './v3' + +/** + * Lifts a Report v2 (PDF attachment or sessionStorage draft of the deployed + * application) to v3 against the migration map of the reference sheet. + * Never throws on content: a zone or finding the map cannot place is kept + * verbatim with its snapshots and flagged `unresolved`, so the practitioner's + * data survives any catalog change and stays identifiable. + */ + +const SEVERITY: Record = { + légère: 'mild', + modérée: 'moderate', + sévère: 'severe', +} + +export interface MigrationOutcome { + report: Report + /** Zones whose legacy id has no annotation in the map. */ + unresolvedZones: number + /** Findings whose legacy path no longer exists in the sheet. */ + unresolvedFindings: number +} + +function migrateZone( + zone: ObservationZoneV2, + map: ReportMigrationMap, +): ReportZone { + const entry = map.annotations[zone.boneId] + const viewId = zone.detailSourceId + ? (map.views[zone.detailSourceId] ?? zone.detailSourceId) + : map.main_view_id + const out: ReportZone = { annotationId: entry?.id ?? zone.boneId, viewId } + if (zone.side) out.side = zone.side + if (zone.vertebrae) out.vertebrae = zone.vertebrae.map((v) => ({ ...v })) + if (entry) { + out.labelFrSnapshot = entry.name.fr + out.labelEnSnapshot = entry.name.en + } else { + out.unresolved = true + } + return out +} + +function migrateFinding(finding: FindingV2, map: ReportMigrationMap): Finding { + const mapped = map.finding_paths[findingPathKey(finding.zoneId, finding.path)] + const out: Finding = { + findingZoneId: finding.zoneId, + path: [...finding.path], + labelFrSnapshot: finding.labelFrSnapshot, + labelEnSnapshot: finding.labelEnSnapshot, + } + if (finding.requiresVetReferral) out.requiresVetReferral = true + if (finding.side) out.side = finding.side + if (typeof mapped === 'string') { + const [zoneId, ...path] = mapped.split('/') + out.findingZoneId = zoneId! + out.path = path + } else { + // null = removed by curation; undefined = never part of the legacy catalog. + out.unresolved = true + } + return out +} + +function migrateObservation( + obs: ObservationV2, + map: ReportMigrationMap, +): Observation { + const out: Observation = { + id: obs.id, + zones: obs.zones.map((z) => migrateZone(z, map)), + findings: obs.findings.map((f) => migrateFinding(f, map)), + freeTextFindings: [...obs.freeTextFindings], + comment: obs.comment, + } + if (obs.severity) out.severity = SEVERITY[obs.severity] + return out +} + +export function migrateReportV2ToV3( + report: ReportV2, + map: ReportMigrationMap, +): MigrationOutcome { + const observations = report.observations.map((o) => + migrateObservation(o, map), + ) + const migrated: Report = { + version: REPORT_VERSION, + id: report.id, + createdAt: report.createdAt, + date: report.date, + practitioner: report.practitioner, + animal: report.animal, + owner: report.owner, + sheet: { ...map.sheet }, + observations, + conclusion: report.conclusion, + recommendations: report.recommendations, + localAnnotations: [], + } + if (report.nextAppointment) migrated.nextAppointment = report.nextAppointment + const zones = observations.flatMap((o) => o.zones) + const findings = observations.flatMap((o) => o.findings) + return { + report: ReportSchema.parse(migrated), + unresolvedZones: zones.filter((z) => z.unresolved).length, + unresolvedFindings: findings.filter((f) => f.unresolved).length, + } +} + +/** Thrown for a report whose version this code cannot read. */ +export class UnsupportedReportVersionError extends Error { + constructor(public readonly foundVersion: number | null) { + super(`unsupported report version: ${foundVersion ?? 'unknown'}`) + this.name = 'UnsupportedReportVersionError' + } +} + +function versionOf(data: unknown): number | null { + if (data === null || typeof data !== 'object') return null + const v = (data as { version?: unknown }).version + return typeof v === 'number' ? v : null +} + +/** + * Reads a report document of any supported version (2 or 3) and returns it + * as v3. Zod errors propagate: a document of a known version that does not + * parse is corrupt, not old. + */ +export function readReportDocument( + data: unknown, + map: ReportMigrationMap, +): MigrationOutcome { + const version = versionOf(data) + if (version === REPORT_VERSION) { + const report = ReportSchema.parse(data) + return { report, unresolvedZones: 0, unresolvedFindings: 0 } + } + if (version === 2) return migrateReportV2ToV3(ReportV2Schema.parse(data), map) + throw new UnsupportedReportVersionError(version) +} diff --git a/packages/domain/src/report/migration-map.ts b/packages/domain/src/report/migration-map.ts new file mode 100644 index 00000000..65326590 --- /dev/null +++ b/packages/domain/src/report/migration-map.ts @@ -0,0 +1,40 @@ +import { z } from 'zod' +import { SheetRefSchema } from './v3' + +/** + * Correspondence between the legacy identifiers a Report v2 carries and the + * canonical sheet a Report v3 references. Generated by the curation pipeline + * (`draft/report-migration-map.json`), never written by hand: annotations + * come from the legacy id map, finding paths from the applier's rename and + * removal records. A `null` finding path means "removed from the sheet": + * the migration keeps the finding with its snapshots and flags it. + */ + +const LocalizedNameSchema = z.object({ fr: z.string(), en: z.string() }) + +export const ReportMigrationMapSchema = z.object({ + schema_version: z.literal(1), + sheet: SheetRefSchema, + /** Id of the view a v2 zone without `detailSourceId` belongs to. */ + main_view_id: z.string().min(1), + /** Legacy detail popup key → view id. */ + views: z.record(z.string(), z.string().min(1)), + /** Legacy `data-anno-id` → annotation id and the legacy labels. */ + annotations: z.record( + z.string(), + z.object({ id: z.string().min(1), name: LocalizedNameSchema }), + ), + /** + * `/` of every legacy finding node → + * the same key in the sheet, or null when the node was removed. + */ + finding_paths: z.record(z.string(), z.string().nullable()), +}) +export type ReportMigrationMap = z.infer + +export function findingPathKey( + zoneId: string, + path: readonly string[], +): string { + return `${zoneId}/${path.join('/')}` +} diff --git a/packages/domain/src/report/v2.ts b/packages/domain/src/report/v2.ts new file mode 100644 index 00000000..9c6b958c --- /dev/null +++ b/packages/domain/src/report/v2.ts @@ -0,0 +1,72 @@ +import { z } from 'zod' +import { + AnimalSchema, + LateralSideSchema, + NextAppointmentSchema, + OwnerSchema, + PractitionerSchema, +} from './identity' + +/** + * Report document version 2, exactly as the deployed application wrote it + * (PDF attachments of the practitioner's archive, sessionStorage drafts). + * Kept as an INPUT format only: nothing writes v2 any more, `migrate.ts` + * lifts it to v3. Field comments describe the legacy meaning. + */ + +export const SeverityV2Schema = z.enum(['légère', 'modérée', 'sévère']) +export type SeverityV2 = z.infer + +export const VertebralRegionV2Schema = z.enum(['C', 'T', 'L', 'S', 'Cd']) + +export const VertebraV2Schema = z.object({ + region: VertebralRegionV2Schema, + index: z.number().int().positive(), +}) + +export const ObservationZoneV2Schema = z.object({ + /** The legacy SVG `data-anno-id` (e.g. `point-mpbwtst0`). */ + boneId: z.string().min(1), + /** Legacy detail popup key (`head`) when the zone came from that view. */ + detailSourceId: z.string().optional(), + vertebrae: z.array(VertebraV2Schema).optional(), + side: LateralSideSchema.optional(), +}) +export type ObservationZoneV2 = z.infer + +export const FindingV2Schema = z.object({ + /** Legacy catalog zone key (equal to the canonical finding zone id). */ + zoneId: z.string().min(1), + /** Node ids from the zone's categories down to the leaf. */ + path: z.array(z.string().min(1)).min(1), + labelFrSnapshot: z.string().min(1), + labelEnSnapshot: z.string().min(1), + requiresVetReferral: z.boolean().optional(), + side: LateralSideSchema.optional(), +}) +export type FindingV2 = z.infer + +export const ObservationV2Schema = z.object({ + id: z.string().min(1), + zones: z.array(ObservationZoneV2Schema), + findings: z.array(FindingV2Schema), + freeTextFindings: z.array(z.string()), + severity: SeverityV2Schema.optional(), + comment: z.string(), +}) +export type ObservationV2 = z.infer + +export const ReportV2Schema = z.object({ + version: z.literal(2), + id: z.string().min(1), + createdAt: z.string(), + date: z.string(), + practitioner: PractitionerSchema, + animal: AnimalSchema, + owner: OwnerSchema, + observations: z.array(ObservationV2Schema), + conclusion: z.string(), + recommendations: z.string(), + nextAppointment: NextAppointmentSchema.optional(), +}) +export type ReportV2 = z.infer diff --git a/packages/domain/src/report/v3.ts b/packages/domain/src/report/v3.ts new file mode 100644 index 00000000..0609199e --- /dev/null +++ b/packages/domain/src/report/v3.ts @@ -0,0 +1,97 @@ +import { z } from 'zod' +import { + AnimalSchema, + LateralSideSchema, + NextAppointmentSchema, + OwnerSchema, + PractitionerSchema, +} from './identity' + +/** + * Report document version 3: a report written on the canonical anatomical + * sheet. Zones name an annotation of a view of an exact sheet, findings a + * node path of a finding zone, both by stable ids; every label the report + * needs to stay readable without the sheet is snapshotted. Breaking change + * → version 4; additive optional fields keep the version. + */ + +export const REPORT_VERSION = 3 + +export const SeveritySchema = z.enum(['mild', 'moderate', 'severe']) +export type Severity = z.infer + +/** Region codes are the sheet's `vertebral_config` codes, checked at runtime. */ +export const VertebraSchema = z.object({ + region: z.string().min(1), + index: z.number().int().positive(), +}) +export type Vertebra = z.infer + +/** The sheet document a report was built on, by content. */ +export const SheetRefSchema = z.object({ + sheetId: z.string().min(1), + /** Database version id once the sheet lives in the database; null for a bundled draft. */ + versionId: z.string().min(1).nullable(), + /** sha256 of the document file the report was written against. */ + documentSha256: z.string().regex(/^[0-9a-f]{64}$/), +}) +export type SheetRef = z.infer + +export const ReportZoneSchema = z.object({ + annotationId: z.string().min(1), + viewId: z.string().min(1), + side: LateralSideSchema.optional(), + vertebrae: z.array(VertebraSchema).optional(), + /** Annotation name at selection time (or legacy name at migration). */ + labelFrSnapshot: z.string().optional(), + labelEnSnapshot: z.string().optional(), + /** Set by the migration when the legacy id has no canonical annotation. */ + unresolved: z.literal(true).optional(), +}) +export type ReportZone = z.infer + +export const FindingSchema = z.object({ + findingZoneId: z.string().min(1), + /** Node ids from the zone's categories down to the leaf. */ + path: z.array(z.string().min(1)).min(1), + labelFrSnapshot: z.string().min(1), + labelEnSnapshot: z.string().min(1), + requiresVetReferral: z.boolean().optional(), + side: LateralSideSchema.optional(), + /** Set by the migration when the path no longer exists in the sheet; data kept. */ + unresolved: z.literal(true).optional(), +}) +export type Finding = z.infer + +export const ObservationSchema = z.object({ + id: z.string().min(1), + zones: z.array(ReportZoneSchema), + findings: z.array(FindingSchema), + freeTextFindings: z.array(z.string()), + severity: SeveritySchema.optional(), + comment: z.string(), +}) +export type Observation = z.infer + +export const ReportSchema = z.object({ + version: z.literal(REPORT_VERSION), + id: z.string().min(1), + /** ISO timestamp of report creation. */ + createdAt: z.string(), + /** ISO date of the clinical encounter. */ + date: z.string(), + practitioner: PractitionerSchema, + animal: AnimalSchema, + owner: OwnerSchema, + sheet: SheetRefSchema, + observations: z.array(ObservationSchema), + conclusion: z.string(), + recommendations: z.string(), + nextAppointment: NextAppointmentSchema.optional(), + /** Reserved for report-only points (OPEN_QUESTIONS Q6); empty until defined. */ + localAnnotations: z.array(z.unknown()).max(0).default([]), +}) +export type Report = z.infer +export type ReportInput = z.input + +export type { LateralSide, NextAppointment } from './identity' diff --git a/packages/domain/tests/anatomical-sheet.validate.test.ts b/packages/domain/tests/anatomical-sheet.validate.test.ts index 8856be86..92e2d52b 100644 --- a/packages/domain/tests/anatomical-sheet.validate.test.ts +++ b/packages/domain/tests/anatomical-sheet.validate.test.ts @@ -33,6 +33,7 @@ function point(id: string, fields: Partial = {}): Annotation { laterality: 'bilateral', geometry: null, review_status: 'inherited', + color: null, name: { fr: id, en: id }, finding_zone_id: 'hip', vertebral_region_code: null, @@ -49,6 +50,7 @@ function trigger(id: string, viewId: string, opensViewId: string) { laterality: 'unpaired', geometry: null, review_status: 'inherited', + color: null, name: null, opens_view_id: opensViewId, } satisfies Annotation diff --git a/packages/domain/tests/fixtures/report-v2.full.json b/packages/domain/tests/fixtures/report-v2.full.json new file mode 100644 index 00000000..b331d170 --- /dev/null +++ b/packages/domain/tests/fixtures/report-v2.full.json @@ -0,0 +1,89 @@ +{ + "version": 2, + "id": "fixture-full-v2", + "createdAt": "2026-06-01T09:00:00.000Z", + "date": "2026-06-01", + "practitioner": { + "name": "Dr. Claire Dupont", + "cabinet": "Cabinet Équi-Ostéo", + "contact": "claire@example.test", + "siret": "12345678901234" + }, + "animal": { + "speciesId": "equine", + "name": "Mistral", + "breed": "Selle Français", + "age": "9 ans" + }, + "owner": { "name": "Jean Martin" }, + "observations": [ + { + "id": "obs-1", + "zones": [ + { "boneId": "point-mpbwyyc9" }, + { "boneId": "point-mpbwtst0", "side": "left" }, + { "boneId": "point-mpbwtst0", "side": "right" } + ], + "findings": [ + { + "zoneId": "c7-t1", + "path": ["c7-t1-dysfunctions", "segmental", "fixation"], + "labelFrSnapshot": "Fixation de la charnière", + "labelEnSnapshot": "Junction fixation" + }, + { + "zoneId": "hip", + "path": ["hip-dysfunctions", "articular", "restriction-flexion"], + "labelFrSnapshot": "Restriction en flexion", + "labelEnSnapshot": "Flexion restriction", + "side": "left" + } + ], + "freeTextFindings": ["Sensibilité au garrot"], + "severity": "modérée", + "comment": "Réagit à la palpation du garrot." + }, + { + "id": "obs-2", + "zones": [ + { + "boneId": "zone-mpbx5hx2", + "vertebrae": [ + { "region": "C", "index": 3 }, + { "region": "C", "index": 4 } + ] + } + ], + "findings": [ + { + "zoneId": "cervical", + "path": ["cervical-observations", "stumbling-proprioceptive"], + "labelFrSnapshot": "Trébuchements / déficit proprioceptif rapporté", + "labelEnSnapshot": "Reported stumbling / proprioceptive deficit", + "requiresVetReferral": true + } + ], + "freeTextFindings": [], + "severity": "sévère", + "comment": "" + }, + { + "id": "obs-3", + "zones": [{ "boneId": "point-mpbyo7zq", "detailSourceId": "head" }], + "findings": [ + { + "zoneId": "atm", + "path": ["atm-observations", "headshaking"], + "labelFrSnapshot": "Headshaking (secouement de tête)", + "labelEnSnapshot": "Headshaking", + "requiresVetReferral": true + } + ], + "freeTextFindings": [], + "comment": "Vue détail tête." + } + ], + "conclusion": "Dysfonction cervico-thoracique avec compensation du bassin.", + "recommendations": "Repos 3 jours puis reprise progressive.", + "nextAppointment": { "kind": "date", "date": "2026-07-01" } +} diff --git a/packages/domain/tests/fixtures/report-v2.minimal.json b/packages/domain/tests/fixtures/report-v2.minimal.json new file mode 100644 index 00000000..1028c40b --- /dev/null +++ b/packages/domain/tests/fixtures/report-v2.minimal.json @@ -0,0 +1,12 @@ +{ + "version": 2, + "id": "fixture-minimal-v2", + "createdAt": "2026-06-01T09:00:00.000Z", + "date": "2026-06-01", + "practitioner": { "name": "Dr. Dupont" }, + "animal": { "speciesId": "equine", "name": "Mistral" }, + "owner": { "name": "Jean Martin" }, + "observations": [], + "conclusion": "", + "recommendations": "" +} diff --git a/packages/domain/tests/report.migrate.test.ts b/packages/domain/tests/report.migrate.test.ts new file mode 100644 index 00000000..f1c87d51 --- /dev/null +++ b/packages/domain/tests/report.migrate.test.ts @@ -0,0 +1,226 @@ +import { describe, expect, it } from 'vitest' +import { + ReportMigrationMapSchema, + ReportSchema, + ReportV2Schema, + migrateReportV2ToV3, + readReportDocument, + UnsupportedReportVersionError, + type ReportMigrationMap, +} from '../src' +import full from './fixtures/report-v2.full.json' +import minimal from './fixtures/report-v2.minimal.json' + +const SHA = 'a'.repeat(64) + +/** Hand-written slice of the generated map, enough for the golden fixtures. */ +const MAP: ReportMigrationMap = ReportMigrationMapSchema.parse({ + schema_version: 1, + sheet: { sheetId: 'sheet-1', versionId: null, documentSha256: SHA }, + main_view_id: 'main', + views: { head: 'head' }, + annotations: { + 'point-mpbwyyc9': { + id: 'c7-t1', + name: { + fr: 'Charnière C7-T1 (cervico-thoracique)', + en: 'C7-T1 (Cervicothoracic)', + }, + }, + 'point-mpbwtst0': { + id: 'hip', + name: { fr: 'Hanche (coxo-fémorale)', en: 'Hip joint' }, + }, + 'zone-mpbx5hx2': { + id: 'cervical', + name: { fr: 'Vertèbres cervicales', en: 'Cervical Vertebrae' }, + }, + 'point-mpbyo7zq': { + id: 'atm', + name: { + fr: 'Articulation Temporo-Mandibulaire (ATM)', + en: 'Temporomandibular Joint (TMJ)', + }, + }, + }, + finding_paths: { + 'c7-t1/c7-t1-dysfunctions/segmental/fixation': + 'c7-t1/c7-t1-dysfunctions/segmental/fixation', + 'hip/hip-dysfunctions/articular/restriction-flexion': + 'hip/hip-dysfunctions/articular/restriction-flexion', + 'cervical/cervical-observations/stumbling-proprioceptive': + 'cervical/cervical-consultation-reasons/stumbling-proprioceptive', + 'atm/atm-observations/headshaking': null, + }, +}) + +describe('Report v3 schema', () => { + it('accepts a report with an empty reserved localAnnotations and defaults it', () => { + const parsed = ReportSchema.parse({ + version: 3, + id: 'r', + createdAt: '2026-10-10T00:00:00Z', + date: '2026-10-10', + practitioner: { name: 'P' }, + animal: { speciesId: 'equine', name: 'A' }, + owner: { name: 'O' }, + sheet: { sheetId: 's', versionId: null, documentSha256: SHA }, + observations: [], + conclusion: '', + recommendations: '', + }) + expect(parsed.localAnnotations).toEqual([]) + }) + + it.each([ + ['version 2', { version: 2 }], + ['a reserved localAnnotations entry', { localAnnotations: [{ x: 1 }] }], + [ + 'a French severity value', + { + observations: [ + { + id: 'o', + zones: [], + findings: [], + freeTextFindings: [], + comment: '', + severity: 'légère', + }, + ], + }, + ], + [ + 'a malformed document hash', + { sheet: { sheetId: 's', versionId: null, documentSha256: 'xyz' } }, + ], + ])('rejects %s', (_label, patch) => { + const base = migrateReportV2ToV3(ReportV2Schema.parse(minimal), MAP).report + expect(ReportSchema.safeParse({ ...base, ...patch }).success).toBe(false) + }) +}) + +describe('migrateReportV2ToV3 on the golden fixtures', () => { + const v2 = ReportV2Schema.parse(full) + const outcome = migrateReportV2ToV3(v2, MAP) + const { report } = outcome + + it('keeps identity, dates, conclusion and appointment verbatim', () => { + expect(report.version).toBe(3) + expect(report.id).toBe(v2.id) + expect(report.practitioner).toEqual(v2.practitioner) + expect(report.animal).toEqual(v2.animal) + expect(report.owner).toEqual(v2.owner) + expect(report.conclusion).toBe(v2.conclusion) + expect(report.nextAppointment).toEqual(v2.nextAppointment) + expect(report.sheet).toEqual(MAP.sheet) + expect(report.observations.map((o) => o.id)).toEqual( + v2.observations.map((o) => o.id), + ) + }) + + it('maps legacy ids to annotation ids, views and snapshots the legacy names', () => { + const zones = report.observations.flatMap((o) => o.zones) + const hip = zones.filter((z) => z.annotationId === 'hip') + expect(hip.map((z) => z.side).sort()).toEqual(['left', 'right']) + expect(hip[0]!.viewId).toBe('main') + expect(hip[0]!.labelFrSnapshot).toBe('Hanche (coxo-fémorale)') + const atm = zones.find((z) => z.annotationId === 'atm')! + expect(atm.viewId).toBe('head') + const cervical = zones.find((z) => z.annotationId === 'cervical')! + expect(cervical.vertebrae).toEqual( + v2.observations + .flatMap((o) => o.zones) + .find((z) => z.boneId === 'zone-mpbx5hx2')!.vertebrae, + ) + expect(zones.some((z) => z.unresolved)).toBe(false) + expect(outcome.unresolvedZones).toBe(0) + }) + + it('remaps moved finding paths, keeps removed ones flagged with their snapshots', () => { + const findings = report.observations.flatMap((o) => o.findings) + const moved = findings.find((f) => + f.path.includes('stumbling-proprioceptive'), + )! + expect(moved.path).toEqual([ + 'cervical-consultation-reasons', + 'stumbling-proprioceptive', + ]) + expect(moved.findingZoneId).toBe('cervical') + expect(moved.unresolved).toBeUndefined() + const removed = findings.find((f) => f.path.includes('headshaking'))! + expect(removed.unresolved).toBe(true) + expect(removed.path).toEqual(['atm-observations', 'headshaking']) + expect(removed.labelFrSnapshot).toBe('Headshaking (secouement de tête)') + expect(removed.requiresVetReferral).toBe(true) + expect(outcome.unresolvedFindings).toBe(1) + }) + + it('converts severities to stable codes', () => { + const codes = report.observations.map((o) => o.severity) + expect(codes).toContain('moderate') + expect(codes).toContain('severe') + expect( + codes.every( + (c) => c === undefined || ['mild', 'moderate', 'severe'].includes(c), + ), + ).toBe(true) + }) + + it('flags an unknown legacy zone id and an unknown finding path instead of dropping them', () => { + const odd = { + ...v2, + observations: [ + { + id: 'o', + zones: [{ boneId: 'point-unknown' }], + findings: [ + { + zoneId: 'nowhere', + path: ['x'], + labelFrSnapshot: 'X', + labelEnSnapshot: 'X', + }, + ], + freeTextFindings: [], + comment: '', + }, + ], + } + const out = migrateReportV2ToV3(ReportV2Schema.parse(odd), MAP) + expect(out.report.observations[0]!.zones[0]).toMatchObject({ + annotationId: 'point-unknown', + viewId: 'main', + unresolved: true, + }) + expect(out.report.observations[0]!.findings[0]).toMatchObject({ + findingZoneId: 'nowhere', + path: ['x'], + unresolved: true, + }) + expect(out.unresolvedZones).toBe(1) + expect(out.unresolvedFindings).toBe(1) + }) +}) + +describe('readReportDocument', () => { + it('returns a v3 document as is and migrates a v2 one', () => { + const v3 = migrateReportV2ToV3(ReportV2Schema.parse(minimal), MAP).report + expect(readReportDocument(v3, MAP).report).toEqual(v3) + expect(readReportDocument(minimal, MAP).report.version).toBe(3) + }) + + it('refuses unknown versions with the found version', () => { + expect(() => readReportDocument({ ...minimal, version: 1 }, MAP)).toThrow( + UnsupportedReportVersionError, + ) + expect(() => readReportDocument({ hello: 'world' }, MAP)).toThrow( + UnsupportedReportVersionError, + ) + try { + readReportDocument({ ...minimal, version: 7 }, MAP) + } catch (e) { + expect((e as UnsupportedReportVersionError).foundVersion).toBe(7) + } + }) +}) From 0a17e390cfc4c18c602b24a38b81a8cdc583c866 Mon Sep 17 00:00:00 2001 From: bchanot Date: Sat, 10 Oct 2026 11:17:34 +0200 Subject: [PATCH 03/16] feat(anatomy): report migration map and sheet reference generated by the pipeline, pure annotation-layer renderer (legacy marker look) shared with the app, app review drawings, marker colours as document data --- apps/app/package.json | 2 + packages/anatomy/package.json | 5 +- packages/anatomy/src/curation/app-review.ts | 36 + packages/anatomy/src/curation/changelog.ts | 24 + packages/anatomy/src/curation/fields.ts | 1 + packages/anatomy/src/curation/index.ts | 8 + .../anatomy/src/curation/migration-map.ts | 178 ++++ packages/anatomy/src/curation/pipeline.ts | 62 +- packages/anatomy/src/index.ts | 1 + packages/anatomy/src/render/dom.ts | 38 + packages/anatomy/src/render/index.ts | 22 + packages/anatomy/src/render/layer.ts | 261 +++++ packages/anatomy/src/render/serialize.ts | 25 + .../tests/curation.migration-map.test.ts | 183 ++++ packages/anatomy/tests/render.layer.test.ts | 158 +++ pnpm-lock.yaml | 6 + .../equine/curation/changes.json | 63 ++ .../equine/draft/CHANGELOG.md | 18 + .../equine/draft/REVIEW-REPORT.md | 1 + .../equine/draft/document.json | 19 +- .../equine/draft/equine_draft.sql | 38 +- .../equine/draft/report-migration-map.json | 997 ++++++++++++++++++ .../equine/draft/review/app-head.svg | 704 +++++++++++++ .../equine/draft/review/app-main.svg | 704 +++++++++++++ .../equine/draft/sheet-ref.json | 7 + 25 files changed, 3533 insertions(+), 28 deletions(-) create mode 100644 packages/anatomy/src/curation/app-review.ts create mode 100644 packages/anatomy/src/curation/migration-map.ts create mode 100644 packages/anatomy/src/render/dom.ts create mode 100644 packages/anatomy/src/render/index.ts create mode 100644 packages/anatomy/src/render/layer.ts create mode 100644 packages/anatomy/src/render/serialize.ts create mode 100644 packages/anatomy/tests/curation.migration-map.test.ts create mode 100644 packages/anatomy/tests/render.layer.test.ts create mode 100644 supabase/seed/anatomical-sheets/equine/draft/report-migration-map.json create mode 100644 supabase/seed/anatomical-sheets/equine/draft/review/app-head.svg create mode 100644 supabase/seed/anatomical-sheets/equine/draft/review/app-main.svg create mode 100644 supabase/seed/anatomical-sheets/equine/draft/sheet-ref.json diff --git a/apps/app/package.json b/apps/app/package.json index 4e352035..32ae0698 100644 --- a/apps/app/package.json +++ b/apps/app/package.json @@ -15,6 +15,8 @@ "scaffold:species": "node scripts/scaffold-species.mjs" }, "dependencies": { + "@faunosteo/anatomy": "workspace:*", + "@faunosteo/domain": "workspace:*", "@faunosteo/supabase": "workspace:*", "motion": "^11.11.17", "pdf-lib": "^1.17.1", diff --git a/packages/anatomy/package.json b/packages/anatomy/package.json index 97b3608e..8ab41a6b 100644 --- a/packages/anatomy/package.json +++ b/packages/anatomy/package.json @@ -2,13 +2,14 @@ "name": "@faunosteo/anatomy", "version": "0.1.0", "private": true, - "description": "Faunosteo anatomy tooling: deterministic legacy importer that turns the historical equine assets into the canonical anatomical sheet draft", + "description": "Faunosteo anatomy tooling: deterministic legacy importer, curation pipeline (changeset \u2192 draft, report migration map) and the pure annotation-layer renderer shared with the application", "license": "MIT", "type": "module", "main": "./src/index.ts", "types": "./src/index.ts", "exports": { - ".": "./src/index.ts" + ".": "./src/index.ts", + "./render": "./src/render/index.ts" }, "scripts": { "typecheck": "tsc -p tsconfig.json --noEmit", diff --git a/packages/anatomy/src/curation/app-review.ts b/packages/anatomy/src/curation/app-review.ts new file mode 100644 index 00000000..7ff13708 --- /dev/null +++ b/packages/anatomy/src/curation/app-review.ts @@ -0,0 +1,36 @@ +import { DOMParser, XMLSerializer } from '@xmldom/xmldom' +import type { AnatomicalSheetDocumentInput } from '@faunosteo/domain' +import { createLayerElement } from '../render/dom' +import { renderAnnotationLayer, viewBoxOf } from '../render/layer' + +/** + * The drawing of one view exactly as the application renders it: the + * cleaned asset framed on the view's box plus the annotation layer the app + * generates from the document. Written under draft/review/app-.svg + * so the markers and the framing can be compared with the legacy files + * before and after a change, outside the browser. + */ + +export interface AppReviewInput { + cleanedSvg: string + document: AnatomicalSheetDocumentInput + viewId: string +} + +export function renderAppReviewDrawing(input: AppReviewInput): string { + const doc = new DOMParser().parseFromString(input.cleanedSvg, 'image/svg+xml') + const root = doc.documentElement + if (!root || root.tagName !== 'svg') throw new Error('not an SVG document') + const view = input.document.views.find((v) => v.id === input.viewId) + if (!view) throw new Error(`unknown view "${input.viewId}"`) + const box = viewBoxOf(view) + if (box) root.setAttribute('viewBox', box) + root.removeAttribute('width') + root.removeAttribute('height') + const layer = renderAnnotationLayer({ + document: input.document, + viewId: view.id, + }) + root.appendChild(createLayerElement(doc, layer) as never) + return new XMLSerializer().serializeToString(doc) +} diff --git a/packages/anatomy/src/curation/changelog.ts b/packages/anatomy/src/curation/changelog.ts index 3a1a5742..0381c6f7 100644 --- a/packages/anatomy/src/curation/changelog.ts +++ b/packages/anatomy/src/curation/changelog.ts @@ -3,6 +3,7 @@ import { KIND_LABELS, LEVEL_LABELS, LEVELS } from './labels' import { needsConfirmation, type ChangeLevel } from './schema' import { statRows, type DocumentStats } from './stats' import { isItem } from './targets' +import type { MigrationMapStats } from './migration-map' import type { ChangeRecord } from './types' /** @@ -94,14 +95,37 @@ function intro(): string { ].join('\n') } +/** Fate of the legacy finding nodes a Report v2 may cite (report-migration-map.json). */ +function migration(stats: MigrationMapStats): string { + const rows = [ + ['Nœuds du catalogue historique', String(stats.nodes)], + ['Chemin identique', String(stats.identical)], + [ + 'Chemin renommé ou déplacé (suivi des renommages)', + String(stats.remapped), + ], + [ + 'Relogé sous une autre catégorie (correspondance unique)', + String(stats.rehomed), + ], + [ + 'Retiré : le bilan garde le constat avec ses libellés figés', + String(stats.removed), + ], + ] + return `## Migration des bilans v2\n\n${table(['Nœuds', 'Nombre'], rows)}` +} + export function renderChangelog( result: { records: readonly ChangeRecord[] }, before: DocumentStats, after: DocumentStats, + migrationStats: MigrationMapStats, ): string { const sections = [ intro(), comparison(before, after), + migration(migrationStats), ...LEVELS.map((level) => levelSection(level, result.records)), ] return `${sections.join('\n\n')}\n` diff --git a/packages/anatomy/src/curation/fields.ts b/packages/anatomy/src/curation/fields.ts index ea96e5dc..d55569e1 100644 --- a/packages/anatomy/src/curation/fields.ts +++ b/packages/anatomy/src/curation/fields.ts @@ -23,6 +23,7 @@ const SETTABLE: Record = { 'finding_zone_id', 'vertebral_region_code', 'opens_view_id', + 'color', ], zone: ['name'], finding_category: [ diff --git a/packages/anatomy/src/curation/index.ts b/packages/anatomy/src/curation/index.ts index c7785472..71f8be4f 100644 --- a/packages/anatomy/src/curation/index.ts +++ b/packages/anatomy/src/curation/index.ts @@ -9,10 +9,18 @@ export { compactValue, renderChangelog } from './changelog' export { buildEquineDraft, DRAFT_SEED_SQL_FILE, + MIGRATION_MAP_FILE, + SHEET_REF_FILE, renderDraftArtifacts, type DraftInput, type DraftResult, } from './pipeline' +export { + buildReportMigrationMap, + type MigrationMapInput, + type MigrationMapStats, +} from './migration-map' +export { renderAppReviewDrawing, type AppReviewInput } from './app-review' export { REVIEW_OVERLAY_DIR, overlayMarkers, diff --git a/packages/anatomy/src/curation/migration-map.ts b/packages/anatomy/src/curation/migration-map.ts new file mode 100644 index 00000000..b6e20cf0 --- /dev/null +++ b/packages/anatomy/src/curation/migration-map.ts @@ -0,0 +1,178 @@ +import type { ReportMigrationMap, SheetRef } from '@faunosteo/domain' +import type { LegacyIdMap } from '../legacy/types' +import { allFindings, topCollection, type Item } from './targets' +import type { ChangeRecord } from './types' + +/** + * Report migration map: where every identifier a Report v2 may carry lands + * in the curated draft. Annotations come from the legacy id map (then + * follow annotation renames), finding paths from replaying the applier's + * rename, move and remove records over every node of the legacy baseline. + * A node removed with its category and re-added under another category at + * the same relative place (the sphenoid restructure) is re-homed when the + * match is unique; anything else stays null = "removed", and the report + * keeps the finding with its snapshots. + */ + +const FINDING = 'finding:' + +export interface MigrationMapInput { + baseline: Item + final: Item + legacyIdMap: LegacyIdMap + records: readonly ChangeRecord[] + sheet: SheetRef + mainViewId: string +} + +export interface MigrationMapStats { + nodes: number + identical: number + remapped: number + rehomed: number + removed: number +} + +interface PathEntry { + legacy: string + current: string | null + rehomed: boolean +} + +function strip(target: string): string { + return target.slice(FINDING.length) +} + +function lastSegment(path: string): string { + return path.slice(path.lastIndexOf('/') + 1) +} + +function withLastSegment(path: string, id: string): string { + const cut = path.lastIndexOf('/') + return cut < 0 ? id : `${path.slice(0, cut + 1)}${id}` +} + +function replacePrefix(entries: PathEntry[], from: string, to: string | null) { + for (const entry of entries) { + const current = entry.current + if (current === null) continue + if (current === from) entry.current = to + else if (current.startsWith(`${from}/`)) { + entry.current = to === null ? null : `${to}${current.slice(from.length)}` + } + } +} + +function applyRecord( + entries: PathEntry[], + ids: { annotations: Map; views: Map }, + record: ChangeRecord, +) { + const { op, target } = record + if (op.op !== 'rename' && op.op !== 'remove' && op.op !== 'move') return + if (target.startsWith(FINDING)) { + const from = strip(target) + if (op.op === 'rename') + replacePrefix(entries, from, withLastSegment(from, op.id)) + if (op.op === 'remove') replacePrefix(entries, from, null) + if (op.op === 'move') + replacePrefix(entries, from, `${strip(op.to)}/${lastSegment(from)}`) + return + } + const [kind, id] = target.split(':', 2) as [string, string] + if (kind === 'zone') { + for (const entry of entries) { + if (entry.current?.startsWith(`${id}/`)) { + entry.current = + op.op === 'remove' + ? null + : `${op.op === 'rename' ? op.id : id}${entry.current.slice(id.length)}` + } + } + return + } + if (op.op === 'rename' && (kind === 'annotation' || kind === 'view')) { + const map = kind === 'annotation' ? ids.annotations : ids.views + for (const [legacy, current] of map) + if (current === id) map.set(legacy, op.id) + } +} + +/** `zone//` present exactly once in the final document. */ +function rehome(entry: PathEntry, finalPaths: ReadonlySet): void { + const [zone, , ...rest] = entry.legacy.split('/') + if (rest.length === 0) return + const tail = `/${rest.join('/')}` + const matches = [...finalPaths].filter( + (p) => + p.startsWith(`${zone}/`) && + p.endsWith(tail) && + p.split('/').length === rest.length + 2, + ) + if (matches.length === 1) { + entry.current = matches[0]! + entry.rehomed = true + } +} + +function annotationNames(doc: Item): Map { + const names = new Map() + for (const a of topCollection(doc, 'annotation')) { + const name = a.name as { fr?: string; en?: string } | null + names.set(String(a.id), { fr: name?.fr ?? '', en: name?.en ?? '' }) + } + return names +} + +export function buildReportMigrationMap(input: MigrationMapInput): { + map: ReportMigrationMap + stats: MigrationMapStats +} { + const entries: PathEntry[] = allFindings(input.baseline).map((e) => ({ + legacy: strip(e.target), + current: strip(e.target), + rehomed: false, + })) + const ids = { + annotations: new Map(Object.entries(input.legacyIdMap.annotations)), + views: new Map(Object.entries(input.legacyIdMap.views)), + } + for (const record of input.records) applyRecord(entries, ids, record) + const finalPaths = new Set( + allFindings(input.final).map((e) => strip(e.target)), + ) + for (const entry of entries) { + if (entry.current !== null && !finalPaths.has(entry.current)) + entry.current = null + if (entry.current === null) rehome(entry, finalPaths) + } + const legacyNames = annotationNames(input.baseline) + const importIds = new Map(Object.entries(input.legacyIdMap.annotations)) + const annotations: ReportMigrationMap['annotations'] = {} + for (const [legacy, finalId] of ids.annotations) { + annotations[legacy] = { + id: finalId, + name: legacyNames.get(importIds.get(legacy)!) ?? { fr: '', en: '' }, + } + } + const finding_paths: Record = {} + for (const entry of entries) finding_paths[entry.legacy] = entry.current + const map: ReportMigrationMap = { + schema_version: 1, + sheet: input.sheet, + main_view_id: input.mainViewId, + views: Object.fromEntries(ids.views), + annotations, + finding_paths, + } + const stats: MigrationMapStats = { + nodes: entries.length, + identical: entries.filter((e) => e.current === e.legacy).length, + remapped: entries.filter( + (e) => e.current !== null && e.current !== e.legacy && !e.rehomed, + ).length, + rehomed: entries.filter((e) => e.rehomed).length, + removed: entries.filter((e) => e.current === null).length, + } + return { map, stats } +} diff --git a/packages/anatomy/src/curation/pipeline.ts b/packages/anatomy/src/curation/pipeline.ts index fab5116e..80792972 100644 --- a/packages/anatomy/src/curation/pipeline.ts +++ b/packages/anatomy/src/curation/pipeline.ts @@ -6,11 +6,19 @@ import type { } from '@faunosteo/domain' import { formatJson, formatMarkdown } from '../format' import { HEAD_VIEW_ID, MAIN_VIEW_ID } from '../legacy/importer' -import type { Anomaly, AssetRecord, ImportResult } from '../legacy/types' +import type { + Anomaly, + AssetRecord, + ImportResult, + LegacyIdMap, +} from '../legacy/types' import { applyChangeset, curatedIssues } from './apply' import { cleanedAsset, stripLegacyAnnotations } from './assets' import { renderChangelog } from './changelog' import { REVIEW_OVERLAY_DIR, renderReviewOverlay } from './overlay' +import { buildReportMigrationMap } from './migration-map' +import { renderAppReviewDrawing } from './app-review' +import { sha256Hex } from '../legacy/ids' import { renderReviewReport } from './review-report' import { ASSET_CHANGE_ID, @@ -44,6 +52,7 @@ export interface DraftResult { document: AnatomicalSheetDocumentInput /** Legacy import the changeset was applied to. */ baseline: AnatomicalSheetDocumentInput + legacyIdMap: LegacyIdMap records: ChangeRecord[] changes: ChangeSummary[] assets: AssetRecord[] @@ -116,6 +125,7 @@ export function buildEquineDraft(input: DraftInput): DraftResult { return { document: result.document, baseline, + legacyIdMap: input.importResult.legacyIdMap, records: result.records, changes: changes.map(changeSummary), assets: [asset], @@ -142,18 +152,66 @@ function reviewOverlays(draft: DraftResult): Record { return files } +export const SHEET_REF_FILE = 'sheet-ref.json' +export const MIGRATION_MAP_FILE = 'report-migration-map.json' + +/** What a report references: the sheet and the exact document bytes. */ +function sheetRef(draft: DraftResult, documentJson: string) { + return { + sheetId: draft.sheetId, + versionId: null, + documentSha256: sha256Hex(documentJson), + } +} + +/** The application's own rendering of each view, for the visual check. */ +function appReviewDrawings(draft: DraftResult): Record { + const files: Record = {} + for (const view of draft.document.views) { + files[`${REVIEW_OVERLAY_DIR}/app-${view.id}.svg`] = renderAppReviewDrawing({ + cleanedSvg: draft.cleanedSvg, + document: draft.document, + viewId: view.id, + }) + } + return files +} + /** Text artifacts of the draft folder, keyed by file name. */ export async function renderDraftArtifacts( draft: DraftResult, legacyAnomalies: readonly Anomaly[], ): Promise> { const documentJson = await formatJson(draft.document) - const changelog = renderChangelog(draft, draft.statsBefore, draft.statsAfter) + const ref = sheetRef(draft, documentJson) + const migration = buildReportMigrationMap({ + baseline: draft.baseline as Record, + final: draft.document as Record, + legacyIdMap: draft.legacyIdMap, + records: draft.records, + sheet: ref, + mainViewId: MAIN_VIEW_ID, + }) + const changelog = renderChangelog( + draft, + draft.statsBefore, + draft.statsAfter, + migration.stats, + ) const review = renderReviewReport({ ...draft, legacyAnomalies }) return { 'document.json': documentJson, 'assets.json': await formatJson(draft.assets), + [SHEET_REF_FILE]: await formatJson({ + sheet_id: ref.sheetId, + version_id: ref.versionId, + document_sha256: ref.documentSha256, + schema_version: draft.document.schema_version, + species_id: draft.document.species_id, + }), + [MIGRATION_MAP_FILE]: await formatJson(migration.map), ...reviewOverlays(draft), + ...appReviewDrawings(draft), 'CHANGELOG.md': await formatMarkdown(changelog), 'REVIEW-REPORT.md': await formatMarkdown(review), [DRAFT_SEED_SQL_FILE]: renderDraftSeedSql({ diff --git a/packages/anatomy/src/index.ts b/packages/anatomy/src/index.ts index 71ee5d44..a1c19c8f 100644 --- a/packages/anatomy/src/index.ts +++ b/packages/anatomy/src/index.ts @@ -1,2 +1,3 @@ export * from './legacy' export * from './curation' +export * from './render' diff --git a/packages/anatomy/src/render/dom.ts b/packages/anatomy/src/render/dom.ts new file mode 100644 index 00000000..bce792cc --- /dev/null +++ b/packages/anatomy/src/render/dom.ts @@ -0,0 +1,38 @@ +import type { LayerElement } from './layer' + +/** + * Materialises a layer tree with any DOM implementation (browser document, + * xmldom in the pipeline). Only the handful of methods used are required, + * so this module compiles without the DOM lib. + */ + +export const SVG_NS = 'http://www.w3.org/2000/svg' + +export interface MinimalNode { + appendChild(child: MinimalNode): unknown +} + +export interface MinimalElement extends MinimalNode { + setAttribute(name: string, value: string): void +} + +export interface MinimalDocument { + createElementNS(ns: string, tag: string): MinimalElement + createTextNode(text: string): MinimalNode +} + +export function createLayerElement( + doc: MinimalDocument, + node: LayerElement, +): MinimalElement { + const element = doc.createElementNS(SVG_NS, node.tag) + for (const [name, value] of Object.entries(node.attrs)) { + element.setAttribute(name, value) + } + if (node.text !== undefined) + element.appendChild(doc.createTextNode(node.text)) + for (const child of node.children) { + element.appendChild(createLayerElement(doc, child)) + } + return element +} diff --git a/packages/anatomy/src/render/index.ts b/packages/anatomy/src/render/index.ts new file mode 100644 index 00000000..96b61d67 --- /dev/null +++ b/packages/anatomy/src/render/index.ts @@ -0,0 +1,22 @@ +export { + DETAIL_VIEW_STYLE, + FALLBACK_COLOR, + LAYER_ATTRIBUTE, + LAYER_NAME, + MAIN_VIEW_STYLE, + renderAnnotationLayer, + styleForView, + viewBoxOf, + type AnnotationState, + type LayerElement, + type LayerInput, + type MarkerStyle, +} from './layer' +export { + createLayerElement, + SVG_NS, + type MinimalDocument, + type MinimalElement, + type MinimalNode, +} from './dom' +export { serializeLayer } from './serialize' diff --git a/packages/anatomy/src/render/layer.ts b/packages/anatomy/src/render/layer.ts new file mode 100644 index 00000000..a561d17d --- /dev/null +++ b/packages/anatomy/src/render/layer.ts @@ -0,0 +1,261 @@ +import type { + AnatomicalSheetDocumentInput, + Geometry, + SheetView, +} from '@faunosteo/domain' + +/** + * Annotation layer of one view, as pure data: the SVG elements the + * application draws over the sheet's drawing, reproducing the legacy + * markers (transparent hitbox + visible twin per point, filled polygon per + * spine zone, dashed outline per detail trigger). The elements carry the + * `data-anno-*` attributes the click delegation, the tooltip and the CSS + * states read, so the drawing itself needs no annotation element at all. + * No DOM here: `dom.ts` materialises the tree, `serialize.ts` prints it. + */ + +export interface LayerElement { + tag: 'g' | 'circle' | 'polygon' | 'path' | 'title' + attrs: Record + children: LayerElement[] + text?: string +} + +/** Visual constants of the legacy markers, per view kind. */ +export interface MarkerStyle { + /** Visible circle radius = hitbox radius − inset (34→22, 30→18, 27→15). */ + visibleInset: number + visibleFillOpacity: number + visibleStroke: string + visibleStrokeWidth: number + zoneFillOpacity: number + zoneStrokeWidth: number + triggerFillOpacity: number + triggerStrokeWidth: number + triggerDash: string +} + +const BASE_STYLE: Omit = { + visibleInset: 12, + visibleStroke: '#000', + visibleStrokeWidth: 1.5, + zoneFillOpacity: 0.3, + zoneStrokeWidth: 2, + triggerFillOpacity: 0.06, + triggerStrokeWidth: 2, + triggerDash: '8,4', +} + +export const MAIN_VIEW_STYLE: MarkerStyle = { + ...BASE_STYLE, + visibleFillOpacity: 0.65, +} +export const DETAIL_VIEW_STYLE: MarkerStyle = { + ...BASE_STYLE, + visibleFillOpacity: 0.5, +} + +/** When neither the annotation nor its category names a colour. */ +export const FALLBACK_COLOR = '#888888' + +export const LAYER_ATTRIBUTE = 'data-layer' +export const LAYER_NAME = 'annotations' + +export type AnnotationState = 'current' + +export interface LayerInput { + document: AnatomicalSheetDocumentInput + viewId: string + /** Annotation id → state, applied as `data-state`. */ + states?: ReadonlyMap +} + +type Annotation = AnatomicalSheetDocumentInput['annotations'][number] + +export function styleForView(view: Pick): MarkerStyle { + return view.kind === 'main' ? MAIN_VIEW_STYLE : DETAIL_VIEW_STYLE +} + +function el( + tag: LayerElement['tag'], + attrs: Record, + children: LayerElement[] = [], +): LayerElement { + return { tag, attrs, children } +} + +function title(text: string): LayerElement { + return { tag: 'title', attrs: {}, children: [], text } +} + +function geometryAttrs( + geometry: Geometry, +): [LayerElement['tag'], Record] { + switch (geometry.type) { + case 'circle': + return [ + 'circle', + { + cx: String(geometry.cx), + cy: String(geometry.cy), + r: String(geometry.r), + }, + ] + case 'polygon': + return [ + 'polygon', + { points: geometry.points.map(([x, y]) => `${x},${y}`).join(' ') }, + ] + case 'path': + return ['path', { d: geometry.d }] + } +} + +function colorOf( + a: Annotation, + categories: Map, +): string { + return a.color ?? categories.get(a.category_id) ?? FALLBACK_COLOR +} + +/** Attributes shared by every element of one annotation. */ +function dataAttrs( + a: Annotation, + input: LayerInput, + viewName: string, +): Record { + const attrs: Record = { + 'data-anno-id': a.id, + 'data-anno-kind': a.kind, + 'data-anno-lateral': a.laterality, + } + if (a.kind === 'detail_trigger') { + attrs['data-anno-opens-view'] = a.opens_view_id + attrs['data-anno-name-fr'] = a.name?.fr ?? viewName + attrs['data-anno-name-en'] = a.name?.en ?? viewName + } else { + attrs['data-anno-name-fr'] = a.name.fr + attrs['data-anno-name-en'] = a.name.en + if (a.finding_zone_id) attrs['data-anno-zone'] = a.finding_zone_id + if (a.vertebral_region_code) + attrs['data-anno-region'] = a.vertebral_region_code + } + const state = input.states?.get(a.id) + if (state) attrs['data-state'] = state + return attrs +} + +function pointElements( + geometry: Extract, + color: string, + style: MarkerStyle, + data: Record, + label: string, +): LayerElement[] { + const hitbox = el( + 'circle', + { + ...geometryAttrs(geometry)[1], + fill: 'transparent', + 'pointer-events': 'all', + style: 'cursor:pointer', + ...data, + }, + [title(label)], + ) + const visible = el( + 'circle', + { + cx: String(geometry.cx), + cy: String(geometry.cy), + r: String(Math.max(2, geometry.r - style.visibleInset)), + fill: color, + 'fill-opacity': String(style.visibleFillOpacity), + stroke: style.visibleStroke, + 'stroke-width': String(style.visibleStrokeWidth), + 'pointer-events': 'none', + ...data, + }, + [title(label)], + ) + return [hitbox, visible] +} + +function shapeElement( + geometry: Geometry, + color: string, + visual: Record, + data: Record, + label: string, +): LayerElement { + const [tag, attrs] = geometryAttrs(geometry) + return el(tag, { ...attrs, fill: color, stroke: color, ...visual, ...data }, [ + title(label), + ]) +} + +function annotationElements( + a: Annotation, + input: LayerInput, + style: MarkerStyle, + categories: Map, + viewName: string, +): LayerElement[] { + if (!a.geometry) return [] + const color = colorOf(a, categories) + const data = dataAttrs(a, input, viewName) + const label = `${data['data-anno-name-fr']} / ${data['data-anno-name-en']}` + if (a.kind === 'detail_trigger') { + const visual = { + 'fill-opacity': String(style.triggerFillOpacity), + 'stroke-width': String(style.triggerStrokeWidth), + 'stroke-dasharray': style.triggerDash, + 'pointer-events': 'all', + style: 'cursor:pointer', + class: 'detail-zone', + } + return [shapeElement(a.geometry, color, visual, data, label)] + } + if (a.geometry.type === 'circle') { + return pointElements(a.geometry, color, style, data, label) + } + const visual = { + 'fill-opacity': String(style.zoneFillOpacity), + 'stroke-width': String(style.zoneStrokeWidth), + 'pointer-events': 'all', + style: 'cursor:pointer', + } + return [shapeElement(a.geometry, color, visual, data, label)] +} + +/** The layer `` of one view: every annotation of that view, in document order. */ +export function renderAnnotationLayer(input: LayerInput): LayerElement { + const { document, viewId } = input + const view = document.views.find((v) => v.id === viewId) + if (!view) throw new Error(`unknown view "${viewId}"`) + const style = styleForView(view) + const categories = new Map( + document.categories.map((c) => [c.id, c.color ?? null]), + ) + const viewNames = new Map(document.views.map((v) => [v.id, v.name.fr])) + const children = document.annotations + .filter((a) => a.view_id === viewId) + .flatMap((a) => { + const opened = + a.kind === 'detail_trigger' + ? (viewNames.get(a.opens_view_id) ?? '') + : '' + return annotationElements(a, input, style, categories, opened) + }) + return el( + 'g', + { [LAYER_ATTRIBUTE]: LAYER_NAME, 'data-view-id': viewId }, + children, + ) +} + +/** `viewBox` attribute value the view renders with, or null for the asset's own. */ +export function viewBoxOf(view: SheetView): string | null { + const box = view.view_box + return box ? `${box.min_x} ${box.min_y} ${box.width} ${box.height}` : null +} diff --git a/packages/anatomy/src/render/serialize.ts b/packages/anatomy/src/render/serialize.ts new file mode 100644 index 00000000..a17600e4 --- /dev/null +++ b/packages/anatomy/src/render/serialize.ts @@ -0,0 +1,25 @@ +import type { LayerElement } from './layer' + +/** Serialises a layer tree to SVG text (review drawings, tests). */ + +function escape(value: string): string { + return value + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') +} + +export function serializeLayer(node: LayerElement, indent = ''): string { + const attrs = Object.entries(node.attrs) + .map(([k, v]) => ` ${k}="${escape(v)}"`) + .join('') + if (node.text !== undefined) { + return `${indent}<${node.tag}${attrs}>${escape(node.text)}` + } + if (node.children.length === 0) return `${indent}<${node.tag}${attrs}/>` + const inner = node.children + .map((child) => serializeLayer(child, `${indent} `)) + .join('\n') + return `${indent}<${node.tag}${attrs}>\n${inner}\n${indent}` +} diff --git a/packages/anatomy/tests/curation.migration-map.test.ts b/packages/anatomy/tests/curation.migration-map.test.ts new file mode 100644 index 00000000..49d3dd45 --- /dev/null +++ b/packages/anatomy/tests/curation.migration-map.test.ts @@ -0,0 +1,183 @@ +import { ReportMigrationMapSchema } from '@faunosteo/domain' +import { beforeAll, describe, expect, it } from 'vitest' +import { + applyChangeset, + buildReportMigrationMap, + type DraftResult, + type ImportResult, +} from '../src' +import { changesetOf, MINI_REFERENCES, miniSheet } from './fixtures/mini-sheet' +import { runDraft } from './helpers' + +const SHEET = { + sheetId: 'sheet', + versionId: null, + documentSha256: 'f'.repeat(64), +} + +describe('report migration map on the real draft', () => { + let result: ImportResult + let draft: DraftResult + let map: ReturnType['map'] + let stats: ReturnType['stats'] + + beforeAll(async () => { + ;({ result, draft } = await runDraft()) + ;({ map, stats } = buildReportMigrationMap({ + baseline: draft.baseline as Record, + final: draft.document as Record, + legacyIdMap: draft.legacyIdMap, + records: draft.records, + sheet: SHEET, + mainViewId: 'main', + })) + }) + + it('is a valid map covering every legacy node, with the expected fates', () => { + expect(ReportMigrationMapSchema.parse(map)).toBeTruthy() + expect(stats).toEqual({ + nodes: 792, + identical: 571, + remapped: 180, + rehomed: 7, + removed: 34, + }) + expect(Object.keys(map.finding_paths)).toHaveLength(792) + }) + + it('maps every legacy annotation with its legacy labels and the views', () => { + expect(Object.keys(map.annotations)).toHaveLength(27) + expect(map.annotations['point-mpbwtst0']).toEqual({ + id: 'hip', + name: { fr: 'Hanche (coxo-fémorale)', en: 'Hip joint' }, + }) + expect(map.annotations['zone-mpby55kd']).toEqual({ + id: 'head-trigger', + name: { fr: '', en: '' }, + }) + expect(map.views).toEqual({ head: 'head' }) + expect(map.main_view_id).toBe('main') + expect(result.legacyIdMap.annotations['point-mpbwtst0']).toBe('hip') + }) + + it('every target path exists in the draft; identical, renamed, re-homed and removed cases', () => { + const final = new Set() + for (const zone of draft.document.finding_zones) { + const walk = ( + nodes: readonly { id: string; children?: readonly unknown[] }[], + prefix: string, + ) => { + for (const n of nodes) { + final.add(`${prefix}/${n.id}`) + walk((n.children ?? []) as never, `${prefix}/${n.id}`) + } + } + walk(zone.categories as never, zone.id) + } + for (const target of Object.values(map.finding_paths)) { + if (target !== null) expect(final.has(target), target).toBe(true) + } + expect( + map.finding_paths['hip/hip-dysfunctions/articular/restriction-flexion'], + ).toBe('hip/hip-dysfunctions/articular/restriction-flexion') + expect( + map.finding_paths[ + 'cervical/cervical-observations/stumbling-proprioceptive' + ], + ).toBe('cervical/cervical-consultation-reasons/stumbling-proprioceptive') + expect( + map.finding_paths[ + 'sacroiliac/sacroiliac-dysfunctions/muscular/sacrotuberous-tension' + ], + ).toBe('sacroiliac/sacroiliac-dysfunctions/muscular/sacrotuberous-ligament') + expect( + map.finding_paths['sphenoid/ssb-dysfunctions/sutures/sphenopetrosal'], + ).toBe('sphenoid/sphenoid-dysfunctions/sutures/sphenopetrosal') + expect( + map.finding_paths['ssb/ssb-dysfunctions/sutures/sphenozygomatic'], + ).toBeNull() + expect( + map.finding_paths['frontal/frontal-dysfunctions/sutures/frontozygomatic'], + ).toBeNull() + }) +}) + +describe('report migration map replay on a synthetic changeset', () => { + function mapOf(ops: Parameters[0]) { + const baseline = miniSheet() + const result = applyChangeset(baseline, MINI_REFERENCES, changesetOf(ops)) + return buildReportMigrationMap({ + baseline: miniSheet() as never, + final: result.document as never, + legacyIdMap: { + views: { head: 'head' }, + annotations: { 'legacy-hip': 'hip' }, + categories: {}, + finding_nodes: {}, + assets: {}, + }, + records: result.records, + sheet: SHEET, + mainViewId: 'main', + }) + } + + it('follows a rename, a move and a removal, and a renamed annotation', () => { + const { map, stats } = mapOf([ + { + op: 'rename', + target: 'finding:hip/hip-dysfunctions/mobility', + id: 'motion', + }, + { + op: 'move', + target: 'finding:hip/hip-dysfunctions/motion/flexion', + to: 'finding:hip/anamnesis', + }, + { op: 'remove', target: 'finding:neck/neck-dysfunctions/vet' }, + { op: 'rename', target: 'annotation:hip', id: 'coxofemoral' }, + ]) + expect(map.finding_paths['hip/hip-dysfunctions/mobility/extension']).toBe( + 'hip/hip-dysfunctions/motion/extension', + ) + expect(map.finding_paths['hip/hip-dysfunctions/mobility/flexion']).toBe( + 'hip/anamnesis/flexion', + ) + expect(map.finding_paths['neck/neck-dysfunctions/vet']).toBeNull() + expect(map.finding_paths['neck/neck-dysfunctions/stiffness']).toBe( + 'neck/neck-dysfunctions/stiffness', + ) + expect(map.annotations['legacy-hip']!.id).toBe('coxofemoral') + expect(stats.removed).toBe(1) + }) + + it('re-homes a node whose category was replaced by another one holding the same path', () => { + const { map, stats } = mapOf([ + { + op: 'add', + target: 'zone:hip', + value: { + id: 'hip-new', + kind: 'dysfunction', + name: { fr: 'N', en: 'N' }, + children: [ + { + id: 'mobility', + name: { fr: 'M', en: 'M' }, + children: [{ id: 'flexion', name: { fr: 'F', en: 'F' } }], + }, + ], + }, + }, + { op: 'remove', target: 'finding:hip/hip-dysfunctions' }, + ]) + expect(map.finding_paths['hip/hip-dysfunctions/mobility/flexion']).toBe( + 'hip/hip-new/mobility/flexion', + ) + expect( + map.finding_paths['hip/hip-dysfunctions/mobility/extension'], + ).toBeNull() + expect(map.finding_paths['hip/hip-dysfunctions']).toBeNull() + expect(stats.rehomed).toBe(2) + }) +}) diff --git a/packages/anatomy/tests/render.layer.test.ts b/packages/anatomy/tests/render.layer.test.ts new file mode 100644 index 00000000..b3b91d73 --- /dev/null +++ b/packages/anatomy/tests/render.layer.test.ts @@ -0,0 +1,158 @@ +import { DOMParser } from '@xmldom/xmldom' +import { beforeAll, describe, expect, it } from 'vitest' +import { + createLayerElement, + renderAnnotationLayer, + serializeLayer, + styleForView, + type DraftResult, + type LayerElement, +} from '../src' +import { miniSheet } from './fixtures/mini-sheet' +import { runDraft } from './helpers' + +function flatten(node: LayerElement): LayerElement[] { + return [node, ...node.children.flatMap(flatten)] +} + +function byId(layer: LayerElement, id: string): LayerElement[] { + return flatten(layer).filter((n) => n.attrs['data-anno-id'] === id) +} + +describe('annotation layer on the real draft', () => { + let draft: DraftResult + beforeAll(async () => { + ;({ draft } = await runDraft()) + }) + + it('draws every annotation of the main view as the legacy pair, zone or trigger', () => { + const layer = renderAnnotationLayer({ + document: draft.document, + viewId: 'main', + }) + expect(layer.attrs).toEqual({ + 'data-layer': 'annotations', + 'data-view-id': 'main', + }) + const main = draft.document.annotations.filter((a) => a.view_id === 'main') + for (const a of main) { + const els = byId(layer, a.id) + if (a.kind === 'point') + expect(els.map((e) => e.tag)).toEqual(['circle', 'circle']) + else expect(els).toHaveLength(1) + } + const [hitbox, visible] = byId(layer, 'hip') + expect(hitbox!.attrs).toMatchObject({ + r: '34', + fill: 'transparent', + 'pointer-events': 'all', + 'data-anno-lateral': 'bilateral', + 'data-anno-zone': 'hip', + }) + expect(visible!.attrs).toMatchObject({ + r: '22', + fill: '#ff9500', + 'fill-opacity': '0.65', + stroke: '#000', + 'stroke-width': '1.5', + 'pointer-events': 'none', + }) + expect(hitbox!.children[0]).toMatchObject({ + tag: 'title', + text: 'Hanche (coxo-fémorale) / Hip joint', + }) + const [spine] = byId(layer, 'cervical') + expect(spine!.tag).toBe('polygon') + expect(spine!.attrs).toMatchObject({ + fill: '#e100ff', + 'fill-opacity': '0.3', + 'stroke-width': '2', + 'data-anno-region': 'C', + }) + const [trigger] = byId(layer, 'head-trigger') + expect(trigger!.attrs).toMatchObject({ + 'data-anno-kind': 'detail_trigger', + 'data-anno-opens-view': 'head', + 'stroke-dasharray': '8,4', + 'fill-opacity': '0.06', + class: 'detail-zone', + }) + expect(trigger!.attrs['data-anno-name-fr']).toBe( + 'Tête (vue latérale gauche)', + ) + }) + + it('uses the detail style, the annotation colour override and the view box on the head view', () => { + const layer = renderAnnotationLayer({ + document: draft.document, + viewId: 'head', + }) + const [c0c1Hit, c0c1Vis] = byId(layer, 'c0-c1') + expect(c0c1Hit!.attrs.r).toBe('27') + expect(c0c1Vis!.attrs).toMatchObject({ + r: '15', + fill: '#ff0000', + 'fill-opacity': '0.5', + }) + expect(byId(layer, 'atm')[1]!.attrs.fill).toBe('#ff8800') + expect(byId(layer, 'hyoid')[1]!.attrs.fill).toBe('#d507c4') + expect(byId(layer, 'parietal')[1]!.attrs.fill).toBe('#1baa08') + expect(styleForView(draft.document.views[1]!).visibleFillOpacity).toBe(0.5) + expect(flatten(layer).some((n) => n.attrs['data-anno-id'] === 'hip')).toBe( + false, + ) + }) + + it('applies states as data-state on both elements of a point', () => { + const states = new Map([['hip', 'current' as const]]) + const layer = renderAnnotationLayer({ + document: draft.document, + viewId: 'main', + states, + }) + expect( + byId(layer, 'hip').every((e) => e.attrs['data-state'] === 'current'), + ).toBe(true) + expect( + byId(layer, 'stifle').every((e) => e.attrs['data-state'] === undefined), + ).toBe(true) + }) + + it('materialises through a DOM and serialises to the same markup', () => { + const layer = renderAnnotationLayer({ + document: draft.document, + viewId: 'head', + }) + const doc = new DOMParser().parseFromString( + '', + 'image/svg+xml', + ) + const element = createLayerElement( + doc as never, + layer, + ) as unknown as Element + expect(element.getAttribute('data-layer')).toBe('annotations') + expect(element.getElementsByTagName('circle')).toHaveLength(18) + const text = serializeLayer(layer) + expect(text).toContain('') + expect(text).toContain('Appareil hyoïdien / Hyoid apparatus') + expect(text).not.toContain(' { + it('skips annotations without geometry and falls back to grey without any colour', () => { + const sheet = miniSheet() + const layer = renderAnnotationLayer({ document: sheet, viewId: 'main' }) + const ids = new Set( + flatten(layer) + .map((n) => n.attrs['data-anno-id']) + .filter(Boolean), + ) + expect(ids.has('hip')).toBe(true) + expect(byId(layer, 'hip')[1]!.attrs.fill).toBe('#888888') + expect(() => + renderAnnotationLayer({ document: sheet, viewId: 'nope' }), + ).toThrow('unknown view') + }) +}) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e3886774..61fdf406 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -20,6 +20,12 @@ importers: apps/app: dependencies: + '@faunosteo/anatomy': + specifier: workspace:* + version: link:../../packages/anatomy + '@faunosteo/domain': + specifier: workspace:* + version: link:../../packages/domain '@faunosteo/supabase': specifier: workspace:* version: link:../../packages/supabase diff --git a/supabase/seed/anatomical-sheets/equine/curation/changes.json b/supabase/seed/anatomical-sheets/equine/curation/changes.json index 9318802f..5e3ebb22 100644 --- a/supabase/seed/anatomical-sheets/equine/curation/changes.json +++ b/supabase/seed/anatomical-sheets/equine/curation/changes.json @@ -5597,6 +5597,69 @@ "value": "to_confirm" } ] + }, + { + "id": "CHG-045", + "level": "A", + "kind": "technical", + "title": { + "fr": "Couleurs des marqueurs portées par le document", + "en": "Marker colours carried by the document" + }, + "rationale": "Les marqueurs étaient des éléments des fichiers SVG historiques, colorés un par un. L'application les dessine désormais à partir du document : chaque catégorie reçoit la couleur que les fichiers lui donnaient (articulations #ff9500, os #a41e65, charnières #ff0000, os du crâne #1baa08, segments vertébraux #e100ff) ; les trois nuances propres à la vue tête (ATM et SSB #ff8800, hyoïde #d507c4) restent des surcharges d'annotation. Aucun changement d'apparence.", + "reference_ids": [ + "legacy-catalog" + ], + "ops": [ + { + "op": "set", + "target": "category:articulations", + "field": "color", + "value": "#ff9500" + }, + { + "op": "set", + "target": "category:os", + "field": "color", + "value": "#a41e65" + }, + { + "op": "set", + "target": "category:charnieres-vertebrales", + "field": "color", + "value": "#ff0000" + }, + { + "op": "set", + "target": "category:zone-colonne", + "field": "color", + "value": "#e100ff" + }, + { + "op": "set", + "target": "category:cadrans-du-crane", + "field": "color", + "value": "#1baa08" + }, + { + "op": "set", + "target": "annotation:atm", + "field": "color", + "value": "#ff8800" + }, + { + "op": "set", + "target": "annotation:ssb", + "field": "color", + "value": "#ff8800" + }, + { + "op": "set", + "target": "annotation:hyoid", + "field": "color", + "value": "#d507c4" + } + ] } ] } \ No newline at end of file diff --git a/supabase/seed/anatomical-sheets/equine/draft/CHANGELOG.md b/supabase/seed/anatomical-sheets/equine/draft/CHANGELOG.md index 3572963b..2f60acc1 100644 --- a/supabase/seed/anatomical-sheets/equine/draft/CHANGELOG.md +++ b/supabase/seed/anatomical-sheets/equine/draft/CHANGELOG.md @@ -32,6 +32,16 @@ Niveaux : A = erreur démontrée, B = amélioration étayée, C = point incertai | Nœuds cités | 0 | 83 | | Régions vertébrales avec plage documentée | 0 | 3 | +## Migration des bilans v2 + +| Nœuds | Nombre | +| ---------------------------------------------------------- | ------ | +| Nœuds du catalogue historique | 792 | +| Chemin identique | 571 | +| Chemin renommé ou déplacé (suivi des renommages) | 180 | +| Relogé sous une autre catégorie (correspondance unique) | 7 | +| Retiré : le bilan garde le constat avec ses libellés figés | 34 | + ## Niveau A : erreurs démontrées | Changement | Objet | Avant | Après | Nature | Justification | Références | Confirmation requise | @@ -354,6 +364,14 @@ Niveaux : A = erreur démontrée, B = amélioration étayée, C = point incertai | `CHG-028` Noms de muscles alignés sur la NAV | `finding:elbow/elbow-dysfunctions/muscular/biceps-brachialis-tension.name.en` | Biceps / brachialis tension | Biceps brachii / brachialis tension | Terminologie | « Sus-épineux / sous-épineux » est l'ancienne nomenclature (OQLF) : M. supraspinatus / infraspinatus. Les multifides sont pluriels (Mm. multifidi). La NAV écrit M. fibularis [peron(a)eus] tertius, « fibularis » en premier ; « péronier tiers » est un calque. L'anglais « cranial tibial » devient « tibialis cranialis » comme les autres libellés latins. Au coude, « biceps / brachial » désigne deux muscles (biceps brachii, brachialis) : le libellé le dit. Les ischio-jambiers du cheval sont le biceps fémoral, le semi-tendineux et le semi-membraneux. | `nav-2017`, `oqlf-supraepineux`, `imaios-fibularis` | non | | `CHG-028` Noms de muscles alignés sur la NAV | `finding:stifle/stifle-dysfunctions/muscular/hamstrings-tension.name.fr` | Tension des ischio-jambiers | Tension des ischio-jambiers (biceps fémoral, semi-tendineux, semi-membraneux) | Terminologie | « Sus-épineux / sous-épineux » est l'ancienne nomenclature (OQLF) : M. supraspinatus / infraspinatus. Les multifides sont pluriels (Mm. multifidi). La NAV écrit M. fibularis [peron(a)eus] tertius, « fibularis » en premier ; « péronier tiers » est un calque. L'anglais « cranial tibial » devient « tibialis cranialis » comme les autres libellés latins. Au coude, « biceps / brachial » désigne deux muscles (biceps brachii, brachialis) : le libellé le dit. Les ischio-jambiers du cheval sont le biceps fémoral, le semi-tendineux et le semi-membraneux. | `nav-2017`, `oqlf-supraepineux`, `imaios-fibularis` | non | | `CHG-028` Noms de muscles alignés sur la NAV | `finding:stifle/stifle-dysfunctions/muscular/hamstrings-tension.name.en` | Hamstring tension | Hamstrings tension (biceps femoris, semitendinosus, semimembranosus) | Terminologie | « Sus-épineux / sous-épineux » est l'ancienne nomenclature (OQLF) : M. supraspinatus / infraspinatus. Les multifides sont pluriels (Mm. multifidi). La NAV écrit M. fibularis [peron(a)eus] tertius, « fibularis » en premier ; « péronier tiers » est un calque. L'anglais « cranial tibial » devient « tibialis cranialis » comme les autres libellés latins. Au coude, « biceps / brachial » désigne deux muscles (biceps brachii, brachialis) : le libellé le dit. Les ischio-jambiers du cheval sont le biceps fémoral, le semi-tendineux et le semi-membraneux. | `nav-2017`, `oqlf-supraepineux`, `imaios-fibularis` | non | +| `CHG-045` Couleurs des marqueurs portées par le document | `category:articulations.color` | null | #ff9500 | Technique | Les marqueurs étaient des éléments des fichiers SVG historiques, colorés un par un. L'application les dessine désormais à partir du document : chaque catégorie reçoit la couleur que les fichiers lui donnaient (articulations #ff9500, os #a41e65, charnières #ff0000, os du crâne #1baa08, segments vertébraux #e100ff) ; les trois nuances propres à la vue tête (ATM et SSB #ff8800, hyoïde #d507c4) restent des surcharges d'annotation. Aucun changement d'apparence. | `legacy-catalog` | non | +| `CHG-045` Couleurs des marqueurs portées par le document | `category:os.color` | null | #a41e65 | Technique | Les marqueurs étaient des éléments des fichiers SVG historiques, colorés un par un. L'application les dessine désormais à partir du document : chaque catégorie reçoit la couleur que les fichiers lui donnaient (articulations #ff9500, os #a41e65, charnières #ff0000, os du crâne #1baa08, segments vertébraux #e100ff) ; les trois nuances propres à la vue tête (ATM et SSB #ff8800, hyoïde #d507c4) restent des surcharges d'annotation. Aucun changement d'apparence. | `legacy-catalog` | non | +| `CHG-045` Couleurs des marqueurs portées par le document | `category:charnieres-vertebrales.color` | null | #ff0000 | Technique | Les marqueurs étaient des éléments des fichiers SVG historiques, colorés un par un. L'application les dessine désormais à partir du document : chaque catégorie reçoit la couleur que les fichiers lui donnaient (articulations #ff9500, os #a41e65, charnières #ff0000, os du crâne #1baa08, segments vertébraux #e100ff) ; les trois nuances propres à la vue tête (ATM et SSB #ff8800, hyoïde #d507c4) restent des surcharges d'annotation. Aucun changement d'apparence. | `legacy-catalog` | non | +| `CHG-045` Couleurs des marqueurs portées par le document | `category:zone-colonne.color` | null | #e100ff | Technique | Les marqueurs étaient des éléments des fichiers SVG historiques, colorés un par un. L'application les dessine désormais à partir du document : chaque catégorie reçoit la couleur que les fichiers lui donnaient (articulations #ff9500, os #a41e65, charnières #ff0000, os du crâne #1baa08, segments vertébraux #e100ff) ; les trois nuances propres à la vue tête (ATM et SSB #ff8800, hyoïde #d507c4) restent des surcharges d'annotation. Aucun changement d'apparence. | `legacy-catalog` | non | +| `CHG-045` Couleurs des marqueurs portées par le document | `category:cadrans-du-crane.color` | null | #1baa08 | Technique | Les marqueurs étaient des éléments des fichiers SVG historiques, colorés un par un. L'application les dessine désormais à partir du document : chaque catégorie reçoit la couleur que les fichiers lui donnaient (articulations #ff9500, os #a41e65, charnières #ff0000, os du crâne #1baa08, segments vertébraux #e100ff) ; les trois nuances propres à la vue tête (ATM et SSB #ff8800, hyoïde #d507c4) restent des surcharges d'annotation. Aucun changement d'apparence. | `legacy-catalog` | non | +| `CHG-045` Couleurs des marqueurs portées par le document | `annotation:atm.color` | null | #ff8800 | Technique | Les marqueurs étaient des éléments des fichiers SVG historiques, colorés un par un. L'application les dessine désormais à partir du document : chaque catégorie reçoit la couleur que les fichiers lui donnaient (articulations #ff9500, os #a41e65, charnières #ff0000, os du crâne #1baa08, segments vertébraux #e100ff) ; les trois nuances propres à la vue tête (ATM et SSB #ff8800, hyoïde #d507c4) restent des surcharges d'annotation. Aucun changement d'apparence. | `legacy-catalog` | non | +| `CHG-045` Couleurs des marqueurs portées par le document | `annotation:ssb.color` | null | #ff8800 | Technique | Les marqueurs étaient des éléments des fichiers SVG historiques, colorés un par un. L'application les dessine désormais à partir du document : chaque catégorie reçoit la couleur que les fichiers lui donnaient (articulations #ff9500, os #a41e65, charnières #ff0000, os du crâne #1baa08, segments vertébraux #e100ff) ; les trois nuances propres à la vue tête (ATM et SSB #ff8800, hyoïde #d507c4) restent des surcharges d'annotation. Aucun changement d'apparence. | `legacy-catalog` | non | +| `CHG-045` Couleurs des marqueurs portées par le document | `annotation:hyoid.color` | null | #d507c4 | Technique | Les marqueurs étaient des éléments des fichiers SVG historiques, colorés un par un. L'application les dessine désormais à partir du document : chaque catégorie reçoit la couleur que les fichiers lui donnaient (articulations #ff9500, os #a41e65, charnières #ff0000, os du crâne #1baa08, segments vertébraux #e100ff) ; les trois nuances propres à la vue tête (ATM et SSB #ff8800, hyoïde #d507c4) restent des surcharges d'annotation. Aucun changement d'apparence. | `legacy-catalog` | non | ## Niveau B : améliorations étayées (confirmation requise) diff --git a/supabase/seed/anatomical-sheets/equine/draft/REVIEW-REPORT.md b/supabase/seed/anatomical-sheets/equine/draft/REVIEW-REPORT.md index 44ed227d..eeaa4814 100644 --- a/supabase/seed/anatomical-sheets/equine/draft/REVIEW-REPORT.md +++ b/supabase/seed/anatomical-sheets/equine/draft/REVIEW-REPORT.md @@ -57,6 +57,7 @@ L'import historique signale 27 anomalies, dont 21 à valider (détail dans `lega - `CHG-021` Termes NAV sur la colonne : vertèbres caudales, jonction thoraco-lombaire (niveau A, Terminologie, confirmation requise : non). La NAV 2017 nomme « Vertebrae caudales [coccygeae] » : le terme premier est « caudales », l'anglais « Coccygeal » devient « Caudal vertebrae » (le français l'était déjà). « Dorso-lombaire » vient de l'ancienne appellation « vertèbres dorsales » ; le terme courant est « thoraco-lombaire ». Les libellés anglais des charnières reçoivent le mot « junction » (usage vétérinaire anglophone courant) ; « hinge » est un calque. Seules C0-C1 (Articulatio atlantooccipitalis) et L6-S1 (Articulatio lumbosacralis) sont des articulations nommées par la NAV, C7-T1 et T18-L1 sont des descripteurs régionaux. Casse de phrase uniforme sur les libellés anglais des segments. Objets : `zone:caudal.name.en`, `annotation:caudal.name.en`, `zone:t18-l1.name.fr`, `annotation:t18-l1.name.fr`, `zone:t18-l1.name.en`, `annotation:t18-l1.name.en`, `zone:c7-t1.name.en`, `annotation:c7-t1.name.en`, `zone:l6-s1.name.en`, `annotation:l6-s1.name.en`, `category:charnieres-vertebrales.name.en`, `zone:cervical.name.en`, `annotation:cervical.name.en`, `zone:thoracic.name.en`, `annotation:thoracic.name.en`, `zone:lumbar.name.en`, `annotation:lumbar.name.en`, `zone:sacral.name.en`, `annotation:sacral.name.en`. Références : `nav-2017`, `imaios-caudal`, `sisson-1910`. - `CHG-027` Libellés du document et des vues (niveau A, Correction, confirmation requise : non). La vue principale est un profil gauche du cheval (tête à gauche, flanc gauche visible) ; « Vue générale » ne le disait pas. La vue tête est le recadrage de ce même dessin. La description du document nomme l'espèce. Objets : `document.description.fr`, `document.description.en`, `view:main.name.fr`, `view:main.name.en`, `view:head.name.fr`, `view:head.name.en`, `category:zone-colonne.name.fr`, `category:zone-colonne.name.en`. Références : `legacy-catalog`. - `CHG-028` Noms de muscles alignés sur la NAV (niveau A, Terminologie, confirmation requise : non). « Sus-épineux / sous-épineux » est l'ancienne nomenclature (OQLF) : M. supraspinatus / infraspinatus. Les multifides sont pluriels (Mm. multifidi). La NAV écrit M. fibularis [peron(a)eus] tertius, « fibularis » en premier ; « péronier tiers » est un calque. L'anglais « cranial tibial » devient « tibialis cranialis » comme les autres libellés latins. Au coude, « biceps / brachial » désigne deux muscles (biceps brachii, brachialis) : le libellé le dit. Les ischio-jambiers du cheval sont le biceps fémoral, le semi-tendineux et le semi-membraneux. Objets : `finding:shoulder/shoulder-dysfunctions/muscular/supraspinatus-infraspinatus.name.fr`, `finding:cervical/cervical-dysfunctions/muscular/multifidus-cervicis.name.fr`, `finding:cervical/cervical-dysfunctions/muscular/multifidus-cervicis.name.en`, `finding:hock/hock-dysfunctions/muscular/peroneus-tertius.name.fr`, `finding:hock/hock-dysfunctions/muscular/peroneus-tertius.name.en`, `finding:hock/hock-dysfunctions/muscular/tibialis-cranialis.name.en`, `finding:elbow/elbow-dysfunctions/muscular/biceps-brachialis-tension.name.fr`, `finding:elbow/elbow-dysfunctions/muscular/biceps-brachialis-tension.name.en`, `finding:stifle/stifle-dysfunctions/muscular/hamstrings-tension.name.fr`, `finding:stifle/stifle-dysfunctions/muscular/hamstrings-tension.name.en`. Références : `nav-2017`, `oqlf-supraepineux`, `imaios-fibularis`. +- `CHG-045` Couleurs des marqueurs portées par le document (niveau A, Technique, confirmation requise : non). Les marqueurs étaient des éléments des fichiers SVG historiques, colorés un par un. L'application les dessine désormais à partir du document : chaque catégorie reçoit la couleur que les fichiers lui donnaient (articulations #ff9500, os #a41e65, charnières #ff0000, os du crâne #1baa08, segments vertébraux #e100ff) ; les trois nuances propres à la vue tête (ATM et SSB #ff8800, hyoïde #d507c4) restent des surcharges d'annotation. Aucun changement d'apparence. Objets : `category:articulations.color`, `category:os.color`, `category:charnieres-vertebrales.color`, `category:zone-colonne.color`, `category:cadrans-du-crane.color`, `annotation:atm.color`, `annotation:ssb.color`, `annotation:hyoid.color`. Références : `legacy-catalog`. ## 4. Ajouts diff --git a/supabase/seed/anatomical-sheets/equine/draft/document.json b/supabase/seed/anatomical-sheets/equine/draft/document.json index 02bb25f9..97cc4d87 100644 --- a/supabase/seed/anatomical-sheets/equine/draft/document.json +++ b/supabase/seed/anatomical-sheets/equine/draft/document.json @@ -419,7 +419,7 @@ "fr": "Articulations", "en": "Joints" }, - "color": null + "color": "#ff9500" }, { "id": "os", @@ -427,7 +427,7 @@ "fr": "Os", "en": "Bones" }, - "color": null + "color": "#a41e65" }, { "id": "charnieres-vertebrales", @@ -435,7 +435,7 @@ "fr": "Charnières vertébrales", "en": "Vertebral junctions" }, - "color": null + "color": "#ff0000" }, { "id": "zone-colonne", @@ -443,7 +443,7 @@ "fr": "Segments vertébraux", "en": "Vertebral segments" }, - "color": null + "color": "#e100ff" }, { "id": "cadrans-du-crane", @@ -451,7 +451,7 @@ "fr": "Os du crâne", "en": "Cranial bones" }, - "color": null + "color": "#1baa08" } ], "views": [ @@ -1025,7 +1025,8 @@ }, "finding_zone_id": "atm", "vertebral_region_code": null, - "review_status": "to_confirm" + "review_status": "to_confirm", + "color": "#ff8800" }, { "id": "ssb", @@ -1045,7 +1046,8 @@ }, "finding_zone_id": "ssb", "vertebral_region_code": null, - "review_status": "to_confirm" + "review_status": "to_confirm", + "color": "#ff8800" }, { "id": "hyoid", @@ -1065,7 +1067,8 @@ }, "finding_zone_id": "hyoid", "vertebral_region_code": null, - "review_status": "to_confirm" + "review_status": "to_confirm", + "color": "#d507c4" }, { "id": "c0-c1", diff --git a/supabase/seed/anatomical-sheets/equine/draft/equine_draft.sql b/supabase/seed/anatomical-sheets/equine/draft/equine_draft.sql index e3f277a5..209ddf37 100644 --- a/supabase/seed/anatomical-sheets/equine/draft/equine_draft.sql +++ b/supabase/seed/anatomical-sheets/equine/draft/equine_draft.sql @@ -442,7 +442,7 @@ select private.insert_sheet_draft( "fr": "Articulations", "en": "Joints" }, - "color": null + "color": "#ff9500" }, { "id": "os", @@ -450,7 +450,7 @@ select private.insert_sheet_draft( "fr": "Os", "en": "Bones" }, - "color": null + "color": "#a41e65" }, { "id": "charnieres-vertebrales", @@ -458,7 +458,7 @@ select private.insert_sheet_draft( "fr": "Charnières vertébrales", "en": "Vertebral junctions" }, - "color": null + "color": "#ff0000" }, { "id": "zone-colonne", @@ -466,7 +466,7 @@ select private.insert_sheet_draft( "fr": "Segments vertébraux", "en": "Vertebral segments" }, - "color": null + "color": "#e100ff" }, { "id": "cadrans-du-crane", @@ -474,7 +474,7 @@ select private.insert_sheet_draft( "fr": "Os du crâne", "en": "Cranial bones" }, - "color": null + "color": "#1baa08" } ], "views": [ @@ -1048,7 +1048,8 @@ select private.insert_sheet_draft( }, "finding_zone_id": "atm", "vertebral_region_code": null, - "review_status": "to_confirm" + "review_status": "to_confirm", + "color": "#ff8800" }, { "id": "ssb", @@ -1068,7 +1069,8 @@ select private.insert_sheet_draft( }, "finding_zone_id": "ssb", "vertebral_region_code": null, - "review_status": "to_confirm" + "review_status": "to_confirm", + "color": "#ff8800" }, { "id": "hyoid", @@ -1088,7 +1090,8 @@ select private.insert_sheet_draft( }, "finding_zone_id": "hyoid", "vertebral_region_code": null, - "review_status": "to_confirm" + "review_status": "to_confirm", + "color": "#d507c4" }, { "id": "c0-c1", @@ -8731,7 +8734,7 @@ from (select $equine_doc${ "fr": "Articulations", "en": "Joints" }, - "color": null + "color": "#ff9500" }, { "id": "os", @@ -8739,7 +8742,7 @@ from (select $equine_doc${ "fr": "Os", "en": "Bones" }, - "color": null + "color": "#a41e65" }, { "id": "charnieres-vertebrales", @@ -8747,7 +8750,7 @@ from (select $equine_doc${ "fr": "Charnières vertébrales", "en": "Vertebral junctions" }, - "color": null + "color": "#ff0000" }, { "id": "zone-colonne", @@ -8755,7 +8758,7 @@ from (select $equine_doc${ "fr": "Segments vertébraux", "en": "Vertebral segments" }, - "color": null + "color": "#e100ff" }, { "id": "cadrans-du-crane", @@ -8763,7 +8766,7 @@ from (select $equine_doc${ "fr": "Os du crâne", "en": "Cranial bones" }, - "color": null + "color": "#1baa08" } ], "views": [ @@ -9337,7 +9340,8 @@ from (select $equine_doc${ }, "finding_zone_id": "atm", "vertebral_region_code": null, - "review_status": "to_confirm" + "review_status": "to_confirm", + "color": "#ff8800" }, { "id": "ssb", @@ -9357,7 +9361,8 @@ from (select $equine_doc${ }, "finding_zone_id": "ssb", "vertebral_region_code": null, - "review_status": "to_confirm" + "review_status": "to_confirm", + "color": "#ff8800" }, { "id": "hyoid", @@ -9377,7 +9382,8 @@ from (select $equine_doc${ }, "finding_zone_id": "hyoid", "vertebral_region_code": null, - "review_status": "to_confirm" + "review_status": "to_confirm", + "color": "#d507c4" }, { "id": "c0-c1", diff --git a/supabase/seed/anatomical-sheets/equine/draft/report-migration-map.json b/supabase/seed/anatomical-sheets/equine/draft/report-migration-map.json new file mode 100644 index 00000000..c199d71f --- /dev/null +++ b/supabase/seed/anatomical-sheets/equine/draft/report-migration-map.json @@ -0,0 +1,997 @@ +{ + "schema_version": 1, + "sheet": { + "sheetId": "503dc301-a8b1-50d4-9e44-0919b2fc2916", + "versionId": null, + "documentSha256": "27c7383c445c73dc2001ebf4794a3ea63d416910bbbaa0d7848dd720de7c2660" + }, + "main_view_id": "main", + "views": { + "head": "head" + }, + "annotations": { + "point-mpbwrkp0": { + "id": "hind-fetlock", + "name": { + "fr": "Boulet post. (métatarso-phalangien)", + "en": "Hind fetlock" + } + }, + "point-mpbwsi9q": { + "id": "hock", + "name": { + "fr": "Jarret (tarsien)", + "en": "Hock" + } + }, + "point-mpbwt4fa": { + "id": "stifle", + "name": { + "fr": "Grasset (fémoro-tibial)", + "en": "Stifle" + } + }, + "point-mpbwtst0": { + "id": "hip", + "name": { + "fr": "Hanche (coxo-fémorale)", + "en": "Hip joint" + } + }, + "point-mpbwugty": { + "id": "sacroiliac", + "name": { + "fr": "Articulation Sacro-Iliaque", + "en": "Sacroiliac Joint" + } + }, + "point-mpbwv4xy": { + "id": "shoulder", + "name": { + "fr": "Épaule (scapulo-humérale)", + "en": "Shoulder joint" + } + }, + "point-mpbwvpvt": { + "id": "elbow", + "name": { + "fr": "Coude (huméro-radial)", + "en": "Elbow joint" + } + }, + "point-mpbwwaru": { + "id": "fore-fetlock", + "name": { + "fr": "Boulet ant. (métacarpo-phalangien)", + "en": "Fore fetlock" + } + }, + "point-mpbwwxvn": { + "id": "fore-sesamoids", + "name": { + "fr": "Sésamoïdes ant. (boulet)", + "en": "Forelimb Sesamoids" + } + }, + "point-mpbwxnb4": { + "id": "l6-s1", + "name": { + "fr": "Charnière L6-S1 (lombo-sacrée)", + "en": "L6-S1 (Lumbosacral)" + } + }, + "point-mpbwyd9i": { + "id": "t18-l1", + "name": { + "fr": "Charnière T18-L1 (dorso-lombaire)", + "en": "T18-L1 (Thoracolumbar)" + } + }, + "point-mpbwyyc9": { + "id": "c7-t1", + "name": { + "fr": "Charnière C7-T1 (cervico-thoracique)", + "en": "C7-T1 (Cervicothoracic)" + } + }, + "zone-mpbx00jq": { + "id": "caudal", + "name": { + "fr": "Vertèbres caudales", + "en": "Coccygeal Vertebrae" + } + }, + "zone-mpbx0xnp": { + "id": "sacral", + "name": { + "fr": "Vertèbres sacrales", + "en": "Sacral Vertebrae" + } + }, + "zone-mpbx1rm9": { + "id": "lumbar", + "name": { + "fr": "Vertèbres lombaires", + "en": "Lumbar Vertebrae" + } + }, + "zone-mpbx2rpe": { + "id": "thoracic", + "name": { + "fr": "Vertèbres thoraciques", + "en": "Thoracic Vertebrae" + } + }, + "zone-mpbx5hx2": { + "id": "cervical", + "name": { + "fr": "Vertèbres cervicales", + "en": "Cervical Vertebrae" + } + }, + "zone-mpby55kd": { + "id": "head-trigger", + "name": { + "fr": "", + "en": "" + } + }, + "point-mpbykomv": { + "id": "parietal", + "name": { + "fr": "Pariétal", + "en": "Parietal bone" + } + }, + "point-mpbylh35": { + "id": "frontal", + "name": { + "fr": "Frontal", + "en": "Frontal bone" + } + }, + "point-mpbymcln": { + "id": "sphenoid", + "name": { + "fr": "Sphénoïde", + "en": "Sphenoid" + } + }, + "point-mpbyn2k3": { + "id": "temporal", + "name": { + "fr": "Temporel", + "en": "Temporal" + } + }, + "point-mpbynls5": { + "id": "occipital", + "name": { + "fr": "Occipital", + "en": "Occipital" + } + }, + "point-mpbyo7zq": { + "id": "atm", + "name": { + "fr": "Articulation Temporo-Mandibulaire (ATM)", + "en": "Temporomandibular Joint (TMJ)" + } + }, + "point-mpbyphay": { + "id": "ssb", + "name": { + "fr": "Synchondrose Sphéno-Basilaire (SSB)", + "en": "Spheno-Basilar Synchondrosis (SBS)" + } + }, + "point-mpbyq841": { + "id": "hyoid", + "name": { + "fr": "Hyoïde", + "en": "Hyoid" + } + }, + "point-mpbyqxbg": { + "id": "c0-c1", + "name": { + "fr": "Charnière C0-C1 (occipito-atloïdienne)", + "en": "C0-C1 (Occipito-atlantal)" + } + } + }, + "finding_paths": { + "parietal/parietal-dysfunctions": "parietal/parietal-dysfunctions", + "parietal/parietal-dysfunctions/mobility": "parietal/parietal-dysfunctions/mobility", + "parietal/parietal-dysfunctions/mobility/flexion-external-rotation": "parietal/parietal-dysfunctions/mobility/flexion-external-rotation", + "parietal/parietal-dysfunctions/mobility/extension-internal-rotation": "parietal/parietal-dysfunctions/mobility/extension-internal-rotation", + "parietal/parietal-dysfunctions/mobility/global-restriction": "parietal/parietal-dysfunctions/mobility/global-restriction", + "parietal/parietal-dysfunctions/intraosseous": "parietal/parietal-dysfunctions/intraosseous", + "parietal/parietal-dysfunctions/intraosseous/squama-deformation": "parietal/parietal-dysfunctions/intraosseous/squama-deformation", + "parietal/parietal-dysfunctions/intraosseous/interparietal-compression": "parietal/parietal-dysfunctions/intraosseous/interparietal-compression", + "parietal/parietal-dysfunctions/sutures": "parietal/parietal-dysfunctions/sutures", + "parietal/parietal-dysfunctions/sutures/frontoparietal": "parietal/parietal-dysfunctions/sutures/frontoparietal", + "parietal/parietal-dysfunctions/sutures/parieto-occipital": "parietal/parietal-dysfunctions/sutures/parieto-occipital", + "parietal/parietal-dysfunctions/sutures/parieto-temporal": "parietal/parietal-dysfunctions/sutures/parieto-temporal", + "parietal/parietal-dysfunctions/sutures/sphenoparietal": "parietal/parietal-dysfunctions/sutures/sphenoparietal", + "parietal/parietal-dysfunctions/sutures/interparietal": "parietal/parietal-dysfunctions/sutures/sagittal", + "parietal/parietal-observations": "parietal/parietal-consultation-reasons", + "parietal/parietal-observations/behavior-change": "parietal/parietal-consultation-reasons/behavior-change", + "parietal/parietal-observations/behavior-change/head-touch-hypersensitivity": "parietal/parietal-consultation-reasons/behavior-change/head-touch-hypersensitivity", + "parietal/parietal-observations/behavior-change/new-irritability": "parietal/parietal-consultation-reasons/behavior-change/new-irritability", + "parietal/parietal-observations/post-trauma-head": "parietal/parietal-consultation-reasons/post-trauma-head", + "parietal/anamnesis": "parietal/anamnesis", + "parietal/anamnesis/trauma-direct": "parietal/anamnesis/trauma-direct", + "parietal/anamnesis/stress-context": "parietal/anamnesis/stress-context", + "parietal/anamnesis/posture-context": "parietal/anamnesis/posture-context", + "parietal/anamnesis/dental-context": "parietal/anamnesis/dental-context", + "parietal/anamnesis/post-veterinary": "parietal/anamnesis/post-veterinary", + "parietal/anamnesis/no-identified-cause": "parietal/anamnesis/no-identified-cause", + "frontal/frontal-dysfunctions": "frontal/frontal-dysfunctions", + "frontal/frontal-dysfunctions/mobility": "frontal/frontal-dysfunctions/mobility", + "frontal/frontal-dysfunctions/mobility/flexion-external-rotation": "frontal/frontal-dysfunctions/mobility/flexion-external-rotation", + "frontal/frontal-dysfunctions/mobility/extension-internal-rotation": "frontal/frontal-dysfunctions/mobility/extension-internal-rotation", + "frontal/frontal-dysfunctions/mobility/global-restriction": "frontal/frontal-dysfunctions/mobility/global-restriction", + "frontal/frontal-dysfunctions/intraosseous": "frontal/frontal-dysfunctions/intraosseous", + "frontal/frontal-dysfunctions/intraosseous/metopic-compression": "frontal/frontal-dysfunctions/intraosseous/interfrontal-compression", + "frontal/frontal-dysfunctions/intraosseous/squama-deformation": "frontal/frontal-dysfunctions/intraosseous/squama-deformation", + "frontal/frontal-dysfunctions/sutures": "frontal/frontal-dysfunctions/sutures", + "frontal/frontal-dysfunctions/sutures/frontoparietal": "frontal/frontal-dysfunctions/sutures/frontoparietal", + "frontal/frontal-dysfunctions/sutures/frontosphenoidal": "frontal/frontal-dysfunctions/sutures/frontosphenoidal", + "frontal/frontal-dysfunctions/sutures/frontonasal": "frontal/frontal-dysfunctions/sutures/frontonasal", + "frontal/frontal-dysfunctions/sutures/frontolacrimal": "frontal/frontal-dysfunctions/sutures/frontolacrimal", + "frontal/frontal-dysfunctions/sutures/frontozygomatic": null, + "frontal/frontal-dysfunctions/sutures/interfrontal": "frontal/frontal-dysfunctions/sutures/interfrontal", + "frontal/frontal-observations": "frontal/frontal-consultation-reasons", + "frontal/frontal-observations/behavior-change": "frontal/frontal-consultation-reasons/behavior-change", + "frontal/frontal-observations/behavior-change/head-touch-hypersensitivity": "frontal/frontal-consultation-reasons/behavior-change/head-touch-hypersensitivity", + "frontal/frontal-observations/behavior-change/new-irritability": "frontal/frontal-consultation-reasons/behavior-change/new-irritability", + "frontal/frontal-observations/head-rubbing": "frontal/frontal-consultation-reasons/head-rubbing", + "frontal/frontal-observations/frontal-relief-asymmetry": "frontal/frontal-consultation-reasons/frontal-relief-asymmetry", + "frontal/frontal-observations/post-trauma-head": "frontal/frontal-consultation-reasons/post-trauma-head", + "frontal/anamnesis": "frontal/anamnesis", + "frontal/anamnesis/trauma-direct": "frontal/anamnesis/trauma-direct", + "frontal/anamnesis/stress-context": "frontal/anamnesis/stress-context", + "frontal/anamnesis/posture-context": "frontal/anamnesis/posture-context", + "frontal/anamnesis/dental-context": "frontal/anamnesis/dental-context", + "frontal/anamnesis/post-veterinary": "frontal/anamnesis/post-veterinary", + "frontal/anamnesis/no-identified-cause": "frontal/anamnesis/no-identified-cause", + "sphenoid/ssb-dysfunctions": null, + "sphenoid/ssb-dysfunctions/physiological": null, + "sphenoid/ssb-dysfunctions/physiological/flexion": null, + "sphenoid/ssb-dysfunctions/physiological/extension": null, + "sphenoid/ssb-dysfunctions/physiological/torsion-right": null, + "sphenoid/ssb-dysfunctions/physiological/torsion-left": null, + "sphenoid/ssb-dysfunctions/physiological/sidebending-rotation-right": null, + "sphenoid/ssb-dysfunctions/physiological/sidebending-rotation-left": null, + "sphenoid/ssb-dysfunctions/traumatic": null, + "sphenoid/ssb-dysfunctions/traumatic/vertical-strain-superior": null, + "sphenoid/ssb-dysfunctions/traumatic/vertical-strain-inferior": null, + "sphenoid/ssb-dysfunctions/traumatic/lateral-strain-right": null, + "sphenoid/ssb-dysfunctions/traumatic/lateral-strain-left": null, + "sphenoid/ssb-dysfunctions/traumatic/compression": null, + "sphenoid/ssb-dysfunctions/intraosseous": "sphenoid/sphenoid-dysfunctions/intraosseous", + "sphenoid/ssb-dysfunctions/intraosseous/pre-post-sphenoid": null, + "sphenoid/ssb-dysfunctions/intraosseous/lesser-wings": null, + "sphenoid/ssb-dysfunctions/intraosseous/greater-wings": null, + "sphenoid/ssb-dysfunctions/sutures": "sphenoid/sphenoid-dysfunctions/sutures", + "sphenoid/ssb-dysfunctions/sutures/sphenopetrosal": "sphenoid/sphenoid-dysfunctions/sutures/sphenopetrosal", + "sphenoid/ssb-dysfunctions/sutures/sphenosquamous": "sphenoid/sphenoid-dysfunctions/sutures/sphenosquamous", + "sphenoid/ssb-dysfunctions/sutures/sphenoparietal": "sphenoid/sphenoid-dysfunctions/sutures/sphenoparietal", + "sphenoid/ssb-dysfunctions/sutures/frontosphenoidal": null, + "sphenoid/ssb-dysfunctions/sutures/sphenozygomatic": null, + "sphenoid/ssb-dysfunctions/sutures/sphenomaxillary": "sphenoid/sphenoid-dysfunctions/sutures/sphenomaxillary", + "sphenoid/ssb-dysfunctions/sutures/sphenovomerian": null, + "sphenoid/ssb-dysfunctions/sutures/sphenopalatine": "sphenoid/sphenoid-dysfunctions/sutures/sphenopalatine", + "sphenoid/sphenoid-observations": "sphenoid/sphenoid-consultation-reasons", + "sphenoid/sphenoid-observations/behavior-change": "sphenoid/sphenoid-consultation-reasons/behavior-change", + "sphenoid/sphenoid-observations/behavior-change/irritability": "sphenoid/sphenoid-consultation-reasons/behavior-change/irritability", + "sphenoid/sphenoid-observations/behavior-change/withdrawal": "sphenoid/sphenoid-consultation-reasons/behavior-change/withdrawal", + "sphenoid/sphenoid-observations/behavior-change/hypersensitivity": "sphenoid/sphenoid-consultation-reasons/behavior-change/head-touch-hypersensitivity", + "sphenoid/sphenoid-observations/performance-drop": "sphenoid/sphenoid-consultation-reasons/performance-drop", + "sphenoid/sphenoid-observations/cycle-irregularity": "sphenoid/sphenoid-consultation-reasons/cycle-irregularity", + "sphenoid/sphenoid-observations/post-trauma-head": "sphenoid/sphenoid-consultation-reasons/post-trauma-head", + "sphenoid/anamnesis": "sphenoid/anamnesis", + "sphenoid/anamnesis/trauma-direct": "sphenoid/anamnesis/trauma-direct", + "sphenoid/anamnesis/stress-context": "sphenoid/anamnesis/stress-context", + "sphenoid/anamnesis/posture-context": "sphenoid/anamnesis/posture-context", + "sphenoid/anamnesis/dental-context": "sphenoid/anamnesis/dental-context", + "sphenoid/anamnesis/post-veterinary": "sphenoid/anamnesis/post-veterinary", + "sphenoid/anamnesis/no-identified-cause": "sphenoid/anamnesis/no-identified-cause", + "temporal/temporal-dysfunctions": "temporal/temporal-dysfunctions", + "temporal/temporal-dysfunctions/mobility": "temporal/temporal-dysfunctions/mobility", + "temporal/temporal-dysfunctions/mobility/temporal-anteriority": "temporal/temporal-dysfunctions/mobility/temporal-anteriority", + "temporal/temporal-dysfunctions/mobility/flexion-external-rotation": "temporal/temporal-dysfunctions/mobility/flexion-external-rotation", + "temporal/temporal-dysfunctions/mobility/extension-internal-rotation": "temporal/temporal-dysfunctions/mobility/extension-internal-rotation", + "temporal/temporal-dysfunctions/mobility/global-restriction": "temporal/temporal-dysfunctions/mobility/global-restriction", + "temporal/temporal-dysfunctions/intraosseous": "temporal/temporal-dysfunctions/intraosseous", + "temporal/temporal-dysfunctions/intraosseous/petrosquamous": "temporal/temporal-dysfunctions/intraosseous/petrosquamous", + "temporal/temporal-dysfunctions/intraosseous/tympanic-part": "temporal/temporal-dysfunctions/intraosseous/tympanic-part", + "temporal/temporal-dysfunctions/sutures": "temporal/temporal-dysfunctions/sutures", + "temporal/temporal-dysfunctions/sutures/parieto-temporal": "temporal/temporal-dysfunctions/sutures/parieto-temporal", + "temporal/temporal-dysfunctions/sutures/sphenosquamous": "temporal/temporal-dysfunctions/sutures/sphenosquamous", + "temporal/temporal-dysfunctions/sutures/occipitomastoid": "temporal/temporal-dysfunctions/sutures/occipitomastoid", + "temporal/temporal-dysfunctions/sutures/temporozygomatic": "temporal/temporal-dysfunctions/sutures/temporozygomatic", + "temporal/temporal-dysfunctions/sutures/petro-occipital": "temporal/temporal-dysfunctions/sutures/petro-occipital", + "temporal/temporal-observations": "temporal/temporal-consultation-reasons", + "temporal/temporal-observations/behavior-change": "temporal/temporal-consultation-reasons/behavior-change", + "temporal/temporal-observations/behavior-change/head-touch-hypersensitivity": "temporal/temporal-consultation-reasons/behavior-change/head-touch-hypersensitivity", + "temporal/temporal-observations/behavior-change/new-irritability": "temporal/temporal-consultation-reasons/behavior-change/new-irritability", + "temporal/temporal-observations/post-trauma-head": "temporal/temporal-consultation-reasons/post-trauma-head", + "temporal/anamnesis": "temporal/anamnesis", + "temporal/anamnesis/trauma-direct": "temporal/anamnesis/trauma-direct", + "temporal/anamnesis/stress-context": "temporal/anamnesis/stress-context", + "temporal/anamnesis/posture-context": "temporal/anamnesis/posture-context", + "temporal/anamnesis/dental-context": "temporal/anamnesis/dental-context", + "temporal/anamnesis/post-veterinary": "temporal/anamnesis/post-veterinary", + "temporal/anamnesis/no-identified-cause": "temporal/anamnesis/no-identified-cause", + "occipital/occipital-dysfunctions": "occipital/occipital-dysfunctions", + "occipital/occipital-dysfunctions/mobility": "occipital/occipital-dysfunctions/mobility", + "occipital/occipital-dysfunctions/mobility/condylar-compression": "occipital/occipital-dysfunctions/mobility/condylar-compression", + "occipital/occipital-dysfunctions/mobility/flexion-external-rotation": "occipital/occipital-dysfunctions/mobility/flexion-external-rotation", + "occipital/occipital-dysfunctions/mobility/extension-internal-rotation": "occipital/occipital-dysfunctions/mobility/extension-internal-rotation", + "occipital/occipital-dysfunctions/mobility/global-restriction": "occipital/occipital-dysfunctions/mobility/global-restriction", + "occipital/occipital-dysfunctions/intraosseous": "occipital/occipital-dysfunctions/intraosseous", + "occipital/occipital-dysfunctions/intraosseous/squama-part": "occipital/occipital-dysfunctions/intraosseous/squama-part", + "occipital/occipital-dysfunctions/intraosseous/condylar-parts": "occipital/occipital-dysfunctions/intraosseous/condylar-parts", + "occipital/occipital-dysfunctions/intraosseous/basilar-part": "occipital/occipital-dysfunctions/intraosseous/basilar-part", + "occipital/occipital-dysfunctions/sutures": "occipital/occipital-dysfunctions/sutures", + "occipital/occipital-dysfunctions/sutures/parieto-occipital": "occipital/occipital-dysfunctions/sutures/parieto-occipital", + "occipital/occipital-dysfunctions/sutures/occipitomastoid": "occipital/occipital-dysfunctions/sutures/occipitomastoid", + "occipital/occipital-dysfunctions/sutures/petro-occipital": "occipital/occipital-dysfunctions/sutures/petro-occipital", + "occipital/occipital-observations": "occipital/occipital-consultation-reasons", + "occipital/occipital-observations/behavior-change": "occipital/occipital-consultation-reasons/behavior-change", + "occipital/occipital-observations/behavior-change/head-touch-hypersensitivity": "occipital/occipital-consultation-reasons/behavior-change/head-touch-hypersensitivity", + "occipital/occipital-observations/behavior-change/new-irritability": "occipital/occipital-consultation-reasons/behavior-change/new-irritability", + "occipital/occipital-observations/post-trauma-head": "occipital/occipital-consultation-reasons/post-trauma-head", + "occipital/anamnesis": "occipital/anamnesis", + "occipital/anamnesis/trauma-direct": "occipital/anamnesis/trauma-direct", + "occipital/anamnesis/stress-context": "occipital/anamnesis/stress-context", + "occipital/anamnesis/posture-context": "occipital/anamnesis/posture-context", + "occipital/anamnesis/dental-context": "occipital/anamnesis/dental-context", + "occipital/anamnesis/post-veterinary": "occipital/anamnesis/post-veterinary", + "occipital/anamnesis/no-identified-cause": "occipital/anamnesis/no-identified-cause", + "ssb/ssb-dysfunctions": "ssb/ssb-dysfunctions", + "ssb/ssb-dysfunctions/physiological": "ssb/ssb-dysfunctions/physiological", + "ssb/ssb-dysfunctions/physiological/flexion": "ssb/ssb-dysfunctions/physiological/flexion", + "ssb/ssb-dysfunctions/physiological/extension": "ssb/ssb-dysfunctions/physiological/extension", + "ssb/ssb-dysfunctions/physiological/torsion-right": "ssb/ssb-dysfunctions/physiological/torsion-right", + "ssb/ssb-dysfunctions/physiological/torsion-left": "ssb/ssb-dysfunctions/physiological/torsion-left", + "ssb/ssb-dysfunctions/physiological/sidebending-rotation-right": "ssb/ssb-dysfunctions/physiological/sidebending-rotation-right", + "ssb/ssb-dysfunctions/physiological/sidebending-rotation-left": "ssb/ssb-dysfunctions/physiological/sidebending-rotation-left", + "ssb/ssb-dysfunctions/traumatic": "ssb/ssb-dysfunctions/traumatic", + "ssb/ssb-dysfunctions/traumatic/vertical-strain-superior": "ssb/ssb-dysfunctions/traumatic/vertical-strain-superior", + "ssb/ssb-dysfunctions/traumatic/vertical-strain-inferior": "ssb/ssb-dysfunctions/traumatic/vertical-strain-inferior", + "ssb/ssb-dysfunctions/traumatic/lateral-strain-right": "ssb/ssb-dysfunctions/traumatic/lateral-strain-right", + "ssb/ssb-dysfunctions/traumatic/lateral-strain-left": "ssb/ssb-dysfunctions/traumatic/lateral-strain-left", + "ssb/ssb-dysfunctions/traumatic/compression": "ssb/ssb-dysfunctions/traumatic/compression", + "ssb/ssb-dysfunctions/intraosseous": null, + "ssb/ssb-dysfunctions/intraosseous/pre-post-sphenoid": null, + "ssb/ssb-dysfunctions/intraosseous/lesser-wings": null, + "ssb/ssb-dysfunctions/intraosseous/greater-wings": null, + "ssb/ssb-dysfunctions/sutures": null, + "ssb/ssb-dysfunctions/sutures/sphenopetrosal": null, + "ssb/ssb-dysfunctions/sutures/sphenosquamous": null, + "ssb/ssb-dysfunctions/sutures/sphenoparietal": null, + "ssb/ssb-dysfunctions/sutures/frontosphenoidal": null, + "ssb/ssb-dysfunctions/sutures/sphenozygomatic": null, + "ssb/ssb-dysfunctions/sutures/sphenomaxillary": null, + "ssb/ssb-dysfunctions/sutures/sphenovomerian": null, + "ssb/ssb-dysfunctions/sutures/sphenopalatine": null, + "ssb/ssb-observations": "ssb/ssb-consultation-reasons", + "ssb/ssb-observations/behavior-change": "ssb/ssb-consultation-reasons/behavior-change", + "ssb/ssb-observations/behavior-change/irritability": "ssb/ssb-consultation-reasons/behavior-change/irritability", + "ssb/ssb-observations/behavior-change/withdrawal": "ssb/ssb-consultation-reasons/behavior-change/withdrawal", + "ssb/ssb-observations/behavior-change/hypersensitivity": "ssb/ssb-consultation-reasons/behavior-change/head-touch-hypersensitivity", + "ssb/ssb-observations/performance-drop": "ssb/ssb-consultation-reasons/performance-drop", + "ssb/ssb-observations/cycle-irregularity": "ssb/ssb-consultation-reasons/cycle-irregularity", + "ssb/ssb-observations/post-trauma-head": "ssb/ssb-consultation-reasons/post-trauma-head", + "ssb/anamnesis": "ssb/anamnesis", + "ssb/anamnesis/trauma-direct": "ssb/anamnesis/trauma-direct", + "ssb/anamnesis/stress-context": "ssb/anamnesis/stress-context", + "ssb/anamnesis/posture-context": "ssb/anamnesis/posture-context", + "ssb/anamnesis/dental-context": "ssb/anamnesis/dental-context", + "ssb/anamnesis/post-veterinary": "ssb/anamnesis/post-veterinary", + "ssb/anamnesis/no-identified-cause": "ssb/anamnesis/no-identified-cause", + "atm/atm-dysfunctions": "atm/atm-dysfunctions", + "atm/atm-dysfunctions/articular": "atm/atm-dysfunctions/articular", + "atm/atm-dysfunctions/articular/restriction-opening": "atm/atm-dysfunctions/articular/restriction-opening", + "atm/atm-dysfunctions/articular/restriction-closing": "atm/atm-dysfunctions/articular/restriction-closing", + "atm/atm-dysfunctions/articular/restriction-lateral": "atm/atm-dysfunctions/articular/restriction-lateral", + "atm/atm-dysfunctions/articular/restriction-protrusion": "atm/atm-dysfunctions/articular/restriction-protrusion", + "atm/atm-dysfunctions/articular/hypomobility": "atm/atm-dysfunctions/articular/hypomobility", + "atm/atm-dysfunctions/articular/hypermobility": "atm/atm-dysfunctions/articular/hypermobility", + "atm/atm-dysfunctions/muscular": "atm/atm-dysfunctions/muscular", + "atm/atm-dysfunctions/muscular/masseter-tension": "atm/atm-dysfunctions/muscular/masseter-tension", + "atm/atm-dysfunctions/muscular/temporalis-tension": "atm/atm-dysfunctions/muscular/temporalis-tension", + "atm/atm-dysfunctions/muscular/pterygoid-tension": "atm/atm-dysfunctions/muscular/pterygoid-tension", + "atm/atm-dysfunctions/muscular/trigger-points": "atm/atm-dysfunctions/muscular/trigger-points", + "atm/atm-dysfunctions/mechanical": "atm/atm-dysfunctions/mechanical", + "atm/atm-dysfunctions/mechanical/lateral-deviation-jaw": "atm/atm-dysfunctions/mechanical/lateral-deviation-jaw", + "atm/atm-dysfunctions/mechanical/asymmetric-dental-wear": "atm/atm-dysfunctions/mechanical/asymmetric-dental-wear", + "atm/atm-dysfunctions/mechanical/opening-deviation": "atm/atm-dysfunctions/mechanical/opening-deviation", + "atm/atm-dysfunctions/mechanical/asymmetric-amplitude": "atm/atm-dysfunctions/mechanical/asymmetric-amplitude", + "atm/atm-observations": "atm/atm-consultation-reasons", + "atm/atm-observations/bit-defense": "atm/atm-consultation-reasons/bit-defense", + "atm/atm-observations/headshaking": "atm/atm-consultation-reasons/headshaking", + "atm/atm-observations/head-tilt-saddle": "atm/atm-consultation-reasons/head-tilt-saddle", + "atm/atm-observations/slow-eating": "atm/atm-consultation-reasons/slow-eating", + "atm/atm-observations/drops-food": "atm/atm-consultation-reasons/drops-food", + "atm/atm-observations/hand-contact-refusal": "atm/atm-consultation-reasons/hand-contact-refusal", + "atm/atm-observations/false-bend": "atm/atm-consultation-reasons/false-bend", + "atm/atm-observations/post-dental-care": "atm/atm-consultation-reasons/post-dental-care", + "atm/anamnesis": "atm/anamnesis", + "atm/anamnesis/trauma-direct": "atm/anamnesis/trauma-direct", + "atm/anamnesis/stress-context": "atm/anamnesis/stress-context", + "atm/anamnesis/posture-context": "atm/anamnesis/posture-context", + "atm/anamnesis/dental-context": "atm/anamnesis/dental-context", + "atm/anamnesis/post-veterinary": "atm/anamnesis/post-veterinary", + "atm/anamnesis/no-identified-cause": "atm/anamnesis/no-identified-cause", + "hyoid/hyoid-dysfunctions": "hyoid/hyoid-dysfunctions", + "hyoid/hyoid-dysfunctions/mobility": "hyoid/hyoid-dysfunctions/mobility", + "hyoid/hyoid-dysfunctions/mobility/global-restriction": "hyoid/hyoid-dysfunctions/mobility/global-restriction", + "hyoid/hyoid-dysfunctions/mobility/lateral-deviation": "hyoid/hyoid-dysfunctions/mobility/lateral-deviation", + "hyoid/hyoid-dysfunctions/mobility/swing-restriction": "hyoid/hyoid-dysfunctions/mobility/retraction-protraction-restriction", + "hyoid/hyoid-dysfunctions/muscular": "hyoid/hyoid-dysfunctions/muscular", + "hyoid/hyoid-dysfunctions/muscular/suprahyoid-tension": "hyoid/hyoid-dysfunctions/muscular/suprahyoid-tension", + "hyoid/hyoid-dysfunctions/muscular/infrahyoid-tension": "hyoid/hyoid-dysfunctions/muscular/infrahyoid-tension", + "hyoid/hyoid-dysfunctions/muscular/stylohyoid-tension": "hyoid/hyoid-dysfunctions/muscular/stylohyoid-tension", + "hyoid/hyoid-dysfunctions/muscular/tongue-base-tension": "hyoid/hyoid-dysfunctions/muscular/tongue-base-tension", + "hyoid/hyoid-dysfunctions/intraosseous": "hyoid/hyoid-dysfunctions/intraosseous", + "hyoid/hyoid-dysfunctions/intraosseous/stylohyoid-bone": "hyoid/hyoid-dysfunctions/intraosseous/stylohyoid-bone", + "hyoid/hyoid-dysfunctions/intraosseous/basihyoid": "hyoid/hyoid-dysfunctions/intraosseous/basihyoid", + "hyoid/hyoid-observations": "hyoid/hyoid-consultation-reasons", + "hyoid/hyoid-observations/bit-defense": "hyoid/hyoid-consultation-reasons/bit-defense", + "hyoid/hyoid-observations/tongue-over-bit": "hyoid/hyoid-consultation-reasons/tongue-over-bit", + "hyoid/hyoid-observations/swallowing-difficulty": "hyoid/hyoid-consultation-reasons/swallowing-difficulty", + "hyoid/hyoid-observations/head-carriage-resistance": "hyoid/hyoid-consultation-reasons/head-carriage-resistance", + "hyoid/hyoid-observations/post-dental-care": "hyoid/hyoid-consultation-reasons/post-dental-care", + "hyoid/anamnesis": "hyoid/anamnesis", + "hyoid/anamnesis/trauma-direct": "hyoid/anamnesis/trauma-direct", + "hyoid/anamnesis/stress-context": "hyoid/anamnesis/stress-context", + "hyoid/anamnesis/posture-context": "hyoid/anamnesis/posture-context", + "hyoid/anamnesis/dental-context": "hyoid/anamnesis/dental-context", + "hyoid/anamnesis/post-veterinary": "hyoid/anamnesis/post-veterinary", + "hyoid/anamnesis/no-identified-cause": "hyoid/anamnesis/no-identified-cause", + "c0-c1/c0-c1-dysfunctions": "c0-c1/c0-c1-dysfunctions", + "c0-c1/c0-c1-dysfunctions/segmental": "c0-c1/c0-c1-dysfunctions/segmental", + "c0-c1/c0-c1-dysfunctions/segmental/restriction-flexion": "c0-c1/c0-c1-dysfunctions/segmental/restriction-flexion", + "c0-c1/c0-c1-dysfunctions/segmental/restriction-extension": "c0-c1/c0-c1-dysfunctions/segmental/restriction-extension", + "c0-c1/c0-c1-dysfunctions/segmental/restriction-lateroflexion": "c0-c1/c0-c1-dysfunctions/segmental/restriction-lateroflexion", + "c0-c1/c0-c1-dysfunctions/segmental/restriction-rotation": "c0-c1/c0-c1-dysfunctions/segmental/restriction-rotation", + "c0-c1/c0-c1-dysfunctions/segmental/fixation": "c0-c1/c0-c1-dysfunctions/segmental/fixation", + "c0-c1/c0-c1-dysfunctions/muscular": "c0-c1/c0-c1-dysfunctions/muscular", + "c0-c1/c0-c1-dysfunctions/muscular/rectus-capitis-tension": "c0-c1/c0-c1-dysfunctions/muscular/rectus-capitis-tension", + "c0-c1/c0-c1-dysfunctions/muscular/obliquus-capitis-tension": "c0-c1/c0-c1-dysfunctions/muscular/obliquus-capitis-tension", + "c0-c1/c0-c1-dysfunctions/muscular/splenius-tension": "c0-c1/c0-c1-dysfunctions/muscular/splenius-tension", + "c0-c1/c0-c1-dysfunctions/muscular/trigger-points": "c0-c1/c0-c1-dysfunctions/muscular/trigger-points", + "c0-c1/c0-c1-dysfunctions/mechanical": "c0-c1/c0-c1-dysfunctions/mechanical", + "c0-c1/c0-c1-dysfunctions/mechanical/amplitude-asymmetry": "c0-c1/c0-c1-dysfunctions/mechanical/amplitude-asymmetry", + "c0-c1/c0-c1-dysfunctions/mechanical/alignment-asymmetry": "c0-c1/c0-c1-dysfunctions/mechanical/alignment-asymmetry", + "c0-c1/c0-c1-observations": "c0-c1/c0-c1-consultation-reasons", + "c0-c1/c0-c1-observations/poll-sensitivity": "c0-c1/c0-c1-consultation-reasons/poll-sensitivity", + "c0-c1/c0-c1-observations/head-carriage": "c0-c1/c0-c1-consultation-reasons/head-carriage", + "c0-c1/c0-c1-observations/headshaking": "c0-c1/c0-c1-consultation-reasons/headshaking", + "c0-c1/c0-c1-observations/bridle-resistance": "c0-c1/c0-c1-consultation-reasons/bridle-resistance", + "c0-c1/c0-c1-observations/palpation-sensitivity": "c0-c1/c0-c1-consultation-reasons/palpation-sensitivity", + "c0-c1/anamnesis": "c0-c1/anamnesis", + "c0-c1/anamnesis/trauma-direct": "c0-c1/anamnesis/trauma-direct", + "c0-c1/anamnesis/saddle-context": "c0-c1/anamnesis/saddle-context", + "c0-c1/anamnesis/posture-context": "c0-c1/anamnesis/posture-context", + "c0-c1/anamnesis/stress-context": "c0-c1/anamnesis/stress-context", + "c0-c1/anamnesis/post-veterinary": "c0-c1/anamnesis/post-veterinary", + "c0-c1/anamnesis/no-identified-cause": "c0-c1/anamnesis/no-identified-cause", + "cervical/cervical-dysfunctions": "cervical/cervical-dysfunctions", + "cervical/cervical-dysfunctions/segmental": "cervical/cervical-dysfunctions/segmental", + "cervical/cervical-dysfunctions/segmental/restriction-flexion": "cervical/cervical-dysfunctions/segmental/restriction-flexion", + "cervical/cervical-dysfunctions/segmental/restriction-extension": "cervical/cervical-dysfunctions/segmental/restriction-extension", + "cervical/cervical-dysfunctions/segmental/restriction-lateroflexion": "cervical/cervical-dysfunctions/segmental/restriction-lateroflexion", + "cervical/cervical-dysfunctions/segmental/restriction-rotation": "cervical/cervical-dysfunctions/segmental/restriction-rotation", + "cervical/cervical-dysfunctions/segmental/localized-fixation": "cervical/cervical-dysfunctions/segmental/localized-fixation", + "cervical/cervical-dysfunctions/group": "cervical/cervical-dysfunctions/group", + "cervical/cervical-dysfunctions/group/nsr-group": "cervical/cervical-dysfunctions/group/nsr-group", + "cervical/cervical-dysfunctions/group/functional-scoliotic-attitude": "cervical/cervical-dysfunctions/group/functional-scoliotic-attitude", + "cervical/cervical-dysfunctions/muscular": "cervical/cervical-dysfunctions/muscular", + "cervical/cervical-dysfunctions/muscular/splenius-tension": "cervical/cervical-dysfunctions/muscular/splenius-tension", + "cervical/cervical-dysfunctions/muscular/longissimus-capitis-cervicis": "cervical/cervical-dysfunctions/muscular/longissimus-capitis-cervicis", + "cervical/cervical-dysfunctions/muscular/scalenus-tension": "cervical/cervical-dysfunctions/muscular/scalenus-tension", + "cervical/cervical-dysfunctions/muscular/brachiocephalicus-tension": "cervical/cervical-dysfunctions/muscular/brachiocephalicus-tension", + "cervical/cervical-dysfunctions/muscular/multifidus-cervicis": "cervical/cervical-dysfunctions/muscular/multifidus-cervicis", + "cervical/cervical-dysfunctions/mechanical": "cervical/cervical-dysfunctions/mechanical", + "cervical/cervical-dysfunctions/mechanical/lateral-bend-asymmetry": "cervical/cervical-dysfunctions/mechanical/lateral-bend-asymmetry", + "cervical/cervical-dysfunctions/mechanical/muscle-relief-asymmetry": "cervical/cervical-dysfunctions/mechanical/muscle-relief-asymmetry", + "cervical/cervical-observations": "cervical/cervical-consultation-reasons", + "cervical/cervical-observations/ridden-work": "cervical/cervical-consultation-reasons/ridden-work", + "cervical/cervical-observations/ridden-work/bend-asymmetry-work": "cervical/cervical-consultation-reasons/ridden-work/bend-asymmetry-work", + "cervical/cervical-observations/ridden-work/head-carriage": "cervical/cervical-consultation-reasons/ridden-work/head-carriage", + "cervical/cervical-observations/ridden-work/contact-resistance": "cervical/cervical-consultation-reasons/ridden-work/contact-resistance", + "cervical/cervical-observations/stumbling-proprioceptive": "cervical/cervical-consultation-reasons/stumbling-proprioceptive", + "cervical/cervical-observations/palpation-sensitivity": "cervical/cervical-consultation-reasons/palpation-sensitivity", + "cervical/cervical-observations/new-stiffness": "cervical/cervical-consultation-reasons/new-stiffness", + "cervical/anamnesis": "cervical/anamnesis", + "cervical/anamnesis/trauma-direct": "cervical/anamnesis/trauma-direct", + "cervical/anamnesis/saddle-context": "cervical/anamnesis/saddle-context", + "cervical/anamnesis/posture-context": "cervical/anamnesis/posture-context", + "cervical/anamnesis/stress-context": "cervical/anamnesis/stress-context", + "cervical/anamnesis/post-veterinary": "cervical/anamnesis/post-veterinary", + "cervical/anamnesis/no-identified-cause": "cervical/anamnesis/no-identified-cause", + "c7-t1/c7-t1-dysfunctions": "c7-t1/c7-t1-dysfunctions", + "c7-t1/c7-t1-dysfunctions/segmental": "c7-t1/c7-t1-dysfunctions/segmental", + "c7-t1/c7-t1-dysfunctions/segmental/restriction-flexion": "c7-t1/c7-t1-dysfunctions/segmental/restriction-flexion", + "c7-t1/c7-t1-dysfunctions/segmental/restriction-extension": "c7-t1/c7-t1-dysfunctions/segmental/restriction-extension", + "c7-t1/c7-t1-dysfunctions/segmental/restriction-lateroflexion": "c7-t1/c7-t1-dysfunctions/segmental/restriction-lateroflexion", + "c7-t1/c7-t1-dysfunctions/segmental/restriction-rotation": "c7-t1/c7-t1-dysfunctions/segmental/restriction-rotation", + "c7-t1/c7-t1-dysfunctions/segmental/fixation": "c7-t1/c7-t1-dysfunctions/segmental/fixation", + "c7-t1/c7-t1-dysfunctions/muscular": "c7-t1/c7-t1-dysfunctions/muscular", + "c7-t1/c7-t1-dysfunctions/muscular/scalenus-tension": "c7-t1/c7-t1-dysfunctions/muscular/scalenus-tension", + "c7-t1/c7-t1-dysfunctions/muscular/serratus-tension": "c7-t1/c7-t1-dysfunctions/muscular/serratus-tension", + "c7-t1/c7-t1-dysfunctions/muscular/brachiocephalicus-tension": "c7-t1/c7-t1-dysfunctions/muscular/brachiocephalicus-tension", + "c7-t1/c7-t1-dysfunctions/muscular/deep-cervical-tension": "c7-t1/c7-t1-dysfunctions/muscular/deep-cervical-tension", + "c7-t1/c7-t1-dysfunctions/mechanical": "c7-t1/c7-t1-dysfunctions/mechanical", + "c7-t1/c7-t1-dysfunctions/mechanical/amplitude-asymmetry": "c7-t1/c7-t1-dysfunctions/mechanical/amplitude-asymmetry", + "c7-t1/c7-t1-dysfunctions/mechanical/alignment-asymmetry": "c7-t1/c7-t1-dysfunctions/mechanical/alignment-asymmetry", + "c7-t1/c7-t1-observations": "c7-t1/c7-t1-consultation-reasons", + "c7-t1/c7-t1-observations/base-neck-stiffness": "c7-t1/c7-t1-consultation-reasons/base-neck-stiffness", + "c7-t1/c7-t1-observations/forelimb-engagement": "c7-t1/c7-t1-consultation-reasons/forelimb-engagement", + "c7-t1/c7-t1-observations/ewe-neck-posture": "c7-t1/c7-t1-consultation-reasons/ewe-neck-posture", + "c7-t1/c7-t1-observations/forelimb-lameness": "c7-t1/c7-t1-consultation-reasons/forelimb-lameness", + "c7-t1/anamnesis": "c7-t1/anamnesis", + "c7-t1/anamnesis/trauma-direct": "c7-t1/anamnesis/trauma-direct", + "c7-t1/anamnesis/saddle-context": "c7-t1/anamnesis/saddle-context", + "c7-t1/anamnesis/posture-context": "c7-t1/anamnesis/posture-context", + "c7-t1/anamnesis/stress-context": "c7-t1/anamnesis/stress-context", + "c7-t1/anamnesis/post-veterinary": "c7-t1/anamnesis/post-veterinary", + "c7-t1/anamnesis/no-identified-cause": "c7-t1/anamnesis/no-identified-cause", + "shoulder/shoulder-dysfunctions": "shoulder/shoulder-dysfunctions", + "shoulder/shoulder-dysfunctions/articular": "shoulder/shoulder-dysfunctions/articular", + "shoulder/shoulder-dysfunctions/articular/restriction-flexion": "shoulder/shoulder-dysfunctions/articular/restriction-flexion", + "shoulder/shoulder-dysfunctions/articular/restriction-extension": "shoulder/shoulder-dysfunctions/articular/restriction-extension", + "shoulder/shoulder-dysfunctions/articular/restriction-abduction-adduction": "shoulder/shoulder-dysfunctions/articular/restriction-abduction-adduction", + "shoulder/shoulder-dysfunctions/articular/restriction-glide": "shoulder/shoulder-dysfunctions/articular/restriction-glide", + "shoulder/shoulder-dysfunctions/articular/hypomobility": "shoulder/shoulder-dysfunctions/articular/hypomobility", + "shoulder/shoulder-dysfunctions/articular/hypermobility": "shoulder/shoulder-dysfunctions/articular/hypermobility", + "shoulder/shoulder-dysfunctions/muscular": "shoulder/shoulder-dysfunctions/muscular", + "shoulder/shoulder-dysfunctions/muscular/supraspinatus-infraspinatus": "shoulder/shoulder-dysfunctions/muscular/supraspinatus-infraspinatus", + "shoulder/shoulder-dysfunctions/muscular/subscapularis-tension": "shoulder/shoulder-dysfunctions/muscular/subscapularis-tension", + "shoulder/shoulder-dysfunctions/muscular/deltoid-tension": "shoulder/shoulder-dysfunctions/muscular/deltoid-tension", + "shoulder/shoulder-dysfunctions/muscular/biceps-brachii-tension": "shoulder/shoulder-dysfunctions/muscular/biceps-brachii-tension", + "shoulder/shoulder-dysfunctions/muscular/trigger-points": "shoulder/shoulder-dysfunctions/muscular/trigger-points", + "shoulder/shoulder-dysfunctions/mechanical": "shoulder/shoulder-dysfunctions/mechanical", + "shoulder/shoulder-dysfunctions/mechanical/weight-bearing-asymmetry": "shoulder/shoulder-dysfunctions/mechanical/weight-bearing-asymmetry", + "shoulder/shoulder-dysfunctions/mechanical/amplitude-asymmetry": "shoulder/shoulder-dysfunctions/mechanical/amplitude-asymmetry", + "shoulder/shoulder-dysfunctions/mechanical/scapula-position-asymmetry": "shoulder/shoulder-dysfunctions/mechanical/scapula-position-asymmetry", + "shoulder/shoulder-observations": "shoulder/shoulder-consultation-reasons", + "shoulder/shoulder-observations/ridden-work": "shoulder/shoulder-consultation-reasons/ridden-work", + "shoulder/shoulder-observations/ridden-work/canter-difficulty": "shoulder/shoulder-consultation-reasons/ridden-work/canter-difficulty", + "shoulder/shoulder-observations/ridden-work/backing-difficulty": "shoulder/shoulder-consultation-reasons/ridden-work/backing-difficulty", + "shoulder/shoulder-observations/ridden-work/limb-engagement": "shoulder/shoulder-consultation-reasons/ridden-work/limb-engagement", + "shoulder/shoulder-observations/ridden-work/jumping-difficulty": "shoulder/shoulder-consultation-reasons/ridden-work/jumping-difficulty", + "shoulder/shoulder-observations/shortened-cranial-phase": "shoulder/shoulder-consultation-reasons/shortened-cranial-phase", + "shoulder/shoulder-observations/limb-lameness": "shoulder/shoulder-consultation-reasons/limb-lameness", + "shoulder/anamnesis": "shoulder/anamnesis", + "shoulder/anamnesis/trauma-direct": "shoulder/anamnesis/trauma-direct", + "shoulder/anamnesis/sport-context": "shoulder/anamnesis/sport-context", + "shoulder/anamnesis/posture-context": "shoulder/anamnesis/posture-context", + "shoulder/anamnesis/stress-context": "shoulder/anamnesis/stress-context", + "shoulder/anamnesis/post-veterinary": "shoulder/anamnesis/post-veterinary", + "shoulder/anamnesis/no-identified-cause": "shoulder/anamnesis/no-identified-cause", + "elbow/elbow-dysfunctions": "elbow/elbow-dysfunctions", + "elbow/elbow-dysfunctions/articular": "elbow/elbow-dysfunctions/articular", + "elbow/elbow-dysfunctions/articular/restriction-flexion": "elbow/elbow-dysfunctions/articular/restriction-flexion", + "elbow/elbow-dysfunctions/articular/restriction-extension": "elbow/elbow-dysfunctions/articular/restriction-extension", + "elbow/elbow-dysfunctions/articular/restriction-lateromedial": "elbow/elbow-dysfunctions/articular/restriction-lateromedial", + "elbow/elbow-dysfunctions/articular/hypomobility": "elbow/elbow-dysfunctions/articular/hypomobility", + "elbow/elbow-dysfunctions/articular/hypermobility": "elbow/elbow-dysfunctions/articular/hypermobility", + "elbow/elbow-dysfunctions/muscular": "elbow/elbow-dysfunctions/muscular", + "elbow/elbow-dysfunctions/muscular/triceps-tension": "elbow/elbow-dysfunctions/muscular/triceps-tension", + "elbow/elbow-dysfunctions/muscular/biceps-brachialis-tension": "elbow/elbow-dysfunctions/muscular/biceps-brachialis-tension", + "elbow/elbow-dysfunctions/muscular/carpal-extensors-origin": "elbow/elbow-dysfunctions/muscular/carpal-extensors-origin", + "elbow/elbow-dysfunctions/muscular/carpal-flexors-origin": "elbow/elbow-dysfunctions/muscular/carpal-flexors-origin", + "elbow/elbow-dysfunctions/muscular/trigger-points": "elbow/elbow-dysfunctions/muscular/trigger-points", + "elbow/elbow-dysfunctions/mechanical": "elbow/elbow-dysfunctions/mechanical", + "elbow/elbow-dysfunctions/mechanical/weight-bearing-asymmetry": "elbow/elbow-dysfunctions/mechanical/weight-bearing-asymmetry", + "elbow/elbow-dysfunctions/mechanical/amplitude-asymmetry": "elbow/elbow-dysfunctions/mechanical/amplitude-asymmetry", + "elbow/elbow-observations": "elbow/elbow-consultation-reasons", + "elbow/elbow-observations/ridden-work": "elbow/elbow-consultation-reasons/ridden-work", + "elbow/elbow-observations/ridden-work/canter-difficulty": "elbow/elbow-consultation-reasons/ridden-work/canter-difficulty", + "elbow/elbow-observations/ridden-work/backing-difficulty": "elbow/elbow-consultation-reasons/ridden-work/backing-difficulty", + "elbow/elbow-observations/ridden-work/limb-engagement": "elbow/elbow-consultation-reasons/ridden-work/limb-engagement", + "elbow/elbow-observations/ridden-work/jumping-difficulty": "elbow/elbow-consultation-reasons/ridden-work/jumping-difficulty", + "elbow/elbow-observations/limb-lameness": "elbow/elbow-consultation-reasons/limb-lameness", + "elbow/anamnesis": "elbow/anamnesis", + "elbow/anamnesis/trauma-direct": "elbow/anamnesis/trauma-direct", + "elbow/anamnesis/sport-context": "elbow/anamnesis/sport-context", + "elbow/anamnesis/posture-context": "elbow/anamnesis/posture-context", + "elbow/anamnesis/stress-context": "elbow/anamnesis/stress-context", + "elbow/anamnesis/post-veterinary": "elbow/anamnesis/post-veterinary", + "elbow/anamnesis/no-identified-cause": "elbow/anamnesis/no-identified-cause", + "fore-fetlock/fore-fetlock-dysfunctions": "fore-fetlock/fore-fetlock-dysfunctions", + "fore-fetlock/fore-fetlock-dysfunctions/articular": "fore-fetlock/fore-fetlock-dysfunctions/articular", + "fore-fetlock/fore-fetlock-dysfunctions/articular/restriction-flexion": "fore-fetlock/fore-fetlock-dysfunctions/articular/restriction-flexion", + "fore-fetlock/fore-fetlock-dysfunctions/articular/restriction-extension": "fore-fetlock/fore-fetlock-dysfunctions/articular/restriction-extension", + "fore-fetlock/fore-fetlock-dysfunctions/articular/restriction-lateromedial": "fore-fetlock/fore-fetlock-dysfunctions/articular/restriction-lateromedial", + "fore-fetlock/fore-fetlock-dysfunctions/articular/hypomobility": "fore-fetlock/fore-fetlock-dysfunctions/articular/hypomobility", + "fore-fetlock/fore-fetlock-dysfunctions/articular/hypermobility": "fore-fetlock/fore-fetlock-dysfunctions/articular/hypermobility", + "fore-fetlock/fore-fetlock-dysfunctions/muscular": "fore-fetlock/fore-fetlock-dysfunctions/muscular", + "fore-fetlock/fore-fetlock-dysfunctions/muscular/digital-flexors-tendon": "fore-fetlock/fore-fetlock-dysfunctions/muscular/digital-flexors-tendon", + "fore-fetlock/fore-fetlock-dysfunctions/muscular/digital-extensor-tendon": "fore-fetlock/fore-fetlock-dysfunctions/muscular/digital-extensor-tendon", + "fore-fetlock/fore-fetlock-dysfunctions/muscular/palmar-fascia": "fore-fetlock/fore-fetlock-dysfunctions/muscular/palmar-fascia", + "fore-fetlock/fore-fetlock-dysfunctions/mechanical": "fore-fetlock/fore-fetlock-dysfunctions/mechanical", + "fore-fetlock/fore-fetlock-dysfunctions/mechanical/weight-bearing-asymmetry": "fore-fetlock/fore-fetlock-dysfunctions/mechanical/weight-bearing-asymmetry", + "fore-fetlock/fore-fetlock-dysfunctions/mechanical/amplitude-asymmetry": "fore-fetlock/fore-fetlock-dysfunctions/mechanical/amplitude-asymmetry", + "fore-fetlock/fore-fetlock-dysfunctions/mechanical/fetlock-axis-asymmetry": "fore-fetlock/fore-fetlock-dysfunctions/mechanical/fetlock-axis-asymmetry", + "fore-fetlock/fore-fetlock-observations": "fore-fetlock/fore-fetlock-consultation-reasons", + "fore-fetlock/fore-fetlock-observations/ridden-work": "fore-fetlock/fore-fetlock-consultation-reasons/ridden-work", + "fore-fetlock/fore-fetlock-observations/ridden-work/canter-difficulty": "fore-fetlock/fore-fetlock-consultation-reasons/ridden-work/canter-difficulty", + "fore-fetlock/fore-fetlock-observations/ridden-work/backing-difficulty": "fore-fetlock/fore-fetlock-consultation-reasons/ridden-work/backing-difficulty", + "fore-fetlock/fore-fetlock-observations/ridden-work/limb-engagement": "fore-fetlock/fore-fetlock-consultation-reasons/ridden-work/limb-engagement", + "fore-fetlock/fore-fetlock-observations/ridden-work/jumping-difficulty": "fore-fetlock/fore-fetlock-consultation-reasons/ridden-work/jumping-difficulty", + "fore-fetlock/fore-fetlock-observations/limb-lameness": "fore-fetlock/fore-fetlock-consultation-reasons/limb-lameness", + "fore-fetlock/anamnesis": "fore-fetlock/anamnesis", + "fore-fetlock/anamnesis/trauma-direct": "fore-fetlock/anamnesis/trauma-direct", + "fore-fetlock/anamnesis/sport-context": "fore-fetlock/anamnesis/sport-context", + "fore-fetlock/anamnesis/posture-context": "fore-fetlock/anamnesis/posture-context", + "fore-fetlock/anamnesis/stress-context": "fore-fetlock/anamnesis/stress-context", + "fore-fetlock/anamnesis/post-veterinary": "fore-fetlock/anamnesis/post-veterinary", + "fore-fetlock/anamnesis/no-identified-cause": "fore-fetlock/anamnesis/no-identified-cause", + "fore-sesamoids/fore-sesamoids-dysfunctions": "fore-sesamoids/fore-sesamoids-dysfunctions", + "fore-sesamoids/fore-sesamoids-dysfunctions/mobility": "fore-sesamoids/fore-sesamoids-dysfunctions/mobility", + "fore-sesamoids/fore-sesamoids-dysfunctions/mobility/sesamoid-glide-restriction": "fore-sesamoids/fore-sesamoids-dysfunctions/mobility/sesamoid-glide-restriction", + "fore-sesamoids/fore-sesamoids-dysfunctions/mobility/medial-sesamoid": "fore-sesamoids/fore-sesamoids-dysfunctions/mobility/medial-sesamoid", + "fore-sesamoids/fore-sesamoids-dysfunctions/mobility/lateral-sesamoid": "fore-sesamoids/fore-sesamoids-dysfunctions/mobility/lateral-sesamoid", + "fore-sesamoids/fore-sesamoids-dysfunctions/ligamentous": "fore-sesamoids/fore-sesamoids-dysfunctions/ligamentous", + "fore-sesamoids/fore-sesamoids-dysfunctions/ligamentous/intersesamoidean": "fore-sesamoids/fore-sesamoids-dysfunctions/ligamentous/intersesamoidean", + "fore-sesamoids/fore-sesamoids-dysfunctions/ligamentous/flexor-tendon-glide": "fore-sesamoids/fore-sesamoids-dysfunctions/ligamentous/flexor-tendon-glide", + "fore-sesamoids/fore-sesamoids-dysfunctions/mechanical": "fore-sesamoids/fore-sesamoids-dysfunctions/mechanical", + "fore-sesamoids/fore-sesamoids-dysfunctions/mechanical/sesamoid-asymmetry": "fore-sesamoids/fore-sesamoids-dysfunctions/mechanical/sesamoid-asymmetry", + "fore-sesamoids/fore-sesamoids-dysfunctions/mechanical/weight-bearing-asymmetry": "fore-sesamoids/fore-sesamoids-dysfunctions/mechanical/weight-bearing-asymmetry", + "fore-sesamoids/fore-sesamoids-observations": "fore-sesamoids/fore-sesamoids-consultation-reasons", + "fore-sesamoids/fore-sesamoids-observations/local-sensitivity": "fore-sesamoids/fore-sesamoids-consultation-reasons/local-sensitivity", + "fore-sesamoids/fore-sesamoids-observations/shortened-stride": "fore-sesamoids/fore-sesamoids-consultation-reasons/shortened-stride", + "fore-sesamoids/fore-sesamoids-observations/forelimb-lameness": "fore-sesamoids/fore-sesamoids-consultation-reasons/forelimb-lameness", + "fore-sesamoids/anamnesis": "fore-sesamoids/anamnesis", + "fore-sesamoids/anamnesis/trauma-direct": "fore-sesamoids/anamnesis/trauma-direct", + "fore-sesamoids/anamnesis/sport-context": "fore-sesamoids/anamnesis/sport-context", + "fore-sesamoids/anamnesis/posture-context": "fore-sesamoids/anamnesis/posture-context", + "fore-sesamoids/anamnesis/stress-context": "fore-sesamoids/anamnesis/stress-context", + "fore-sesamoids/anamnesis/post-veterinary": "fore-sesamoids/anamnesis/post-veterinary", + "fore-sesamoids/anamnesis/no-identified-cause": "fore-sesamoids/anamnesis/no-identified-cause", + "thoracic/thoracic-dysfunctions": "thoracic/thoracic-dysfunctions", + "thoracic/thoracic-dysfunctions/segmental": "thoracic/thoracic-dysfunctions/segmental", + "thoracic/thoracic-dysfunctions/segmental/restriction-flexion": "thoracic/thoracic-dysfunctions/segmental/restriction-flexion", + "thoracic/thoracic-dysfunctions/segmental/restriction-extension": "thoracic/thoracic-dysfunctions/segmental/restriction-extension", + "thoracic/thoracic-dysfunctions/segmental/restriction-lateroflexion": "thoracic/thoracic-dysfunctions/segmental/restriction-lateroflexion", + "thoracic/thoracic-dysfunctions/segmental/restriction-rotation": "thoracic/thoracic-dysfunctions/segmental/restriction-rotation", + "thoracic/thoracic-dysfunctions/segmental/localized-fixation": "thoracic/thoracic-dysfunctions/segmental/localized-fixation", + "thoracic/thoracic-dysfunctions/costovertebral": "thoracic/thoracic-dysfunctions/costovertebral", + "thoracic/thoracic-dysfunctions/costovertebral/rib-head-restriction": "thoracic/thoracic-dysfunctions/costovertebral/rib-head-restriction", + "thoracic/thoracic-dysfunctions/costovertebral/rib-respiratory-restriction": "thoracic/thoracic-dysfunctions/costovertebral/rib-respiratory-restriction", + "thoracic/thoracic-dysfunctions/group": "thoracic/thoracic-dysfunctions/group", + "thoracic/thoracic-dysfunctions/group/nsr-group": "thoracic/thoracic-dysfunctions/group/nsr-group", + "thoracic/thoracic-dysfunctions/group/functional-scoliotic-attitude": "thoracic/thoracic-dysfunctions/group/functional-scoliotic-attitude", + "thoracic/thoracic-dysfunctions/muscular": "thoracic/thoracic-dysfunctions/muscular", + "thoracic/thoracic-dysfunctions/muscular/longissimus-tension": "thoracic/thoracic-dysfunctions/muscular/longissimus-tension", + "thoracic/thoracic-dysfunctions/muscular/iliocostalis-tension": "thoracic/thoracic-dysfunctions/muscular/iliocostalis-tension", + "thoracic/thoracic-dysfunctions/muscular/trapezius-tension": "thoracic/thoracic-dysfunctions/muscular/trapezius-tension", + "thoracic/thoracic-dysfunctions/muscular/latissimus-tension": "thoracic/thoracic-dysfunctions/muscular/latissimus-tension", + "thoracic/thoracic-dysfunctions/muscular/trigger-points": "thoracic/thoracic-dysfunctions/muscular/trigger-points", + "thoracic/thoracic-dysfunctions/mechanical": "thoracic/thoracic-dysfunctions/mechanical", + "thoracic/thoracic-dysfunctions/mechanical/muscle-relief-asymmetry": "thoracic/thoracic-dysfunctions/mechanical/muscle-relief-asymmetry", + "thoracic/thoracic-dysfunctions/mechanical/withers-asymmetry": "thoracic/thoracic-dysfunctions/mechanical/withers-asymmetry", + "thoracic/thoracic-observations": "thoracic/thoracic-consultation-reasons", + "thoracic/thoracic-observations/ridden-work": "thoracic/thoracic-consultation-reasons/ridden-work", + "thoracic/thoracic-observations/ridden-work/saddle-region-sensitivity": "thoracic/thoracic-consultation-reasons/ridden-work/saddle-region-sensitivity", + "thoracic/thoracic-observations/ridden-work/cold-backed": "thoracic/thoracic-consultation-reasons/ridden-work/cold-backed", + "thoracic/thoracic-observations/ridden-work/hindquarter-engagement": "thoracic/thoracic-consultation-reasons/ridden-work/back-transmission", + "thoracic/thoracic-observations/ridden-work/bucking": "thoracic/thoracic-consultation-reasons/ridden-work/bucking", + "thoracic/thoracic-observations/girthing-defense": "thoracic/thoracic-consultation-reasons/girthing-defense", + "thoracic/thoracic-observations/palpation-sensitivity": "thoracic/thoracic-consultation-reasons/palpation-sensitivity", + "thoracic/thoracic-observations/new-stiffness": "thoracic/thoracic-consultation-reasons/new-stiffness", + "thoracic/anamnesis": "thoracic/anamnesis", + "thoracic/anamnesis/trauma-direct": "thoracic/anamnesis/trauma-direct", + "thoracic/anamnesis/saddle-context": "thoracic/anamnesis/saddle-context", + "thoracic/anamnesis/posture-context": "thoracic/anamnesis/posture-context", + "thoracic/anamnesis/stress-context": "thoracic/anamnesis/stress-context", + "thoracic/anamnesis/post-veterinary": "thoracic/anamnesis/post-veterinary", + "thoracic/anamnesis/no-identified-cause": "thoracic/anamnesis/no-identified-cause", + "t18-l1/t18-l1-dysfunctions": "t18-l1/t18-l1-dysfunctions", + "t18-l1/t18-l1-dysfunctions/segmental": "t18-l1/t18-l1-dysfunctions/segmental", + "t18-l1/t18-l1-dysfunctions/segmental/restriction-flexion": "t18-l1/t18-l1-dysfunctions/segmental/restriction-flexion", + "t18-l1/t18-l1-dysfunctions/segmental/restriction-extension": "t18-l1/t18-l1-dysfunctions/segmental/restriction-extension", + "t18-l1/t18-l1-dysfunctions/segmental/restriction-lateroflexion": "t18-l1/t18-l1-dysfunctions/segmental/restriction-lateroflexion", + "t18-l1/t18-l1-dysfunctions/segmental/restriction-rotation": "t18-l1/t18-l1-dysfunctions/segmental/restriction-rotation", + "t18-l1/t18-l1-dysfunctions/segmental/fixation": "t18-l1/t18-l1-dysfunctions/segmental/fixation", + "t18-l1/t18-l1-dysfunctions/muscular": "t18-l1/t18-l1-dysfunctions/muscular", + "t18-l1/t18-l1-dysfunctions/muscular/longissimus-tension": "t18-l1/t18-l1-dysfunctions/muscular/longissimus-tension", + "t18-l1/t18-l1-dysfunctions/muscular/iliocostalis-tension": "t18-l1/t18-l1-dysfunctions/muscular/iliocostalis-tension", + "t18-l1/t18-l1-dysfunctions/muscular/thoracolumbar-fascia": "t18-l1/t18-l1-dysfunctions/muscular/thoracolumbar-fascia", + "t18-l1/t18-l1-dysfunctions/muscular/trigger-points": "t18-l1/t18-l1-dysfunctions/muscular/trigger-points", + "t18-l1/t18-l1-dysfunctions/mechanical": "t18-l1/t18-l1-dysfunctions/mechanical", + "t18-l1/t18-l1-dysfunctions/mechanical/amplitude-asymmetry": "t18-l1/t18-l1-dysfunctions/mechanical/amplitude-asymmetry", + "t18-l1/t18-l1-dysfunctions/mechanical/alignment-asymmetry": "t18-l1/t18-l1-dysfunctions/mechanical/alignment-asymmetry", + "t18-l1/t18-l1-observations": "t18-l1/t18-l1-consultation-reasons", + "t18-l1/t18-l1-observations/back-mobility-loss": "t18-l1/t18-l1-consultation-reasons/back-mobility-loss", + "t18-l1/t18-l1-observations/saddle-rear-sensitivity": "t18-l1/t18-l1-consultation-reasons/saddle-rear-sensitivity", + "t18-l1/t18-l1-observations/transmission-defect": "t18-l1/t18-l1-consultation-reasons/transmission-defect", + "t18-l1/t18-l1-observations/palpation-sensitivity": "t18-l1/t18-l1-consultation-reasons/palpation-sensitivity", + "t18-l1/anamnesis": "t18-l1/anamnesis", + "t18-l1/anamnesis/trauma-direct": "t18-l1/anamnesis/trauma-direct", + "t18-l1/anamnesis/saddle-context": "t18-l1/anamnesis/saddle-context", + "t18-l1/anamnesis/posture-context": "t18-l1/anamnesis/posture-context", + "t18-l1/anamnesis/stress-context": "t18-l1/anamnesis/stress-context", + "t18-l1/anamnesis/post-veterinary": "t18-l1/anamnesis/post-veterinary", + "t18-l1/anamnesis/no-identified-cause": "t18-l1/anamnesis/no-identified-cause", + "lumbar/lumbar-dysfunctions": "lumbar/lumbar-dysfunctions", + "lumbar/lumbar-dysfunctions/segmental": "lumbar/lumbar-dysfunctions/segmental", + "lumbar/lumbar-dysfunctions/segmental/restriction-flexion": "lumbar/lumbar-dysfunctions/segmental/restriction-flexion", + "lumbar/lumbar-dysfunctions/segmental/restriction-extension": "lumbar/lumbar-dysfunctions/segmental/restriction-extension", + "lumbar/lumbar-dysfunctions/segmental/restriction-lateroflexion": "lumbar/lumbar-dysfunctions/segmental/restriction-lateroflexion", + "lumbar/lumbar-dysfunctions/segmental/restriction-rotation": "lumbar/lumbar-dysfunctions/segmental/restriction-rotation", + "lumbar/lumbar-dysfunctions/segmental/localized-fixation": "lumbar/lumbar-dysfunctions/segmental/localized-fixation", + "lumbar/lumbar-dysfunctions/group": "lumbar/lumbar-dysfunctions/group", + "lumbar/lumbar-dysfunctions/group/nsr-group": "lumbar/lumbar-dysfunctions/group/nsr-group", + "lumbar/lumbar-dysfunctions/group/functional-scoliotic-attitude": "lumbar/lumbar-dysfunctions/group/functional-scoliotic-attitude", + "lumbar/lumbar-dysfunctions/muscular": "lumbar/lumbar-dysfunctions/muscular", + "lumbar/lumbar-dysfunctions/muscular/longissimus-tension": "lumbar/lumbar-dysfunctions/muscular/longissimus-tension", + "lumbar/lumbar-dysfunctions/muscular/iliocostalis-tension": "lumbar/lumbar-dysfunctions/muscular/iliocostalis-tension", + "lumbar/lumbar-dysfunctions/muscular/psoas-tension": "lumbar/lumbar-dysfunctions/muscular/psoas-tension", + "lumbar/lumbar-dysfunctions/muscular/trigger-points": "lumbar/lumbar-dysfunctions/muscular/trigger-points", + "lumbar/lumbar-dysfunctions/mechanical": "lumbar/lumbar-dysfunctions/mechanical", + "lumbar/lumbar-dysfunctions/mechanical/muscle-relief-asymmetry": "lumbar/lumbar-dysfunctions/mechanical/muscle-relief-asymmetry", + "lumbar/lumbar-dysfunctions/mechanical/pelvic-tilt-asymmetry": "lumbar/lumbar-dysfunctions/mechanical/pelvic-tilt-asymmetry", + "lumbar/lumbar-observations": "lumbar/lumbar-consultation-reasons", + "lumbar/lumbar-observations/ridden-work": "lumbar/lumbar-consultation-reasons/ridden-work", + "lumbar/lumbar-observations/ridden-work/hollow-back-under-rider": "lumbar/lumbar-consultation-reasons/ridden-work/hollow-back-under-rider", + "lumbar/lumbar-observations/ridden-work/hindlimb-engagement": "lumbar/lumbar-consultation-reasons/ridden-work/hindlimb-engagement", + "lumbar/lumbar-observations/ridden-work/jumping-difficulty": "lumbar/lumbar-consultation-reasons/ridden-work/jumping-difficulty", + "lumbar/lumbar-observations/ridden-work/blocking-at-work": "lumbar/lumbar-consultation-reasons/ridden-work/blocking-at-work", + "lumbar/lumbar-observations/girthing-defense": "lumbar/lumbar-consultation-reasons/girthing-defense", + "lumbar/lumbar-observations/palpation-sensitivity": "lumbar/lumbar-consultation-reasons/palpation-sensitivity", + "lumbar/lumbar-observations/new-stiffness": "lumbar/lumbar-consultation-reasons/new-stiffness", + "lumbar/anamnesis": "lumbar/anamnesis", + "lumbar/anamnesis/trauma-direct": "lumbar/anamnesis/trauma-direct", + "lumbar/anamnesis/saddle-context": "lumbar/anamnesis/saddle-context", + "lumbar/anamnesis/posture-context": "lumbar/anamnesis/posture-context", + "lumbar/anamnesis/stress-context": "lumbar/anamnesis/stress-context", + "lumbar/anamnesis/post-veterinary": "lumbar/anamnesis/post-veterinary", + "lumbar/anamnesis/no-identified-cause": "lumbar/anamnesis/no-identified-cause", + "l6-s1/l6-s1-dysfunctions": "l6-s1/l6-s1-dysfunctions", + "l6-s1/l6-s1-dysfunctions/segmental": "l6-s1/l6-s1-dysfunctions/segmental", + "l6-s1/l6-s1-dysfunctions/segmental/restriction-flexion": "l6-s1/l6-s1-dysfunctions/segmental/restriction-flexion", + "l6-s1/l6-s1-dysfunctions/segmental/restriction-extension": "l6-s1/l6-s1-dysfunctions/segmental/restriction-extension", + "l6-s1/l6-s1-dysfunctions/segmental/restriction-lateroflexion": "l6-s1/l6-s1-dysfunctions/segmental/restriction-lateroflexion", + "l6-s1/l6-s1-dysfunctions/segmental/restriction-rotation": "l6-s1/l6-s1-dysfunctions/segmental/restriction-rotation", + "l6-s1/l6-s1-dysfunctions/segmental/fixation": "l6-s1/l6-s1-dysfunctions/segmental/fixation", + "l6-s1/l6-s1-dysfunctions/muscular": "l6-s1/l6-s1-dysfunctions/muscular", + "l6-s1/l6-s1-dysfunctions/muscular/psoas-tension": "l6-s1/l6-s1-dysfunctions/muscular/psoas-tension", + "l6-s1/l6-s1-dysfunctions/muscular/longissimus-tension": "l6-s1/l6-s1-dysfunctions/muscular/longissimus-tension", + "l6-s1/l6-s1-dysfunctions/muscular/gluteal-tension": "l6-s1/l6-s1-dysfunctions/muscular/gluteal-tension", + "l6-s1/l6-s1-dysfunctions/muscular/trigger-points": "l6-s1/l6-s1-dysfunctions/muscular/trigger-points", + "l6-s1/l6-s1-dysfunctions/mechanical": "l6-s1/l6-s1-dysfunctions/mechanical", + "l6-s1/l6-s1-dysfunctions/mechanical/amplitude-asymmetry": "l6-s1/l6-s1-dysfunctions/mechanical/amplitude-asymmetry", + "l6-s1/l6-s1-dysfunctions/mechanical/alignment-asymmetry": "l6-s1/l6-s1-dysfunctions/mechanical/alignment-asymmetry", + "l6-s1/l6-s1-observations": "l6-s1/l6-s1-consultation-reasons", + "l6-s1/l6-s1-observations/hindlimb-engagement": "l6-s1/l6-s1-consultation-reasons/hindlimb-engagement", + "l6-s1/l6-s1-observations/canter-quality": "l6-s1/l6-s1-consultation-reasons/canter-quality", + "l6-s1/l6-s1-observations/jumping-propulsion": "l6-s1/l6-s1-consultation-reasons/jumping-propulsion", + "l6-s1/l6-s1-observations/palpation-sensitivity": "l6-s1/l6-s1-consultation-reasons/palpation-sensitivity", + "l6-s1/anamnesis": "l6-s1/anamnesis", + "l6-s1/anamnesis/trauma-direct": "l6-s1/anamnesis/trauma-direct", + "l6-s1/anamnesis/saddle-context": "l6-s1/anamnesis/saddle-context", + "l6-s1/anamnesis/posture-context": "l6-s1/anamnesis/posture-context", + "l6-s1/anamnesis/stress-context": "l6-s1/anamnesis/stress-context", + "l6-s1/anamnesis/post-veterinary": "l6-s1/anamnesis/post-veterinary", + "l6-s1/anamnesis/no-identified-cause": "l6-s1/anamnesis/no-identified-cause", + "sacral/sacral-dysfunctions": "sacral/sacral-dysfunctions", + "sacral/sacral-dysfunctions/mobility": "sacral/sacral-dysfunctions/mobility", + "sacral/sacral-dysfunctions/mobility/nutation-restriction": "sacral/sacral-dysfunctions/mobility/nutation-restriction", + "sacral/sacral-dysfunctions/mobility/counternutation-restriction": "sacral/sacral-dysfunctions/mobility/counternutation-restriction", + "sacral/sacral-dysfunctions/mobility/sacral-torsion": "sacral/sacral-dysfunctions/mobility/sacral-torsion", + "sacral/sacral-dysfunctions/mobility/lateralisation": "sacral/sacral-dysfunctions/mobility/lateralisation", + "sacral/sacral-dysfunctions/muscular": "sacral/sacral-dysfunctions/muscular", + "sacral/sacral-dysfunctions/muscular/gluteal-tension": "sacral/sacral-dysfunctions/muscular/gluteal-tension", + "sacral/sacral-dysfunctions/muscular/longissimus-tension": "sacral/sacral-dysfunctions/muscular/longissimus-tension", + "sacral/sacral-dysfunctions/muscular/sacrocaudalis-tension": "sacral/sacral-dysfunctions/muscular/sacrocaudalis-tension", + "sacral/sacral-dysfunctions/muscular/trigger-points": "sacral/sacral-dysfunctions/muscular/trigger-points", + "sacral/sacral-dysfunctions/mechanical": "sacral/sacral-dysfunctions/mechanical", + "sacral/sacral-dysfunctions/mechanical/tuber-sacrale-asymmetry": "sacral/sacral-dysfunctions/mechanical/tuber-sacrale-asymmetry", + "sacral/sacral-dysfunctions/mechanical/pelvic-obliquity": "sacral/sacral-dysfunctions/mechanical/pelvic-obliquity", + "sacral/sacral-observations": "sacral/sacral-consultation-reasons", + "sacral/sacral-observations/ridden-work": "sacral/sacral-consultation-reasons/ridden-work", + "sacral/sacral-observations/ridden-work/hindlimb-propulsion": "sacral/sacral-consultation-reasons/ridden-work/hindlimb-propulsion", + "sacral/sacral-observations/ridden-work/canter-quality": "sacral/sacral-consultation-reasons/ridden-work/canter-quality", + "sacral/sacral-observations/ridden-work/bunny-hopping": "sacral/sacral-consultation-reasons/ridden-work/bunny-hopping", + "sacral/sacral-observations/tail-carriage": "sacral/sacral-consultation-reasons/tail-carriage", + "sacral/sacral-observations/palpation-sensitivity": "sacral/sacral-consultation-reasons/palpation-sensitivity", + "sacral/sacral-observations/new-stiffness": "sacral/sacral-consultation-reasons/new-stiffness", + "sacral/anamnesis": "sacral/anamnesis", + "sacral/anamnesis/trauma-direct": "sacral/anamnesis/trauma-direct", + "sacral/anamnesis/saddle-context": "sacral/anamnesis/saddle-context", + "sacral/anamnesis/posture-context": "sacral/anamnesis/posture-context", + "sacral/anamnesis/stress-context": "sacral/anamnesis/stress-context", + "sacral/anamnesis/post-veterinary": "sacral/anamnesis/post-veterinary", + "sacral/anamnesis/no-identified-cause": "sacral/anamnesis/no-identified-cause", + "sacroiliac/sacroiliac-dysfunctions": "sacroiliac/sacroiliac-dysfunctions", + "sacroiliac/sacroiliac-dysfunctions/articular": "sacroiliac/sacroiliac-dysfunctions/articular", + "sacroiliac/sacroiliac-dysfunctions/articular/nutation-restriction": "sacroiliac/sacroiliac-dysfunctions/articular/nutation-restriction", + "sacroiliac/sacroiliac-dysfunctions/articular/counternutation-restriction": "sacroiliac/sacroiliac-dysfunctions/articular/counternutation-restriction", + "sacroiliac/sacroiliac-dysfunctions/articular/iliac-rotation": "sacroiliac/sacroiliac-dysfunctions/articular/iliac-rotation", + "sacroiliac/sacroiliac-dysfunctions/articular/shear-restriction": "sacroiliac/sacroiliac-dysfunctions/articular/shear-restriction", + "sacroiliac/sacroiliac-dysfunctions/articular/hypomobility": "sacroiliac/sacroiliac-dysfunctions/articular/hypomobility", + "sacroiliac/sacroiliac-dysfunctions/articular/hypermobility": "sacroiliac/sacroiliac-dysfunctions/articular/hypermobility", + "sacroiliac/sacroiliac-dysfunctions/muscular": "sacroiliac/sacroiliac-dysfunctions/muscular", + "sacroiliac/sacroiliac-dysfunctions/muscular/gluteus-medius-tension": "sacroiliac/sacroiliac-dysfunctions/muscular/gluteus-medius-tension", + "sacroiliac/sacroiliac-dysfunctions/muscular/longissimus-tension": "sacroiliac/sacroiliac-dysfunctions/muscular/longissimus-tension", + "sacroiliac/sacroiliac-dysfunctions/muscular/biceps-femoris-tension": "sacroiliac/sacroiliac-dysfunctions/muscular/biceps-femoris-tension", + "sacroiliac/sacroiliac-dysfunctions/muscular/sacrotuberous-tension": "sacroiliac/sacroiliac-dysfunctions/muscular/sacrotuberous-ligament", + "sacroiliac/sacroiliac-dysfunctions/muscular/trigger-points": "sacroiliac/sacroiliac-dysfunctions/muscular/trigger-points", + "sacroiliac/sacroiliac-dysfunctions/mechanical": "sacroiliac/sacroiliac-dysfunctions/mechanical", + "sacroiliac/sacroiliac-dysfunctions/mechanical/tuber-sacrale-asymmetry": "sacroiliac/sacroiliac-dysfunctions/mechanical/tuber-sacrale-asymmetry", + "sacroiliac/sacroiliac-dysfunctions/mechanical/tuber-coxae-asymmetry": "sacroiliac/sacroiliac-dysfunctions/mechanical/tuber-coxae-asymmetry", + "sacroiliac/sacroiliac-dysfunctions/mechanical/pelvic-obliquity": "sacroiliac/sacroiliac-dysfunctions/mechanical/pelvic-obliquity", + "sacroiliac/sacroiliac-observations": "sacroiliac/sacroiliac-consultation-reasons", + "sacroiliac/sacroiliac-observations/ridden-work": "sacroiliac/sacroiliac-consultation-reasons/ridden-work", + "sacroiliac/sacroiliac-observations/ridden-work/hindlimb-engagement": "sacroiliac/sacroiliac-consultation-reasons/ridden-work/hindlimb-engagement", + "sacroiliac/sacroiliac-observations/ridden-work/canter-disunited": "sacroiliac/sacroiliac-consultation-reasons/ridden-work/canter-disunited", + "sacroiliac/sacroiliac-observations/ridden-work/bunny-hopping": "sacroiliac/sacroiliac-consultation-reasons/ridden-work/bunny-hopping", + "sacroiliac/sacroiliac-observations/ridden-work/jumping-difficulty": "sacroiliac/sacroiliac-consultation-reasons/ridden-work/jumping-difficulty", + "sacroiliac/sacroiliac-observations/croup-asymmetry": "sacroiliac/sacroiliac-consultation-reasons/croup-asymmetry", + "sacroiliac/sacroiliac-observations/hindlimb-lameness": "sacroiliac/sacroiliac-consultation-reasons/hindlimb-lameness", + "sacroiliac/anamnesis": "sacroiliac/anamnesis", + "sacroiliac/anamnesis/trauma-direct": "sacroiliac/anamnesis/trauma-direct", + "sacroiliac/anamnesis/sport-context": "sacroiliac/anamnesis/sport-context", + "sacroiliac/anamnesis/posture-context": "sacroiliac/anamnesis/posture-context", + "sacroiliac/anamnesis/stress-context": "sacroiliac/anamnesis/stress-context", + "sacroiliac/anamnesis/post-veterinary": "sacroiliac/anamnesis/post-veterinary", + "sacroiliac/anamnesis/no-identified-cause": "sacroiliac/anamnesis/no-identified-cause", + "hip/hip-dysfunctions": "hip/hip-dysfunctions", + "hip/hip-dysfunctions/articular": "hip/hip-dysfunctions/articular", + "hip/hip-dysfunctions/articular/restriction-flexion": "hip/hip-dysfunctions/articular/restriction-flexion", + "hip/hip-dysfunctions/articular/restriction-extension": "hip/hip-dysfunctions/articular/restriction-extension", + "hip/hip-dysfunctions/articular/restriction-abduction-adduction": "hip/hip-dysfunctions/articular/restriction-abduction-adduction", + "hip/hip-dysfunctions/articular/restriction-rotation": "hip/hip-dysfunctions/articular/restriction-rotation", + "hip/hip-dysfunctions/articular/hypomobility": "hip/hip-dysfunctions/articular/hypomobility", + "hip/hip-dysfunctions/articular/hypermobility": "hip/hip-dysfunctions/articular/hypermobility", + "hip/hip-dysfunctions/muscular": "hip/hip-dysfunctions/muscular", + "hip/hip-dysfunctions/muscular/gluteal-group-tension": "hip/hip-dysfunctions/muscular/gluteal-group-tension", + "hip/hip-dysfunctions/muscular/iliopsoas-tension": "hip/hip-dysfunctions/muscular/iliopsoas-tension", + "hip/hip-dysfunctions/muscular/adductors-tension": "hip/hip-dysfunctions/muscular/adductors-tension", + "hip/hip-dysfunctions/muscular/biceps-femoris-tension": "hip/hip-dysfunctions/muscular/biceps-femoris-tension", + "hip/hip-dysfunctions/muscular/trigger-points": "hip/hip-dysfunctions/muscular/trigger-points", + "hip/hip-dysfunctions/mechanical": "hip/hip-dysfunctions/mechanical", + "hip/hip-dysfunctions/mechanical/weight-bearing-asymmetry": "hip/hip-dysfunctions/mechanical/weight-bearing-asymmetry", + "hip/hip-dysfunctions/mechanical/amplitude-asymmetry": "hip/hip-dysfunctions/mechanical/amplitude-asymmetry", + "hip/hip-dysfunctions/mechanical/croup-asymmetry": "hip/hip-dysfunctions/mechanical/croup-asymmetry", + "hip/hip-observations": "hip/hip-consultation-reasons", + "hip/hip-observations/ridden-work": "hip/hip-consultation-reasons/ridden-work", + "hip/hip-observations/ridden-work/canter-difficulty": "hip/hip-consultation-reasons/ridden-work/canter-difficulty", + "hip/hip-observations/ridden-work/backing-difficulty": "hip/hip-consultation-reasons/ridden-work/backing-difficulty", + "hip/hip-observations/ridden-work/limb-engagement": "hip/hip-consultation-reasons/ridden-work/limb-engagement", + "hip/hip-observations/ridden-work/jumping-difficulty": "hip/hip-consultation-reasons/ridden-work/jumping-difficulty", + "hip/hip-observations/limb-lameness": "hip/hip-consultation-reasons/limb-lameness", + "hip/anamnesis": "hip/anamnesis", + "hip/anamnesis/trauma-direct": "hip/anamnesis/trauma-direct", + "hip/anamnesis/sport-context": "hip/anamnesis/sport-context", + "hip/anamnesis/posture-context": "hip/anamnesis/posture-context", + "hip/anamnesis/stress-context": "hip/anamnesis/stress-context", + "hip/anamnesis/post-veterinary": "hip/anamnesis/post-veterinary", + "hip/anamnesis/no-identified-cause": "hip/anamnesis/no-identified-cause", + "stifle/stifle-dysfunctions": "stifle/stifle-dysfunctions", + "stifle/stifle-dysfunctions/articular": "stifle/stifle-dysfunctions/articular", + "stifle/stifle-dysfunctions/articular/restriction-flexion": "stifle/stifle-dysfunctions/articular/restriction-flexion", + "stifle/stifle-dysfunctions/articular/restriction-extension": "stifle/stifle-dysfunctions/articular/restriction-extension", + "stifle/stifle-dysfunctions/articular/restriction-patellar-glide": "stifle/stifle-dysfunctions/articular/restriction-patellar-glide", + "stifle/stifle-dysfunctions/articular/restriction-tibial-rotation": "stifle/stifle-dysfunctions/articular/restriction-tibial-rotation", + "stifle/stifle-dysfunctions/articular/hypomobility": "stifle/stifle-dysfunctions/articular/hypomobility", + "stifle/stifle-dysfunctions/articular/hypermobility": "stifle/stifle-dysfunctions/articular/hypermobility", + "stifle/stifle-dysfunctions/muscular": "stifle/stifle-dysfunctions/muscular", + "stifle/stifle-dysfunctions/muscular/quadriceps-tension": "stifle/stifle-dysfunctions/muscular/quadriceps-tension", + "stifle/stifle-dysfunctions/muscular/hamstrings-tension": "stifle/stifle-dysfunctions/muscular/hamstrings-tension", + "stifle/stifle-dysfunctions/muscular/tfl-tension": "stifle/stifle-dysfunctions/muscular/tfl-tension", + "stifle/stifle-dysfunctions/muscular/trigger-points": "stifle/stifle-dysfunctions/muscular/trigger-points", + "stifle/stifle-dysfunctions/mechanical": "stifle/stifle-dysfunctions/mechanical", + "stifle/stifle-dysfunctions/mechanical/weight-bearing-asymmetry": "stifle/stifle-dysfunctions/mechanical/weight-bearing-asymmetry", + "stifle/stifle-dysfunctions/mechanical/amplitude-asymmetry": "stifle/stifle-dysfunctions/mechanical/amplitude-asymmetry", + "stifle/stifle-dysfunctions/mechanical/patellar-lateral-deviation": "stifle/stifle-dysfunctions/mechanical/patellar-lateral-deviation", + "stifle/stifle-observations": "stifle/stifle-consultation-reasons", + "stifle/stifle-observations/ridden-work": "stifle/stifle-consultation-reasons/ridden-work", + "stifle/stifle-observations/ridden-work/canter-difficulty": "stifle/stifle-consultation-reasons/ridden-work/canter-difficulty", + "stifle/stifle-observations/ridden-work/backing-difficulty": "stifle/stifle-consultation-reasons/ridden-work/backing-difficulty", + "stifle/stifle-observations/ridden-work/limb-engagement": "stifle/stifle-consultation-reasons/ridden-work/limb-engagement", + "stifle/stifle-observations/ridden-work/jumping-difficulty": "stifle/stifle-consultation-reasons/ridden-work/jumping-difficulty", + "stifle/stifle-observations/patellar-catching": "stifle/stifle-consultation-reasons/patellar-catching", + "stifle/stifle-observations/limb-lameness": "stifle/stifle-consultation-reasons/limb-lameness", + "stifle/anamnesis": "stifle/anamnesis", + "stifle/anamnesis/trauma-direct": "stifle/anamnesis/trauma-direct", + "stifle/anamnesis/sport-context": "stifle/anamnesis/sport-context", + "stifle/anamnesis/posture-context": "stifle/anamnesis/posture-context", + "stifle/anamnesis/stress-context": "stifle/anamnesis/stress-context", + "stifle/anamnesis/post-veterinary": "stifle/anamnesis/post-veterinary", + "stifle/anamnesis/no-identified-cause": "stifle/anamnesis/no-identified-cause", + "hock/hock-dysfunctions": "hock/hock-dysfunctions", + "hock/hock-dysfunctions/articular": "hock/hock-dysfunctions/articular", + "hock/hock-dysfunctions/articular/restriction-flexion": "hock/hock-dysfunctions/articular/restriction-flexion", + "hock/hock-dysfunctions/articular/restriction-extension": "hock/hock-dysfunctions/articular/restriction-extension", + "hock/hock-dysfunctions/articular/restriction-rotation": "hock/hock-dysfunctions/articular/restriction-rotation", + "hock/hock-dysfunctions/articular/restriction-small-joints": "hock/hock-dysfunctions/articular/restriction-small-joints", + "hock/hock-dysfunctions/articular/hypomobility": "hock/hock-dysfunctions/articular/hypomobility", + "hock/hock-dysfunctions/articular/hypermobility": "hock/hock-dysfunctions/articular/hypermobility", + "hock/hock-dysfunctions/muscular": "hock/hock-dysfunctions/muscular", + "hock/hock-dysfunctions/muscular/gastrocnemius-tension": "hock/hock-dysfunctions/muscular/gastrocnemius-tension", + "hock/hock-dysfunctions/muscular/peroneus-tertius": "hock/hock-dysfunctions/muscular/peroneus-tertius", + "hock/hock-dysfunctions/muscular/deep-digital-flexor": "hock/hock-dysfunctions/muscular/deep-digital-flexor", + "hock/hock-dysfunctions/muscular/tibialis-cranialis": "hock/hock-dysfunctions/muscular/tibialis-cranialis", + "hock/hock-dysfunctions/muscular/trigger-points": "hock/hock-dysfunctions/muscular/trigger-points", + "hock/hock-dysfunctions/mechanical": "hock/hock-dysfunctions/mechanical", + "hock/hock-dysfunctions/mechanical/weight-bearing-asymmetry": "hock/hock-dysfunctions/mechanical/weight-bearing-asymmetry", + "hock/hock-dysfunctions/mechanical/amplitude-asymmetry": "hock/hock-dysfunctions/mechanical/amplitude-asymmetry", + "hock/hock-dysfunctions/mechanical/hock-axis-asymmetry": "hock/hock-dysfunctions/mechanical/hock-axis-asymmetry", + "hock/hock-observations": "hock/hock-consultation-reasons", + "hock/hock-observations/ridden-work": "hock/hock-consultation-reasons/ridden-work", + "hock/hock-observations/ridden-work/canter-difficulty": "hock/hock-consultation-reasons/ridden-work/canter-difficulty", + "hock/hock-observations/ridden-work/backing-difficulty": "hock/hock-consultation-reasons/ridden-work/backing-difficulty", + "hock/hock-observations/ridden-work/limb-engagement": "hock/hock-consultation-reasons/ridden-work/limb-engagement", + "hock/hock-observations/ridden-work/jumping-difficulty": "hock/hock-consultation-reasons/ridden-work/jumping-difficulty", + "hock/hock-observations/limb-lameness": "hock/hock-consultation-reasons/limb-lameness", + "hock/anamnesis": "hock/anamnesis", + "hock/anamnesis/trauma-direct": "hock/anamnesis/trauma-direct", + "hock/anamnesis/sport-context": "hock/anamnesis/sport-context", + "hock/anamnesis/posture-context": "hock/anamnesis/posture-context", + "hock/anamnesis/stress-context": "hock/anamnesis/stress-context", + "hock/anamnesis/post-veterinary": "hock/anamnesis/post-veterinary", + "hock/anamnesis/no-identified-cause": "hock/anamnesis/no-identified-cause", + "hind-fetlock/hind-fetlock-dysfunctions": "hind-fetlock/hind-fetlock-dysfunctions", + "hind-fetlock/hind-fetlock-dysfunctions/articular": "hind-fetlock/hind-fetlock-dysfunctions/articular", + "hind-fetlock/hind-fetlock-dysfunctions/articular/restriction-flexion": "hind-fetlock/hind-fetlock-dysfunctions/articular/restriction-flexion", + "hind-fetlock/hind-fetlock-dysfunctions/articular/restriction-extension": "hind-fetlock/hind-fetlock-dysfunctions/articular/restriction-extension", + "hind-fetlock/hind-fetlock-dysfunctions/articular/restriction-lateromedial": "hind-fetlock/hind-fetlock-dysfunctions/articular/restriction-lateromedial", + "hind-fetlock/hind-fetlock-dysfunctions/articular/hypomobility": "hind-fetlock/hind-fetlock-dysfunctions/articular/hypomobility", + "hind-fetlock/hind-fetlock-dysfunctions/articular/hypermobility": "hind-fetlock/hind-fetlock-dysfunctions/articular/hypermobility", + "hind-fetlock/hind-fetlock-dysfunctions/muscular": "hind-fetlock/hind-fetlock-dysfunctions/muscular", + "hind-fetlock/hind-fetlock-dysfunctions/muscular/digital-flexors-tendon": "hind-fetlock/hind-fetlock-dysfunctions/muscular/digital-flexors-tendon", + "hind-fetlock/hind-fetlock-dysfunctions/muscular/digital-extensor-tendon": "hind-fetlock/hind-fetlock-dysfunctions/muscular/digital-extensor-tendon", + "hind-fetlock/hind-fetlock-dysfunctions/muscular/plantar-fascia": "hind-fetlock/hind-fetlock-dysfunctions/muscular/plantar-fascia", + "hind-fetlock/hind-fetlock-dysfunctions/mechanical": "hind-fetlock/hind-fetlock-dysfunctions/mechanical", + "hind-fetlock/hind-fetlock-dysfunctions/mechanical/weight-bearing-asymmetry": "hind-fetlock/hind-fetlock-dysfunctions/mechanical/weight-bearing-asymmetry", + "hind-fetlock/hind-fetlock-dysfunctions/mechanical/amplitude-asymmetry": "hind-fetlock/hind-fetlock-dysfunctions/mechanical/amplitude-asymmetry", + "hind-fetlock/hind-fetlock-dysfunctions/mechanical/fetlock-axis-asymmetry": "hind-fetlock/hind-fetlock-dysfunctions/mechanical/fetlock-axis-asymmetry", + "hind-fetlock/hind-fetlock-observations": "hind-fetlock/hind-fetlock-consultation-reasons", + "hind-fetlock/hind-fetlock-observations/ridden-work": "hind-fetlock/hind-fetlock-consultation-reasons/ridden-work", + "hind-fetlock/hind-fetlock-observations/ridden-work/canter-difficulty": "hind-fetlock/hind-fetlock-consultation-reasons/ridden-work/canter-difficulty", + "hind-fetlock/hind-fetlock-observations/ridden-work/backing-difficulty": "hind-fetlock/hind-fetlock-consultation-reasons/ridden-work/backing-difficulty", + "hind-fetlock/hind-fetlock-observations/ridden-work/limb-engagement": "hind-fetlock/hind-fetlock-consultation-reasons/ridden-work/limb-engagement", + "hind-fetlock/hind-fetlock-observations/ridden-work/jumping-difficulty": "hind-fetlock/hind-fetlock-consultation-reasons/ridden-work/jumping-difficulty", + "hind-fetlock/hind-fetlock-observations/limb-lameness": "hind-fetlock/hind-fetlock-consultation-reasons/limb-lameness", + "hind-fetlock/anamnesis": "hind-fetlock/anamnesis", + "hind-fetlock/anamnesis/trauma-direct": "hind-fetlock/anamnesis/trauma-direct", + "hind-fetlock/anamnesis/sport-context": "hind-fetlock/anamnesis/sport-context", + "hind-fetlock/anamnesis/posture-context": "hind-fetlock/anamnesis/posture-context", + "hind-fetlock/anamnesis/stress-context": "hind-fetlock/anamnesis/stress-context", + "hind-fetlock/anamnesis/post-veterinary": "hind-fetlock/anamnesis/post-veterinary", + "hind-fetlock/anamnesis/no-identified-cause": "hind-fetlock/anamnesis/no-identified-cause", + "caudal/caudal-dysfunctions": "caudal/caudal-dysfunctions", + "caudal/caudal-dysfunctions/segmental": "caudal/caudal-dysfunctions/segmental", + "caudal/caudal-dysfunctions/segmental/restriction-lateroflexion": "caudal/caudal-dysfunctions/segmental/restriction-lateroflexion", + "caudal/caudal-dysfunctions/segmental/restriction-dorsoventral": "caudal/caudal-dysfunctions/segmental/restriction-dorsoventral", + "caudal/caudal-dysfunctions/segmental/localized-fixation": "caudal/caudal-dysfunctions/segmental/localized-fixation", + "caudal/caudal-dysfunctions/muscular": "caudal/caudal-dysfunctions/muscular", + "caudal/caudal-dysfunctions/muscular/sacrocaudalis-dorsalis": "caudal/caudal-dysfunctions/muscular/sacrocaudalis-dorsalis", + "caudal/caudal-dysfunctions/muscular/sacrocaudalis-ventralis": "caudal/caudal-dysfunctions/muscular/sacrocaudalis-ventralis", + "caudal/caudal-dysfunctions/muscular/coccygeus-tension": "caudal/caudal-dysfunctions/muscular/coccygeus-tension", + "caudal/caudal-dysfunctions/mechanical": "caudal/caudal-dysfunctions/mechanical", + "caudal/caudal-dysfunctions/mechanical/tail-deviation": "caudal/caudal-dysfunctions/mechanical/tail-deviation", + "caudal/caudal-dysfunctions/mechanical/tail-carriage-asymmetry": "caudal/caudal-dysfunctions/mechanical/tail-carriage-asymmetry", + "caudal/caudal-observations": "caudal/caudal-consultation-reasons", + "caudal/caudal-observations/tail-clamped": "caudal/caudal-consultation-reasons/tail-clamped", + "caudal/caudal-observations/tail-swishing": "caudal/caudal-consultation-reasons/tail-swishing", + "caudal/caudal-observations/tail-deviation-new": "caudal/caudal-consultation-reasons/tail-deviation-new", + "caudal/caudal-observations/tail-handling-sensitivity": "caudal/caudal-consultation-reasons/tail-handling-sensitivity", + "caudal/anamnesis": "caudal/anamnesis", + "caudal/anamnesis/trauma-direct": "caudal/anamnesis/trauma-direct", + "caudal/anamnesis/saddle-context": "caudal/anamnesis/saddle-context", + "caudal/anamnesis/posture-context": "caudal/anamnesis/posture-context", + "caudal/anamnesis/stress-context": "caudal/anamnesis/stress-context", + "caudal/anamnesis/post-veterinary": "caudal/anamnesis/post-veterinary", + "caudal/anamnesis/no-identified-cause": "caudal/anamnesis/no-identified-cause" + } +} diff --git a/supabase/seed/anatomical-sheets/equine/draft/review/app-head.svg b/supabase/seed/anatomical-sheets/equine/draft/review/app-head.svg new file mode 100644 index 00000000..ba0113f5 --- /dev/null +++ b/supabase/seed/anatomical-sheets/equine/draft/review/app-head.svg @@ -0,0 +1,704 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Pariétal / Parietal bonePariétal / Parietal boneFrontal / Frontal boneFrontal / Frontal boneSphénoïde / Sphenoid boneSphénoïde / Sphenoid boneTemporal / Temporal boneTemporal / Temporal boneOccipital / Occipital boneOccipital / Occipital boneArticulation temporo-mandibulaire (ATM) / Temporomandibular joint (TMJ)Articulation temporo-mandibulaire (ATM) / Temporomandibular joint (TMJ)Synchondrose sphéno-occipitale (SSB) / Spheno-occipital synchondrosis (SBS)Synchondrose sphéno-occipitale (SSB) / Spheno-occipital synchondrosis (SBS)Appareil hyoïdien / Hyoid apparatusAppareil hyoïdien / Hyoid apparatusCharnière C0-C1 (atlanto-occipitale) / C0-C1 junction (atlanto-occipital joint)Charnière C0-C1 (atlanto-occipitale) / C0-C1 junction (atlanto-occipital joint) \ No newline at end of file diff --git a/supabase/seed/anatomical-sheets/equine/draft/review/app-main.svg b/supabase/seed/anatomical-sheets/equine/draft/review/app-main.svg new file mode 100644 index 00000000..0dddae59 --- /dev/null +++ b/supabase/seed/anatomical-sheets/equine/draft/review/app-main.svg @@ -0,0 +1,704 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Boulet postérieur (métatarso-phalangien) / Hind fetlockBoulet postérieur (métatarso-phalangien) / Hind fetlockJarret (tarso-crurale et intertarsiennes) / Hock (tarsal joints)Jarret (tarso-crurale et intertarsiennes) / Hock (tarsal joints)Grasset (fémoro-tibiale et fémoro-patellaire) / Stifle jointGrasset (fémoro-tibiale et fémoro-patellaire) / Stifle jointHanche (coxo-fémorale) / Hip jointHanche (coxo-fémorale) / Hip jointArticulation sacro-iliaque / Sacroiliac jointArticulation sacro-iliaque / Sacroiliac jointÉpaule (scapulo-humérale) / Shoulder jointÉpaule (scapulo-humérale) / Shoulder jointCoude (huméro-radio-ulnaire) / Elbow jointCoude (huméro-radio-ulnaire) / Elbow jointCarpe (antébrachio-carpienne, médio-carpienne) / Carpus (carpal joints)Carpe (antébrachio-carpienne, médio-carpienne) / Carpus (carpal joints)Boulet antérieur (métacarpo-phalangien) / Fore fetlockBoulet antérieur (métacarpo-phalangien) / Fore fetlockSésamoïdes antérieurs (boulet) / Forelimb sesamoidsSésamoïdes antérieurs (boulet) / Forelimb sesamoidsCharnière L6-S1 (lombo-sacrée) / L6-S1 junction (lumbosacral joint)Charnière L6-S1 (lombo-sacrée) / L6-S1 junction (lumbosacral joint)Charnière T18-L1 (thoraco-lombaire) / T18-L1 junction (thoracolumbar)Charnière T18-L1 (thoraco-lombaire) / T18-L1 junction (thoracolumbar)Charnière C7-T1 (cervico-thoracique) / C7-T1 junction (cervicothoracic)Charnière C7-T1 (cervico-thoracique) / C7-T1 junction (cervicothoracic)Vertèbres caudales / Caudal vertebraeVertèbres sacrales / Sacral vertebraeVertèbres lombaires / Lumbar vertebraeVertèbres thoraciques / Thoracic vertebraeVertèbres cervicales / Cervical vertebraeTête (vue latérale gauche) / Tête (vue latérale gauche) \ No newline at end of file diff --git a/supabase/seed/anatomical-sheets/equine/draft/sheet-ref.json b/supabase/seed/anatomical-sheets/equine/draft/sheet-ref.json new file mode 100644 index 00000000..5633394d --- /dev/null +++ b/supabase/seed/anatomical-sheets/equine/draft/sheet-ref.json @@ -0,0 +1,7 @@ +{ + "sheet_id": "503dc301-a8b1-50d4-9e44-0919b2fc2916", + "version_id": null, + "document_sha256": "27c7383c445c73dc2001ebf4794a3ea63d416910bbbaa0d7848dd720de7c2660", + "schema_version": 2, + "species_id": "equine" +} From ce2ec26112268dabd631a5a3c6d4f404079073d5 Mon Sep 17 00:00:00 2001 From: bchanot Date: Sat, 10 Oct 2026 11:36:14 +0200 Subject: [PATCH 04/16] =?UTF-8?q?feat(app):=20application=20on=20the=20can?= =?UTF-8?q?onical=20sheet=20=E2=80=94=20report=20v3=20store=20with=20v2=20?= =?UTF-8?q?draft=20migration,=20bundled=20SheetProvider=20(SHEET=5FBUNDLE)?= =?UTF-8?q?,=20annotation=20layer=20rendered=20from=20the=20document,=20zo?= =?UTF-8?q?ne=20interaction=20service,=20pickers=20and=20cards=20on=20the?= =?UTF-8?q?=20sheet=20index,=20PDF=20v3=20export=20with=20v2=20archive=20i?= =?UTF-8?q?mport;=20legacy=20registry,=20matchers,=20editors=20and=20asset?= =?UTF-8?q?s=20removed?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Dockerfile | 7 +- apps/app/package.json | 3 +- apps/app/public/pathology-editor.html | 1700 ------ apps/app/scripts/scaffold-species.mjs | 238 - apps/app/src/anatomy/drawing.ts | 97 + apps/app/src/anatomy/labels.ts | 19 - apps/app/src/anatomy/svgConvention.ts | 107 - apps/app/src/anatomy/svgLoader.ts | 17 - apps/app/src/anatomy/types.ts | 55 - apps/app/src/app/App.tsx | 9 +- apps/app/src/app/routes/EditorRoute.tsx | 590 +-- apps/app/src/app/routes/EditorsRoute.tsx | 42 - apps/app/src/app/routes/HomeRoute.tsx | 74 +- apps/app/src/app/routes/NewReportRoute.tsx | 95 +- apps/app/src/app/routes/NotFoundRoute.tsx | 8 +- apps/app/src/app/routes/SvgEditorRoute.tsx | 1858 ------- apps/app/src/components/brand/Footer.tsx | 10 +- .../src/components/canvas/AnatomyCanvas.tsx | 148 +- .../app/src/components/canvas/DetailModal.tsx | 25 +- .../observation/FindingsTreePicker.tsx | 185 +- .../observation/LateralityPicker.tsx | 2 +- .../observation/ObservationCard.tsx | 295 +- .../observation/ObservationList.tsx | 14 +- .../observation/SeveritySelector.tsx | 22 +- .../components/observation/VertebraPicker.tsx | 123 +- apps/app/src/components/report/AnimalForm.tsx | 53 +- .../src/components/report/ConclusionPanel.tsx | 23 +- .../report/NextAppointmentPicker.tsx | 2 +- .../components/report/PractitionerForm.tsx | 32 +- .../src/components/report/ReportHeader.tsx | 7 +- apps/app/src/components/ui/Card.tsx | 6 +- apps/app/src/components/ui/Chip.tsx | 5 +- apps/app/src/components/ui/Dialog.tsx | 12 +- apps/app/src/components/ui/Input.tsx | 25 +- apps/app/src/components/ui/Select.tsx | 29 +- apps/app/src/components/ui/Textarea.tsx | 25 +- apps/app/src/domain/schema/animal.ts | 17 - apps/app/src/domain/schema/findings.ts | 67 - apps/app/src/domain/schema/observation.ts | 61 - apps/app/src/domain/schema/practitioner.ts | 11 - apps/app/src/domain/schema/report.ts | 33 - apps/app/src/domain/species/equine/index.ts | 18 - .../domain/species/equine/pathologies.json | 4616 ----------------- .../src/domain/species/equine/pathologies.ts | 13 - apps/app/src/domain/species/registry.ts | 57 - apps/app/src/domain/species/types.ts | 32 - apps/app/src/i18n/en.ts | 136 +- apps/app/src/i18n/fr.ts | 144 +- apps/app/src/lib/dates.ts | 3 +- apps/app/src/lib/spineZones.ts | 131 - apps/app/src/lib/zoneMatch.ts | 130 - apps/app/src/pdf/attachment.ts | 114 +- apps/app/src/pdf/export.ts | 108 +- apps/app/src/pdf/import.ts | 22 +- apps/app/src/pdf/render/conclusionPage.ts | 18 +- apps/app/src/pdf/render/footer.ts | 13 +- apps/app/src/pdf/render/header.ts | 2 +- apps/app/src/pdf/render/observationPage.ts | 372 +- apps/app/src/pdf/render/svgToPng.ts | 7 +- apps/app/src/services/sheetIndex.ts | 113 + apps/app/src/services/zoneInteraction.ts | 213 + apps/app/src/sheets/provider.ts | 83 + apps/app/src/sheets/useSheet.ts | 54 + apps/app/src/sheets/virtual-sheet.d.ts | 3 + apps/app/src/state/persistence.ts | 41 + apps/app/src/state/practitionerCache.ts | 5 +- apps/app/src/state/reportStore.ts | 262 +- apps/app/src/styles/svg-editor.css | 528 -- apps/app/tests/helpers/sheet.ts | 39 + apps/app/tests/unit/anatomy.horse.test.ts | 72 - .../tests/unit/anatomy.svgConvention.test.ts | 99 - apps/app/tests/unit/anatomy.svgLoader.test.ts | 23 - apps/app/tests/unit/char.catalog.test.ts | 169 - apps/app/tests/unit/char.clickChain.test.tsx | 293 -- apps/app/tests/unit/char.i18nSpecies.test.tsx | 127 - .../tests/unit/char.pathologyEditor.test.ts | 146 - apps/app/tests/unit/char.pdfFull.test.ts | 250 - .../tests/unit/char.schemaPersistence.test.ts | 115 - .../tests/unit/char.svgCatalogLink.test.ts | 222 - .../unit/components.AnatomyCanvas.test.tsx | 131 +- .../components.FindingsTreePicker.test.tsx | 344 +- .../unit/components.LanguageSwitcher.test.tsx | 10 +- .../unit/components.VertebraPicker.test.tsx | 157 +- apps/app/tests/unit/lib.spineZones.test.ts | 120 - apps/app/tests/unit/lib.zoneMatch.test.ts | 154 - .../tests/unit/pdf.attachment.inflate.test.ts | 4 +- apps/app/tests/unit/pdf.attachment.test.ts | 41 +- apps/app/tests/unit/pdf.roundtrip.test.ts | 404 +- apps/app/tests/unit/pdf.svgToPng.test.ts | 23 +- apps/app/tests/unit/pdf.zoneLabels.test.ts | 96 - .../tests/unit/routes.EditorRoute.test.tsx | 198 + .../app/tests/unit/schema.observation.test.ts | 157 - apps/app/tests/unit/schema.report.test.ts | 53 - .../unit/services.zoneInteraction.test.ts | 214 + apps/app/tests/unit/sheets.provider.test.ts | 113 + apps/app/tests/unit/smoke.test.ts | 23 +- .../tests/unit/species.equineFindings.test.ts | 52 - apps/app/tests/unit/species.registry.test.ts | 24 - apps/app/tests/unit/state.draftMirror.test.ts | 35 - .../unit/state.reportStore.restore.test.ts | 58 - .../unit/state.reportStore.setters.test.ts | 56 - apps/app/tests/unit/state.reportStore.test.ts | 223 +- apps/app/tsconfig.node.json | 16 +- apps/app/vite.config.ts | 23 +- apps/app/vite/sheet-bundle.ts | 95 + apps/app/vitest.config.ts | 8 + docs/ADDING-A-SPECIES.md | 230 - docs/ANATOMY-SVG-CONVENTION.md | 179 - package.json | 4 +- packages/anatomy/src/legacy/sources.ts | 8 +- .../equine/legacy-sources}/Horse.svg | 0 .../equine/legacy-sources}/Horse_head.svg | 0 .../equine/legacy-sources}/pathologies.json | 0 .../equine/legacy-sources}/vertebrae.ts | 0 114 files changed, 3560 insertions(+), 14637 deletions(-) delete mode 100644 apps/app/public/pathology-editor.html delete mode 100755 apps/app/scripts/scaffold-species.mjs create mode 100644 apps/app/src/anatomy/drawing.ts delete mode 100644 apps/app/src/anatomy/labels.ts delete mode 100644 apps/app/src/anatomy/svgConvention.ts delete mode 100644 apps/app/src/anatomy/svgLoader.ts delete mode 100644 apps/app/src/anatomy/types.ts delete mode 100644 apps/app/src/app/routes/EditorsRoute.tsx delete mode 100644 apps/app/src/app/routes/SvgEditorRoute.tsx delete mode 100644 apps/app/src/domain/schema/animal.ts delete mode 100644 apps/app/src/domain/schema/findings.ts delete mode 100644 apps/app/src/domain/schema/observation.ts delete mode 100644 apps/app/src/domain/schema/practitioner.ts delete mode 100644 apps/app/src/domain/schema/report.ts delete mode 100644 apps/app/src/domain/species/equine/index.ts delete mode 100644 apps/app/src/domain/species/equine/pathologies.json delete mode 100644 apps/app/src/domain/species/equine/pathologies.ts delete mode 100644 apps/app/src/domain/species/registry.ts delete mode 100644 apps/app/src/domain/species/types.ts delete mode 100644 apps/app/src/lib/spineZones.ts delete mode 100644 apps/app/src/lib/zoneMatch.ts create mode 100644 apps/app/src/services/sheetIndex.ts create mode 100644 apps/app/src/services/zoneInteraction.ts create mode 100644 apps/app/src/sheets/provider.ts create mode 100644 apps/app/src/sheets/useSheet.ts create mode 100644 apps/app/src/sheets/virtual-sheet.d.ts create mode 100644 apps/app/src/state/persistence.ts delete mode 100644 apps/app/src/styles/svg-editor.css create mode 100644 apps/app/tests/helpers/sheet.ts delete mode 100644 apps/app/tests/unit/anatomy.horse.test.ts delete mode 100644 apps/app/tests/unit/anatomy.svgConvention.test.ts delete mode 100644 apps/app/tests/unit/anatomy.svgLoader.test.ts delete mode 100644 apps/app/tests/unit/char.catalog.test.ts delete mode 100644 apps/app/tests/unit/char.clickChain.test.tsx delete mode 100644 apps/app/tests/unit/char.i18nSpecies.test.tsx delete mode 100644 apps/app/tests/unit/char.pathologyEditor.test.ts delete mode 100644 apps/app/tests/unit/char.pdfFull.test.ts delete mode 100644 apps/app/tests/unit/char.schemaPersistence.test.ts delete mode 100644 apps/app/tests/unit/char.svgCatalogLink.test.ts delete mode 100644 apps/app/tests/unit/lib.spineZones.test.ts delete mode 100644 apps/app/tests/unit/lib.zoneMatch.test.ts delete mode 100644 apps/app/tests/unit/pdf.zoneLabels.test.ts create mode 100644 apps/app/tests/unit/routes.EditorRoute.test.tsx delete mode 100644 apps/app/tests/unit/schema.observation.test.ts delete mode 100644 apps/app/tests/unit/schema.report.test.ts create mode 100644 apps/app/tests/unit/services.zoneInteraction.test.ts create mode 100644 apps/app/tests/unit/sheets.provider.test.ts delete mode 100644 apps/app/tests/unit/species.equineFindings.test.ts delete mode 100644 apps/app/tests/unit/species.registry.test.ts delete mode 100644 apps/app/tests/unit/state.draftMirror.test.ts delete mode 100644 apps/app/tests/unit/state.reportStore.restore.test.ts delete mode 100644 apps/app/tests/unit/state.reportStore.setters.test.ts create mode 100644 apps/app/vite/sheet-bundle.ts delete mode 100644 docs/ADDING-A-SPECIES.md delete mode 100644 docs/ANATOMY-SVG-CONVENTION.md rename {apps/app/public/species/equine => supabase/seed/anatomical-sheets/equine/legacy-sources}/Horse.svg (100%) rename {apps/app/public/species/equine => supabase/seed/anatomical-sheets/equine/legacy-sources}/Horse_head.svg (100%) rename {apps/app/public/species/equine => supabase/seed/anatomical-sheets/equine/legacy-sources}/pathologies.json (100%) rename {apps/app/src/domain/species/equine => supabase/seed/anatomical-sheets/equine/legacy-sources}/vertebrae.ts (100%) diff --git a/Dockerfile b/Dockerfile index 27e293d4..e5ae5525 100644 --- a/Dockerfile +++ b/Dockerfile @@ -17,7 +17,12 @@ COPY packages/supabase/package.json packages/supabase/ RUN pnpm install --frozen-lockfile -# Copy source and build the private app only +# Copy source and build the private app only. +# SHEET_BUNDLE=draft embeds the reference equine DRAFT (medically unvalidated) +# into the bundle for a preview deployment; the default image carries no sheet +# (BDR-037, Step 5 D2): `docker build --build-arg SHEET_BUNDLE=draft .` +ARG SHEET_BUNDLE=none +ENV SHEET_BUNDLE=$SHEET_BUNDLE COPY . . RUN pnpm --filter @faunosteo/app build diff --git a/apps/app/package.json b/apps/app/package.json index 32ae0698..6e9b44a5 100644 --- a/apps/app/package.json +++ b/apps/app/package.json @@ -11,8 +11,7 @@ "typecheck": "tsc -p tsconfig.json --noEmit", "test": "vitest", "test:run": "vitest run", - "lint": "eslint . --max-warnings 0", - "scaffold:species": "node scripts/scaffold-species.mjs" + "lint": "eslint . --max-warnings 0" }, "dependencies": { "@faunosteo/anatomy": "workspace:*", diff --git a/apps/app/public/pathology-editor.html b/apps/app/public/pathology-editor.html deleted file mode 100644 index adb79e21..00000000 --- a/apps/app/public/pathology-editor.html +++ /dev/null @@ -1,1700 +0,0 @@ - - - - - - - Faunosteo — Éditeur de pathologies - - - -
-
- Faunosteo - -
-
- - -
-
- -
-
-
-
-
- -
-
-

-
-
- -
- - -
-
- - - - diff --git a/apps/app/scripts/scaffold-species.mjs b/apps/app/scripts/scaffold-species.mjs deleted file mode 100755 index c6f03e51..00000000 --- a/apps/app/scripts/scaffold-species.mjs +++ /dev/null @@ -1,238 +0,0 @@ -#!/usr/bin/env node -/** - * Scaffolds a new species: prompts for the few required values then - * writes the boilerplate that the auto-discovery registry expects. - * - * Run via: pnpm scaffold:species - * or: node scripts/scaffold-species.mjs - * - * The script never touches existing files — it refuses to write if any - * of the targets already exist, so you can rerun it after fixing typos - * without losing work. SVG assets are NOT created; drop them in - * `public/species//` yourself after the script finishes. - */ - -import { existsSync } from 'node:fs' -import { mkdir, writeFile } from 'node:fs/promises' -import { dirname, resolve } from 'node:path' -import { fileURLToPath } from 'node:url' -import readline from 'node:readline/promises' -import { stdin as input, stdout as output } from 'node:process' - -const HERE = dirname(fileURLToPath(import.meta.url)) -const PROJECT_ROOT = resolve(HERE, '..') - -const rl = readline.createInterface({ input, output }) - -async function ask(question, fallback) { - const suffix = fallback === undefined ? '' : ` [${fallback}]` - const raw = (await rl.question(`${question}${suffix}: `)).trim() - return raw || (fallback ?? '') -} - -async function askRequired(question, validate) { - while (true) { - const v = (await rl.question(`${question}: `)).trim() - if (!v) { - console.log(' (required)') - continue - } - if (validate) { - const err = validate(v) - if (err) { - console.log(` ${err}`) - continue - } - } - return v - } -} - -async function askPositiveInt(question, fallback) { - while (true) { - const v = await ask(question, String(fallback)) - const n = Number(v) - if (Number.isInteger(n) && n > 0) return n - console.log(' enter a positive integer') - } -} - -function isKebab(s) { - return /^[a-z][a-z0-9-]*$/.test(s) -} - -function capitalize(s) { - return s.charAt(0).toUpperCase() + s.slice(1) -} - -function indexTs({ id, labelFr, labelEn, mainSvgPath, details, formulaConstName }) { - const detailLines = details - .map((d) => ` ${d.key}: '${d.path}',`) - .join('\n') - return `import type { SpeciesManifest } from '@/domain/species/types' -import { ${formulaConstName} } from './vertebrae' - -const ${id}: SpeciesManifest = { - id: '${id}', - labelFr: '${labelFr.replace(/'/g, "\\'")}', - labelEn: '${labelEn.replace(/'/g, "\\'")}', - mainSvg: '${mainSvgPath}', - details: { -${detailLines} - }, - vertebralFormula: ${formulaConstName}, - findings: () => import('./pathologies'), -} - -// Default export is the convention picked up by the registry's -// import.meta.glob() auto-discovery. -export default ${id} -` -} - -function vertebraeTs({ formulaConstName, labelFr, formula }) { - return `import type { VertebralFormula } from '@/domain/species/types' - -/** Vertebral formula for ${labelFr}. Adjust to species-specific anatomy. */ -export const ${formulaConstName}: VertebralFormula = { - C: ${formula.C}, - T: ${formula.T}, - L: ${formula.L}, - S: ${formula.S}, - Cd: ${formula.Cd}, -} -` -} - -function pathologiesTs() { - return `import { - SpeciesFindingsSchema, - type SpeciesFindings, -} from '@/domain/schema/findings' -import data from './pathologies.json' - -const FINDINGS: SpeciesFindings = SpeciesFindingsSchema.parse(data) - -export default FINDINGS -` -} - -function pathologiesJsonTemplate({ id, labelFr, labelEn }) { - return JSON.stringify( - { - schema_version: '1.1', - scope_disclaimer: - "Les éléments listés correspondent au périmètre légal de l'ostéopathie animale : dysfonctions ostéopathiques palpées, observations cliniques et motifs de consultation. Aucun diagnostic médical n'est posé. Toute pathologie organique relève du vétérinaire.", - species: { - id, - name_fr: labelFr, - name_en: labelEn, - }, - zones: {}, - }, - null, - 2, - ) -} - -async function collectDetails() { - const details = [] - console.log('\nDetail popup SVGs (optional — leave key blank to stop).') - console.log(' Each "key" must match a data-anno-opens-detail value on a hitbox in the main SVG.') - for (;;) { - const key = (await rl.question(' detail key (e.g. head, patte): ')).trim() - if (!key) return details - if (!isKebab(key)) { - console.log(' → key must be kebab-case (lowercase, hyphen-separated). Try again.') - continue - } - const path = await askRequired( - ` detail SVG path for "${key}" (e.g. /species/canine/Dog_head.svg)`, - (v) => (v.startsWith('/species/') ? '' : ' path must start with /species/'), - ) - details.push({ key, path }) - } -} - -async function main() { - console.log('\nZoosteo — new species scaffold') - console.log('-----------------------------------\n') - - const id = await askRequired( - 'species id (kebab-case, e.g. canine, feline, bovine)', - (v) => (isKebab(v) ? '' : 'must be kebab-case (lowercase letters / digits / hyphens; start with a letter)'), - ) - const labelFr = await askRequired('display label (FR), e.g. "Chien"') - const labelEn = await ask('display label (EN), e.g. "Dog"', capitalize(id)) - const assetFolder = await ask( - 'public asset folder under /species/', - id, - ) - const mainSvgFile = await askRequired( - `main SVG filename in /public/species/${assetFolder}/ (e.g. Dog.svg)`, - ) - const mainSvgPath = `/species/${assetFolder}/${mainSvgFile}` - - const details = await collectDetails() - - console.log('\nVertebral formula (counts per region):') - const formula = { - C: await askPositiveInt(' cervical (C)', 7), - T: await askPositiveInt(' thoracic (T)', 13), - L: await askPositiveInt(' lumbar (L)', 6), - S: await askPositiveInt(' sacral (S)', 5), - Cd: await askPositiveInt(' caudal (Cd)', 18), - } - - const formulaConstName = `${id.replace(/-/g, '_').toUpperCase()}_VERTEBRAL_FORMULA` - const speciesDir = resolve(PROJECT_ROOT, 'src/domain/species', id) - const targets = { - 'index.ts': indexTs({ id, labelFr, labelEn, mainSvgPath, details, formulaConstName }), - 'vertebrae.ts': vertebraeTs({ formulaConstName, labelFr, formula }), - 'pathologies.ts': pathologiesTs(), - 'pathologies.json': pathologiesJsonTemplate({ id, labelFr, labelEn }), - } - - // Refuse to clobber. - for (const file of Object.keys(targets)) { - const p = resolve(speciesDir, file) - if (existsSync(p)) { - console.error(`\n✖ ${p} already exists. Aborting to protect existing work.`) - process.exit(1) - } - } - - await mkdir(speciesDir, { recursive: true }) - for (const [file, body] of Object.entries(targets)) { - await writeFile(resolve(speciesDir, file), body) - } - - const publicDir = resolve(PROJECT_ROOT, 'public/species', assetFolder) - await mkdir(publicDir, { recursive: true }) - - console.log(`\n✓ Created src/domain/species/${id}/`) - for (const file of Object.keys(targets)) console.log(` - ${file}`) - console.log(`✓ Ensured public/species/${assetFolder}/ exists`) - - console.log('\nNext steps:') - console.log(` 1. Drop your SVG assets into public/species/${assetFolder}/`) - console.log(` - main: ${mainSvgFile}`) - for (const d of details) { - const file = d.path.split('/').pop() - console.log(` - detail "${d.key}": ${file}`) - } - console.log(` 2. Author the findings tree in src/domain/species/${id}/pathologies.json`) - console.log(` (schema documented in src/domain/schema/findings.ts).`) - console.log(` 3. Adjust the vertebral counts in vertebrae.ts if needed.`) - console.log(` 4. Run: pnpm typecheck && pnpm test:run && pnpm dev`) - console.log(' The new species will appear automatically in the animal picker.\n') -} - -main() - .catch((err) => { - console.error('Scaffold failed:', err) - process.exit(1) - }) - .finally(() => { - rl.close() - }) diff --git a/apps/app/src/anatomy/drawing.ts b/apps/app/src/anatomy/drawing.ts new file mode 100644 index 00000000..cbee6683 --- /dev/null +++ b/apps/app/src/anatomy/drawing.ts @@ -0,0 +1,97 @@ +import { + createLayerElement, + renderAnnotationLayer, + viewBoxOf, +} from '@faunosteo/anatomy/render' +import type { SheetView } from '@faunosteo/domain' +import type { SheetIndex } from '@/services/sheetIndex' + +/** + * Builds the inline SVG of one view: the sheet's drawing (sanitised asset + * text) framed on the view's box, plus the annotation layer generated from + * the document. The drawing is parsed once per asset and cloned per view. + */ + +const SVG_NS = 'http://www.w3.org/2000/svg' +const FORBIDDEN_TAGS = ['script', 'foreignObject', 'iframe', 'object', 'embed'] + +export type ViewStates = ReadonlyMap + +/** Drops scripts, embedded documents, event handlers and script URLs (LRN-025). */ +export function sanitizeSvg(root: Element): void { + for (const tag of FORBIDDEN_TAGS) { + for (const el of Array.from(root.getElementsByTagName(tag))) el.remove() + } + for (const el of Array.from(root.querySelectorAll('*'))) { + for (const attr of Array.from(el.attributes)) { + const name = attr.name.toLowerCase() + const value = attr.value.trim().toLowerCase() + if (name.startsWith('on') || value.startsWith('javascript:')) { + el.removeAttribute(attr.name) + } + } + } +} + +export function parseDrawing(svgText: string): SVGSVGElement { + const doc = new DOMParser().parseFromString(svgText, 'image/svg+xml') + if (doc.querySelector('parsererror')) throw new Error('invalid SVG asset') + const root = doc.documentElement + if (root.tagName.toLowerCase() !== 'svg') + throw new Error('asset root is not ') + sanitizeSvg(root) + return root as unknown as SVGSVGElement +} + +const parsed = new Map() + +function drawingOf(index: SheetIndex, assetId: string): SVGSVGElement { + const key = `${index.sheet.ref.documentSha256}:${assetId}` + let root = parsed.get(key) + if (!root) { + const text = index.sheet.assets[assetId] + if (text === undefined) throw new Error(`asset ${assetId} not bundled`) + root = parseDrawing(text) + parsed.set(key, root) + } + return root +} + +/** The asset a view draws: its own, else its parent's (a crop). */ +export function assetOfView(index: SheetIndex, view: SheetView): string { + if (view.svg_asset_id) return view.svg_asset_id + if (view.kind === 'detail') { + const parent = index.view(view.parent_view_id) + if (parent) return assetOfView(index, parent) + } + throw new Error(`view ${view.id} has no asset`) +} + +export function buildViewSvg( + index: SheetIndex, + viewId: string, + states: ViewStates, +): SVGSVGElement { + const view = index.view(viewId) + if (!view) throw new Error(`unknown view ${viewId}`) + const source = drawingOf(index, assetOfView(index, view)) + const svg = document.createElementNS(SVG_NS, 'svg') + for (const attr of Array.from(source.attributes)) { + if (attr.name === 'width' || attr.name === 'height') continue + svg.setAttribute(attr.name, attr.value) + } + svg.setAttribute( + 'viewBox', + viewBoxOf(view) ?? source.getAttribute('viewBox') ?? '0 0 100 100', + ) + for (const child of Array.from(source.childNodes)) { + svg.appendChild(document.importNode(child, true)) + } + const layer = renderAnnotationLayer({ + document: index.sheet.document, + viewId, + states, + }) + svg.appendChild(createLayerElement(document, layer) as unknown as Node) + return svg +} diff --git a/apps/app/src/anatomy/labels.ts b/apps/app/src/anatomy/labels.ts deleted file mode 100644 index fe2f0fed..00000000 --- a/apps/app/src/anatomy/labels.ts +++ /dev/null @@ -1,19 +0,0 @@ -import type { Locale } from '@/i18n/types' -import { pickLocaleLabel } from '@/i18n/pickLocaleLabel' -import type { Bone } from './types' - -/** - * Resolves the user-facing label for an anatomical zone given the active - * locale. Falls back to the opposite language when the requested one is - * missing (some SVG hitboxes carry only `data-anno-name-fr`), then to the - * provided fallback (typically the raw boneId) so the UI never renders - * an empty label. - */ -export function boneLabel( - bone: Bone | undefined, - locale: Locale, - fallback: string, -): string { - if (!bone) return fallback - return pickLocaleLabel(bone.fr, bone.en, locale, fallback) -} diff --git a/apps/app/src/anatomy/svgConvention.ts b/apps/app/src/anatomy/svgConvention.ts deleted file mode 100644 index 67c0c3cc..00000000 --- a/apps/app/src/anatomy/svgConvention.ts +++ /dev/null @@ -1,107 +0,0 @@ -import { SvgConventionError } from './types' -import type { Bone, BoneCategory } from './types' - -/** - * Validates that an annotated SVG element carries the two attributes the - * application needs to wire it up: a stable id (`data-anno-id`) and a - * category bucket (`data-anno-category`). Labels (`data-anno-name-fr/en`) - * and the popup trigger (`data-anno-opens-detail`) are optional and - * checked only at use-site. - * - * The category value itself is opaque to the application — any non-empty - * string is accepted. New SVGs are free to introduce new categories - * without touching this parser. - */ -function validateBoneElement(el: Element): void { - const boneId = el.getAttribute('data-anno-id') ?? '' - if (!boneId) { - throw new SvgConventionError( - 'Element with missing data-anno-id', - boneId, - 'data-anno-id', - ) - } - const cat = el.getAttribute('data-anno-category') ?? '' - if (!cat) { - throw new SvgConventionError( - `Element data-anno-id="${boneId}" missing attribute data-anno-category`, - boneId, - 'data-anno-category', - ) - } -} - -/** - * Parses an SVG document and returns a map of `data-anno-id` → Bone. - * - * Every element carrying `data-anno-id` is collected. Multiple elements - * may share the same id (e.g. hitbox + visible layer); they all end up - * grouped under the same Bone with all elements in `els`. - * - * Throws `SvgConventionError` only on the two required attributes - * (`data-anno-id`, `data-anno-category`). Labels are optional. - */ -export function parseSvgBones(svgRoot: SVGSVGElement): Map { - const map = new Map() - const all = svgRoot.querySelectorAll('[data-anno-id]') - all.forEach((el) => { - validateBoneElement(el) - const id = el.getAttribute('data-anno-id') as string - const fr = el.getAttribute('data-anno-name-fr') ?? '' - const en = el.getAttribute('data-anno-name-en') ?? '' - const category = el.getAttribute('data-anno-category') as BoneCategory - const opensDetail = - el.getAttribute('data-anno-opens-detail') ?? undefined - const special = el.getAttribute('data-anno-special') ?? undefined - const lateral = (el.getAttribute('data-anno-lateral') ?? undefined) as - | 'bilateral' - | 'unpaired' - | undefined - - const existing = map.get(id) - if (existing) { - existing.els.push(el) - if (opensDetail && !existing.opensDetail) { - existing.opensDetail = opensDetail - } - if (special && !existing.special) { - existing.special = special - } - if (lateral && !existing.lateral) { - existing.lateral = lateral - } - if (!existing.fr && fr) existing.fr = fr - if (!existing.en && en) existing.en = en - } else { - map.set(id, { - id, - fr, - en, - category, - opensDetail, - special, - lateral, - els: [el], - }) - } - }) - return map -} - -/** - * Walks up from `event.target` to find the nearest element carrying - * `data-anno-id`. Returns null when the click did not land on an - * annotated element. - */ -export function getBoneIdFromEvent(event: Event): string | null { - return getAnnotatedElement(event)?.getAttribute('data-anno-id') || null -} - -export function getAnnotatedElement(event: Event): Element | null { - let node = event.target as Element | null - while (node && node.nodeType === 1) { - if (node.hasAttribute('data-anno-id')) return node - node = node.parentElement - } - return null -} diff --git a/apps/app/src/anatomy/svgLoader.ts b/apps/app/src/anatomy/svgLoader.ts deleted file mode 100644 index 2084f78b..00000000 --- a/apps/app/src/anatomy/svgLoader.ts +++ /dev/null @@ -1,17 +0,0 @@ -export async function loadSvg(publicPath: string): Promise { - const resp = await fetch(publicPath) - if (!resp.ok) { - throw new Error(`Failed to load SVG ${publicPath}: HTTP ${resp.status}`) - } - const text = await resp.text() - const doc = new DOMParser().parseFromString(text, 'image/svg+xml') - const parseErr = doc.querySelector('parsererror') - if (parseErr) { - throw new Error(`Invalid SVG at ${publicPath}: ${parseErr.textContent}`) - } - const root = doc.documentElement - if (root.tagName.toLowerCase() !== 'svg') { - throw new Error(`Root element of ${publicPath} is not `) - } - return root as unknown as SVGSVGElement -} diff --git a/apps/app/src/anatomy/types.ts b/apps/app/src/anatomy/types.ts deleted file mode 100644 index f0c3c03c..00000000 --- a/apps/app/src/anatomy/types.ts +++ /dev/null @@ -1,55 +0,0 @@ -/** - * `data-anno-category` is a free-form string supplied by the SVG. - * - * The application never branches on category values — it treats every - * annotation the same way. Categories are kept around because they're - * useful for grouping and future filtering, but no code path here may - * rely on a closed set. - */ -export type BoneCategory = string - -/** - * Logical annotation as parsed from an SVG. All DOM elements sharing the - * same `data-anno-id` are grouped into one Bone. `id` is the persisted - * identifier surfaced in the report JSON contract - * (`ObservationZone.boneId`); keep it stable across SVG renames. - */ -export interface Bone { - id: string - /** French label from data-anno-name-fr — may be empty for opens-detail-only triggers */ - fr: string - /** English label from data-anno-name-en — may be empty */ - en: string - /** Raw value from data-anno-category — opaque to the application */ - category: BoneCategory - /** Detail popup id from data-anno-opens-detail, if present */ - opensDetail?: string - /** - * Free-form behavior hint from `data-anno-special`. - * - * Known values consumed by the application: - * - `vertebral-precision`: clicking the zone opens VertebraPicker. - * - * Opaque to the parser; new values are accepted without code changes. - */ - special?: string - /** Laterality hint from data-anno-lateral — bilateral or unpaired */ - lateral?: 'bilateral' | 'unpaired' - /** All DOM elements carrying this annotation (used for colorization) */ - els: Element[] -} - -/** Visual state applied to SVG elements (active-observation highlight). */ -export type BoneState = 'current' | 'default' - -/** Error thrown when SVG violates the convention. */ -export class SvgConventionError extends Error { - constructor( - message: string, - public readonly boneId: string, - public readonly missingAttribute: string, - ) { - super(message) - this.name = 'SvgConventionError' - } -} diff --git a/apps/app/src/app/App.tsx b/apps/app/src/app/App.tsx index 706094d9..349d4e24 100644 --- a/apps/app/src/app/App.tsx +++ b/apps/app/src/app/App.tsx @@ -1,15 +1,12 @@ -import { BrowserRouter, Routes, Route, useLocation } from 'react-router-dom' +import { BrowserRouter, Routes, Route } from 'react-router-dom' import { ConfigProvider } from './providers/ConfigProvider' import Footer from '@/components/brand/Footer' import HomeRoute from './routes/HomeRoute' import NewReportRoute from './routes/NewReportRoute' import EditorRoute from './routes/EditorRoute' -import SvgEditorRoute from './routes/SvgEditorRoute' -import EditorsRoute from './routes/EditorsRoute' import NotFoundRoute from './routes/NotFoundRoute' function AppShell() { - const hideFooter = useLocation().pathname === '/svg-editor' return (
@@ -17,12 +14,10 @@ function AppShell() { } /> } /> } /> - } /> - } /> } />
- {!hideFooter &&
} +
) } diff --git a/apps/app/src/app/routes/EditorRoute.tsx b/apps/app/src/app/routes/EditorRoute.tsx index d1d6d4c1..e5617411 100644 --- a/apps/app/src/app/routes/EditorRoute.tsx +++ b/apps/app/src/app/routes/EditorRoute.tsx @@ -1,12 +1,16 @@ -import { useEffect, useMemo, useState } from 'react' +import { useCallback, useEffect, useMemo, useState } from 'react' import { useNavigate } from 'react-router-dom' +import type { + Animal, + LateralSide, + Owner, + Practitioner, +} from '@faunosteo/domain' import AnatomyCanvas from '@/components/canvas/AnatomyCanvas' import DetailModal from '@/components/canvas/DetailModal' import ObservationList from '@/components/observation/ObservationList' import VertebraPicker from '@/components/observation/VertebraPicker' -import { regionFromLabel } from '@/lib/spineZones' import LateralityPicker from '@/components/observation/LateralityPicker' -import type { LateralSide } from '@/domain/schema/observation' import ConclusionPanel from '@/components/report/ConclusionPanel' import ReportHeader from '@/components/report/ReportHeader' import PractitionerForm from '@/components/report/PractitionerForm' @@ -15,315 +19,155 @@ import Button from '@/components/ui/Button' import Dialog from '@/components/ui/Dialog' import { useReportStore } from '@/state/reportStore' import { writeCachedPractitioner } from '@/state/practitionerCache' -import { getSpecies } from '@/domain/species/registry' -import { loadSvg } from '@/anatomy/svgLoader' -import { parseSvgBones } from '@/anatomy/svgConvention' -import { collectSpineVertebrae, syncSpineZones } from '@/lib/spineZones' -import type { Bone, BoneState } from '@/anatomy/types' -import type { Observation, ObservationZone } from '@/domain/schema/observation' -import type { Report } from '@/domain/schema/report' -import type { SpeciesFindings } from '@/domain/schema/findings' -import type { Practitioner } from '@/domain/schema/practitioner' -import type { Animal, Owner } from '@/domain/schema/animal' +import { useLocaleStore } from '@/state/localeStore' +import { useSheet } from '@/sheets/useSheet' +import { isObservable, pickLabel, type SheetIndex } from '@/services/sheetIndex' +import { + addSides, + collectVertebrae, + decideZoneClick, + ensureZone, + refOf, + removeAllSides, + removeZoneAt, + sidesPresent, + syncVertebrae, + toggleZone, + type ZoneRef, +} from '@/services/zoneInteraction' +import type { ViewStates } from '@/anatomy/drawing' import { exportReportToPdf } from '@/pdf/export' import { useT } from '@/i18n/useT' -import { useLocaleStore } from '@/state/localeStore' -import { boneLabel } from '@/anatomy/labels' +import { DEFAULT_SPECIES_ID } from './NewReportRoute' const DISCLAIMER_FLAG = 'osteo:disclaimer-shown' -/** Merges newly parsed bones into the accumulated map without overwriting. */ -function mergeBones(prev: Map, parsed: Map) { - const merged = new Map(prev) - parsed.forEach((b, id) => { - if (!merged.has(id)) merged.set(id, b) - }) - return merged +interface Identity { + practitioner: Practitioner + animal: Animal + owner: Owner } +/** Editor on the reference sheet: wires the canvas, the pickers and the store. */ export default function EditorRoute() { const navigate = useNavigate() const t = useT() const locale = useLocaleStore((s) => s.locale) - const report = useReportStore((s) => s.report) - const activeIndex = useReportStore((s) => s.activeObservationIndex) - const addObservation = useReportStore((s) => s.addObservation) - const updateObservation = useReportStore((s) => s.updateObservation) - const removeObservation = useReportStore((s) => s.removeObservation) - const moveObservationUp = useReportStore((s) => s.moveObservationUp) - const moveObservationDown = useReportStore((s) => s.moveObservationDown) - const setActiveObservation = useReportStore((s) => s.setActiveObservation) - const setConclusion = useReportStore((s) => s.setConclusion) - const setRecommendations = useReportStore((s) => s.setRecommendations) - const setNextAppointment = useReportStore((s) => s.setNextAppointment) - const setPractitioner = useReportStore((s) => s.setPractitioner) - const setAnimal = useReportStore((s) => s.setAnimal) - const setOwner = useReportStore((s) => s.setOwner) + const store = useReportStore() + const { report, activeObservationIndex: activeIndex } = store + // Without a report yet (draft restore), the default species' sheet carries the migration map. + const sheet = useSheet(report?.animal.speciesId ?? DEFAULT_SPECIES_ID) - const [bones, setBones] = useState>(new Map()) - const [detailBones, setDetailBones] = useState>(new Map()) - const [findings, setFindings] = useState(null) - const [disclaimer, setDisclaimer] = useState(null) - const [detail, setDetail] = useState<{ - id: string - src: string - title: string - } | null>(null) + const [detailViewId, setDetailViewId] = useState(null) const [vertebraTarget, setVertebraTarget] = useState(null) - const [lateralTarget, setLateralTarget] = useState<{ - boneId: string - detailSourceId?: string - } | null>(null) + const [lateralTarget, setLateralTarget] = useState(null) + const [disclaimer, setDisclaimer] = useState(null) const [exporting, setExporting] = useState(false) - const [editOpen, setEditOpen] = useState(false) - const [editDraft, setEditDraft] = useState<{ - practitioner: Practitioner - animal: Animal - owner: Owner - } | null>(null) - - function openEditInfos() { - if (!report) return - setEditDraft({ - practitioner: report.practitioner, - animal: report.animal, - owner: report.owner, - }) - setEditOpen(true) - } - - function closeEditInfos() { - setEditOpen(false) - setEditDraft(null) - } - - function saveEditInfos() { - if (!editDraft) return closeEditInfos() - const name = editDraft.practitioner.name.trim() - const animalName = editDraft.animal.name.trim() - const ownerName = editDraft.owner.name.trim() - if (!name || !animalName || !ownerName) return - setPractitioner(editDraft.practitioner) - setAnimal(editDraft.animal) - setOwner(editDraft.owner) - writeCachedPractitioner(editDraft.practitioner) - closeEditInfos() - } - - function acknowledgeDisclaimer() { - if (typeof sessionStorage !== 'undefined') { - sessionStorage.setItem(DISCLAIMER_FLAG, '1') - } - setDisclaimer(null) - } - - useEffect(() => { - if (!report) navigate('/') - }, [report, navigate]) + const [editDraft, setEditDraft] = useState(null) useEffect(() => { window.scrollTo({ top: 0, left: 0, behavior: 'auto' }) }, []) - const species = useMemo( - () => (report ? getSpecies(report.animal.speciesId) : undefined), - [report], - ) + // No report in memory: restore the per-tab draft once the sheet is known. + useEffect(() => { + if (report) return + if (sheet.status === 'ready') + store.restoreDraft(sheet.index.sheet.migrationMap) + if (sheet.status !== 'loading' && !useReportStore.getState().report) + navigate('/') + }, [report, sheet, store, navigate]) useEffect(() => { - if (!species) return - loadSvg(species.mainSvg).then((root) => setBones(parseSvgBones(root))) - species.findings().then((m) => setFindings(m.default)) - - // Eagerly preload every detail SVG so observation zones imported - // from a PDF (which can carry detail-popup boneIds without the user - // ever re-opening the popup) resolve their labels and findings - // pickers immediately on mount. Each fetch is independent — a 404 - // on one detail asset must not prevent the others from loading. - Object.values(species.details).forEach((path) => { - loadSvg(path) - .then((root) => { - const parsed = parseSvgBones(root) - setDetailBones((prev) => mergeBones(prev, parsed)) - }) - .catch((err) => { - console.warn(`EditorRoute: failed to preload detail SVG ${path}`, err) - }) - }) - }, [species]) - - useEffect(() => { - if (!findings) return - if (typeof sessionStorage === 'undefined') return + if (sheet.status !== 'ready' || typeof sessionStorage === 'undefined') + return if (sessionStorage.getItem(DISCLAIMER_FLAG)) return - setDisclaimer(findings.scope_disclaimer) - }, [findings]) - - useEffect(() => { - if (!detail) return - let cancelled = false - loadSvg(detail.src).then((root) => { - if (cancelled) return - const parsed = parseSvgBones(root) - setDetailBones((prev) => mergeBones(prev, parsed)) - }) - return () => { - cancelled = true - } - }, [detail]) - - const allBones = useMemo(() => { - const m = new Map(bones) - detailBones.forEach((b, id) => { - if (!m.has(id)) m.set(id, b) - }) - return m - }, [bones, detailBones]) + const text = sheet.index.sheet.document.scope_disclaimer + setDisclaimer( + pickLabel({ fr: text.fr ?? '', en: text.en ?? '' }, locale) || null, + ) + }, [sheet, locale]) const activeObs = activeIndex >= 0 ? report?.observations[activeIndex] : undefined - const boneStates = useMemo>(() => { - const map = new Map() - if (!report || activeIndex < 0) return map - const active = report.observations[activeIndex] - if (!active) return map - active.zones.forEach((z) => { - map.set(z.boneId, 'current') - }) + const states = useMemo(() => { + const map = new Map() + activeObs?.zones.forEach((z) => map.set(z.annotationId, 'current')) return map - }, [report, activeIndex]) + }, [activeObs]) - function onToggleCard(index: number) { - setActiveObservation(activeIndex === index ? -1 : index) - } - - /** Opens the detail-popup modal for a bone that carries data-anno-opens-detail. */ - function handleDetailOpen(bone: Bone, detailId: string, detailSrc: string) { - setDetail({ - id: detailId, - src: detailSrc, - title: boneLabel(bone, locale, detailId), - }) - } - - /** - * No expanded observation — auto-expand the most recent one (or the - * first if no rows yet) so the click lands somewhere. Defers the actual - * zone add to the next render where activeObs is set. - */ - function activateFallbackObservation(report: Report) { - const fallbackIndex = - report.observations.length > 0 ? report.observations.length - 1 : -1 - if (fallbackIndex < 0) return - setActiveObservation(fallbackIndex) - } - - /** - * Spine-zone behavior: always open VertebraPicker on click. Adds the - * zone if missing; never toggles it off here (use the ✕ button). - */ - function handleSpineZone( - activeObs: Observation, - boneId: string, - detailSourceId: string | undefined, - existingIndex: number, - ) { - let targetIndex = existingIndex - if (existingIndex < 0) { - const newZone: ObservationZone = { - boneId, - ...(detailSourceId ? { detailSourceId } : {}), + const onZoneClick = useCallback( + (annotationId: string) => { + // Fresh state: two clicks may land before React re-renders the handler. + const { report, activeObservationIndex: activeIndex } = + useReportStore.getState() + if (sheet.status !== 'ready' || !report) return + const activeObs = + activeIndex >= 0 ? report.observations[activeIndex] : undefined + const index = sheet.index + const annotation = index.annotation(annotationId) + const decision = decideZoneClick(annotation, activeObs) + if (!annotation) return + switch (decision.kind) { + case 'ignore': + return + case 'open_view': + return setDetailViewId(decision.viewId) + case 'activate_fallback': + return store.setActiveObservation(report.observations.length - 1) + case 'open_vertebra_picker': { + const { observation, index: zoneIndex } = ensureZone( + activeObs!, + annotation, + ) + store.updateObservation(activeIndex, observation) + return setVertebraTarget(zoneIndex) + } + case 'open_laterality_picker': + return setLateralTarget(refOf(annotation)) + case 'remove_both_sides': + return store.updateObservation( + activeIndex, + removeAllSides(activeObs!, refOf(annotation)), + ) + case 'toggle': + return store.updateObservation( + activeIndex, + toggleZone(activeObs!, annotation), + ) } - const nextZones = [...activeObs.zones, newZone] - targetIndex = nextZones.length - 1 - updateObservation(activeIndex, { ...activeObs, zones: nextZones }) - } - setVertebraTarget(targetIndex) + }, + [sheet, store], + ) + + function acknowledgeDisclaimer() { + sessionStorage?.setItem(DISCLAIMER_FLAG, '1') + setDisclaimer(null) } - /** Bilateral zone: adding a side, or clearing both once left+right are set. */ - function handleBilateralZone( - activeObs: Observation, - boneId: string, - detailSourceId: string | undefined, - ) { - const sidesPresent = activeObs.zones - .filter( - (z) => z.boneId === boneId && z.detailSourceId === detailSourceId, - ) - .map((z) => z.side) - .filter(Boolean) as LateralSide[] - - if (sidesPresent.includes('left') && sidesPresent.includes('right')) { - const nextZones = activeObs.zones.filter( - (z) => !(z.boneId === boneId && z.detailSourceId === detailSourceId), - ) - updateObservation(activeIndex, { ...activeObs, zones: nextZones }) + function saveEditInfos() { + if (!editDraft) return + if ( + ![ + editDraft.practitioner.name, + editDraft.animal.name, + editDraft.owner.name, + ].every((v) => v.trim()) + ) return - } - - setLateralTarget({ - boneId, - ...(detailSourceId ? { detailSourceId } : {}), - }) + store.setPractitioner(editDraft.practitioner) + store.setAnimal(editDraft.animal) + store.setOwner(editDraft.owner) + writeCachedPractitioner(editDraft.practitioner) + setEditDraft(null) } - /** Plain zone: toggles it on the active observation. */ - function toggleZone( - activeObs: Observation, - boneId: string, - detailSourceId: string | undefined, - existingIndex: number, - ) { - const newZone: ObservationZone = { - boneId, - ...(detailSourceId ? { detailSourceId } : {}), - } - const nextZones = - existingIndex >= 0 - ? activeObs.zones.filter((_, k) => k !== existingIndex) - : [...activeObs.zones, newZone] - updateObservation(activeIndex, { ...activeObs, zones: nextZones }) - } - - function onZoneClick(boneId: string, detailSourceId?: string) { - if (!report) return - const bone = bones.get(boneId) ?? detailBones.get(boneId) - if (!bone) return - - if (bone.opensDetail && species?.details[bone.opensDetail]) { - handleDetailOpen(bone, bone.opensDetail, species.details[bone.opensDetail]) - return - } - - if (!activeObs || activeIndex < 0) { - activateFallbackObservation(report) - return - } - - const matches = (z: ObservationZone) => - z.boneId === boneId && z.detailSourceId === detailSourceId - const existingIndex = activeObs.zones.findIndex(matches) - - if (bone.special === 'vertebral-precision') { - handleSpineZone(activeObs, boneId, detailSourceId, existingIndex) - return - } - - if (bone.lateral === 'bilateral') { - handleBilateralZone(activeObs, boneId, detailSourceId) - return - } - - toggleZone(activeObs, boneId, detailSourceId, existingIndex) - } - - async function onExport() { + async function onExport(index: SheetIndex) { if (!report) return setExporting(true) try { - const bytes = await exportReportToPdf(report, { locale }) + const bytes = await exportReportToPdf(report, index, { locale }) const blob = new Blob([bytes as BlobPart], { type: 'application/pdf' }) const url = URL.createObjectURL(blob) const a = document.createElement('a') @@ -339,73 +183,109 @@ export default function EditorRoute() { } } - if (!report || !species) return null + if (!report) return null + if (sheet.status === 'loading') { + return ( +

+ {t('sheet.loading')} +

+ ) + } + if (sheet.status === 'none') return null + const index = sheet.index + const vertebraZone = + vertebraTarget !== null ? activeObs?.zones[vertebraTarget] : undefined + const vertebraAnnotation = + vertebraZone && index.annotation(vertebraZone.annotationId) + const lateralAnnotation = + lateralTarget && index.annotation(lateralTarget.annotationId) + const detailView = detailViewId ? index.view(detailViewId) : undefined return (
- + + setEditDraft({ + practitioner: report.practitioner, + animal: report.animal, + owner: report.owner, + }) + } + />
-
+
onZoneClick(id)} + index={index} + viewId={index.mainView.id} + states={states} + onZoneClick={onZoneClick} + className="flex-1" /> +

+ {t( + index.sheet.status === 'draft' + ? 'sheet.status.draft' + : 'sheet.status.published', + )} +

updateObservation(i, next)} + onToggle={(i) => + store.setActiveObservation(activeIndex === i ? -1 : i) + } + onAdd={store.addObservation} + onDelete={store.removeObservation} + onMoveUp={store.moveObservationUp} + onMoveDown={store.moveObservationDown} + sheet={index} + onChange={store.updateObservation} onOpenVertebraPicker={(_i, zoneIndex) => setVertebraTarget(zoneIndex) } onRemoveZone={(i, zoneIndex) => { const obs = report.observations[i] - if (!obs) return - const zones = obs.zones.filter((_, k) => k !== zoneIndex) - updateObservation(i, { ...obs, zones }) + if (obs) store.updateObservation(i, removeZoneAt(obs, zoneIndex)) }} />
-
- {detail && ( + {detailView && ( setDetail(null)} - detailSrc={detail.src} - detailId={detail.id} - title={`${t('editor.detail_title_prefix')}${detail.title}`} - boneStates={boneStates} - onZoneClick={(id, did) => onZoneClick(id, did)} + onClose={() => setDetailViewId(null)} + index={index} + viewId={detailView.id} + title={pickLabel(detailView.name, locale)} + states={states} + onZoneClick={onZoneClick} /> )} {editDraft && ( setEditDraft(null)} title={t('editor.edit_dialog_title')} size="lg" > @@ -419,6 +299,9 @@ export default function EditorRoute() { setEditDraft((d) => (d ? { ...d, animal: next } : d)) } @@ -427,15 +310,17 @@ export default function EditorRoute() { } />
- +
@@ -463,86 +350,45 @@ export default function EditorRoute() { {vertebraTarget !== null && activeObs && - activeObs.zones[vertebraTarget] && ( + vertebraZone && + isObservable(vertebraAnnotation) && ( setVertebraTarget(null)} onConfirm={(vertebrae) => { const fresh = useReportStore.getState().report?.observations[activeIndex] - if (!fresh?.zones[vertebraTarget]) { - setVertebraTarget(null) - return + if (fresh) { + store.updateObservation( + activeIndex, + syncVertebrae(fresh, vertebrae, index, vertebraZone.viewId), + ) } - // Picker edits every region at once: reconcile all spine zones — - // spawn newly picked regions, prune emptied ones, keep the rest. - const next = syncSpineZones(fresh.zones, vertebrae, bones) - updateObservation(activeIndex, { ...fresh, zones: next }) setVertebraTarget(null) }} - initial={collectSpineVertebrae( - activeObs.zones, - bones, - activeObs.zones[vertebraTarget].boneId, - )} - formula={species.vertebralFormula} - title={`${t('vertebra.title_prefix')}${boneLabel( - bones.get(activeObs.zones[vertebraTarget].boneId), - locale, - '', - )}`} - initialRegion={(() => { - const b = bones.get(activeObs.zones[vertebraTarget].boneId) - return regionFromLabel(b?.fr ?? '') ?? regionFromLabel(b?.en ?? '') - })()} + initial={collectVertebrae(activeObs, index, vertebraTarget)} + regions={index.regions()} + title={`${t('vertebra.title_prefix')}${pickLabel(vertebraAnnotation.name, locale)}`} + initialRegion={ + vertebraAnnotation.vertebral_region_code ?? undefined + } /> )} - {lateralTarget && activeObs && ( + {lateralTarget && activeObs && lateralAnnotation && ( setLateralTarget(null)} - title={boneLabel( - allBones.get(lateralTarget.boneId), - locale, - lateralTarget.boneId, - )} - existingSides={ - activeObs.zones - .filter( - (z) => - z.boneId === lateralTarget.boneId && - z.detailSourceId === lateralTarget.detailSourceId && - z.side, - ) - .map((z) => z.side!) as LateralSide[] - } - onSelect={(sides) => { + title={pickLabel(index.name(lateralAnnotation), locale)} + existingSides={sidesPresent(activeObs, lateralTarget)} + onSelect={(sides: LateralSide[]) => { const fresh = useReportStore.getState().report?.observations[activeIndex] - if (!fresh) { - setLateralTarget(null) - return - } - const newSideZones = sides - .filter( - (side) => - !fresh.zones.some( - (z) => - z.boneId === lateralTarget.boneId && - z.detailSourceId === lateralTarget.detailSourceId && - z.side === side, - ), + if (fresh) + store.updateObservation( + activeIndex, + addSides(fresh, lateralAnnotation, sides), ) - .map((side) => ({ - boneId: lateralTarget.boneId, - ...(lateralTarget.detailSourceId - ? { detailSourceId: lateralTarget.detailSourceId } - : {}), - side, - })) - const nextZones = [...fresh.zones, ...newSideZones] - updateObservation(activeIndex, { ...fresh, zones: nextZones }) setLateralTarget(null) }} /> diff --git a/apps/app/src/app/routes/EditorsRoute.tsx b/apps/app/src/app/routes/EditorsRoute.tsx deleted file mode 100644 index b795ddd2..00000000 --- a/apps/app/src/app/routes/EditorsRoute.tsx +++ /dev/null @@ -1,42 +0,0 @@ -import { Link } from 'react-router-dom' -import AppHeader from '@/components/brand/AppHeader' -import Card from '@/components/ui/Card' -import { useT } from '@/i18n/useT' - -export default function EditorsRoute() { - const t = useT() - - return ( -
- -
-
- -

{t('editors.svg.title')}

-

- {t('editors.svg.description')} -

- - {t('editors.svg.cta')} - -
- -

{t('editors.pathology.title')}

-

- {t('editors.pathology.description')} -

- - {t('editors.pathology.cta')} - -
-
-
-
- ) -} diff --git a/apps/app/src/app/routes/HomeRoute.tsx b/apps/app/src/app/routes/HomeRoute.tsx index fa7ace68..0d0e61c6 100644 --- a/apps/app/src/app/routes/HomeRoute.tsx +++ b/apps/app/src/app/routes/HomeRoute.tsx @@ -5,25 +5,42 @@ import Button from '@/components/ui/Button' import Card from '@/components/ui/Card' import { importReportFromPdf, ImportError } from '@/pdf/import' import { useReportStore } from '@/state/reportStore' +import { useSheet } from '@/sheets/useSheet' +import { DEFAULT_SPECIES_ID } from './NewReportRoute' import { useT } from '@/i18n/useT' export default function HomeRoute() { const navigate = useNavigate() const fileRef = useRef(null) const hydrate = useReportStore((s) => s.hydrateReport) + const sheet = useSheet(DEFAULT_SPECIES_ID) const [error, setError] = useState(null) const [busy, setBusy] = useState(false) const t = useT() async function onPickFile(e: React.ChangeEvent) { const file = e.target.files?.[0] - if (!file) return + if (!file || sheet.status !== 'ready') return setBusy(true) setError(null) try { const bytes = new Uint8Array(await file.arrayBuffer()) - const report = await importReportFromPdf(bytes) - hydrate(report) + const outcome = await importReportFromPdf( + bytes, + sheet.index.sheet.migrationMap, + ) + if ( + outcome.migrated && + outcome.unresolvedFindings + outcome.unresolvedZones > 0 + ) { + window.alert( + t('home.import.migrated').replace( + '{count}', + String(outcome.unresolvedFindings + outcome.unresolvedZones), + ), + ) + } + hydrate(outcome.report) navigate('/editor') } catch (err) { if (err instanceof ImportError) { @@ -48,21 +65,58 @@ export default function HomeRoute() { } } + const noSheet = sheet.status === 'none' + return (
+ {noSheet && ( + +

+ {t('home.no_sheet.title')} +

+

+ {t('home.no_sheet.description')} +

+
+ )} -

{t('home.new_report.title')}

-

{t('home.new_report.description')}

- +

+ {t('home.new_report.title')} +

+

+ {t('home.new_report.description')} +

+
-

{t('home.import.title')}

-

{t('home.import.description')}

- - {error &&

{error}

} diff --git a/apps/app/src/app/routes/NewReportRoute.tsx b/apps/app/src/app/routes/NewReportRoute.tsx index 4bd0c003..e4dbdad1 100644 --- a/apps/app/src/app/routes/NewReportRoute.tsx +++ b/apps/app/src/app/routes/NewReportRoute.tsx @@ -1,5 +1,6 @@ import { useEffect, useState } from 'react' import { useNavigate } from 'react-router-dom' +import type { Animal, Owner, Practitioner } from '@faunosteo/domain' import PractitionerForm from '@/components/report/PractitionerForm' import AnimalForm from '@/components/report/AnimalForm' import AppHeader from '@/components/brand/AppHeader' @@ -7,18 +8,29 @@ import Button from '@/components/ui/Button' import Input from '@/components/ui/Input' import Label from '@/components/ui/Label' import { todayIso } from '@/lib/dates' -import { readCachedPractitioner, writeCachedPractitioner } from '@/state/practitionerCache' +import { + readCachedPractitioner, + writeCachedPractitioner, +} from '@/state/practitionerCache' import { useReportStore } from '@/state/reportStore' +import { useSheet } from '@/sheets/useSheet' import { useT } from '@/i18n/useT' +/** The one species this build ships a sheet for. */ +export const DEFAULT_SPECIES_ID = 'equine' + export default function NewReportRoute() { const navigate = useNavigate() const initReport = useReportStore((s) => s.initReport) const t = useT() + const sheet = useSheet(DEFAULT_SPECIES_ID) - const [practitioner, setPractitioner] = useState({ name: '' }) - const [animal, setAnimal] = useState({ speciesId: 'equine', name: '' }) - const [owner, setOwner] = useState({ name: '' }) + const [practitioner, setPractitioner] = useState({ name: '' }) + const [animal, setAnimal] = useState({ + speciesId: DEFAULT_SPECIES_ID, + name: '', + }) + const [owner, setOwner] = useState({ name: '' }) const [date, setDate] = useState(todayIso()) useEffect(() => { @@ -26,20 +38,27 @@ export default function NewReportRoute() { if (cached) setPractitioner(cached) }, []) - const canSubmit = practitioner.name.trim() && animal.name.trim() && owner.name.trim() + const canSubmit = + practitioner.name.trim() && + animal.name.trim() && + owner.name.trim() && + sheet.status === 'ready' function submit() { - if (!canSubmit) return + if (!canSubmit || sheet.status !== 'ready') return writeCachedPractitioner(practitioner) - initReport({ - date, - practitioner, - animal, - owner, - observations: [], - conclusion: '', - recommendations: '', - }) + initReport( + { + date, + practitioner, + animal, + owner, + observations: [], + conclusion: '', + recommendations: '', + }, + sheet.index.sheet.ref, + ) navigate('/editor') } @@ -47,16 +66,52 @@ export default function NewReportRoute() {
-

{t('new_report.title')}

+

+ {t('new_report.title')} +

+ {sheet.status === 'none' && ( +

+ {t('home.no_sheet.description')} +

+ )}
- setDate(e.target.value)} /> + setDate(e.target.value)} + />
- +
- - + +
diff --git a/apps/app/src/app/routes/NotFoundRoute.tsx b/apps/app/src/app/routes/NotFoundRoute.tsx index 7367e553..30e48ada 100644 --- a/apps/app/src/app/routes/NotFoundRoute.tsx +++ b/apps/app/src/app/routes/NotFoundRoute.tsx @@ -9,8 +9,12 @@ export default function NotFoundRoute() {

{t('not_found.title')}

-

{t('not_found.description')}

- +

+ {t('not_found.description')} +

+
) diff --git a/apps/app/src/app/routes/SvgEditorRoute.tsx b/apps/app/src/app/routes/SvgEditorRoute.tsx deleted file mode 100644 index e234961e..00000000 --- a/apps/app/src/app/routes/SvgEditorRoute.tsx +++ /dev/null @@ -1,1858 +0,0 @@ -import { useEffect, useRef } from 'react' -import { Link } from 'react-router-dom' -import AppHeader from '@/components/brand/AppHeader' -import { useT } from '@/i18n/useT' -import { useLocaleStore } from '@/state/localeStore' -import { getDict } from '@/i18n/index' -import type { Locale } from '@/i18n/types' -import { getAllSpecies, speciesLabel } from '@/domain/species/registry' -import '@/styles/svg-editor.css' - -type TFn = (key: string) => string - -export default function SvgEditorRoute() { - const canvasRef = useRef(null) - const canvasInnerRef = useRef(null) - const sidebarRef = useRef(null) - const cleanupRef = useRef<(() => void) | null>(null) - const t = useT() - const locale = useLocaleStore((s) => s.locale) - - useEffect(() => { - const meta = document.createElement('meta') - meta.name = 'robots' - meta.content = 'noindex,nofollow' - document.head.appendChild(meta) - return () => { - document.head.removeChild(meta) - } - }, []) - - useEffect(() => { - const canvas = canvasRef.current - const canvasInner = canvasInnerRef.current - const sidebar = sidebarRef.current - if (!canvas || !canvasInner || !sidebar) return - - const dict = getDict(locale) - const tFn: TFn = (key: string) => dict[key] ?? key - const cleanup = initSvgEditor(canvas, canvasInner, sidebar, tFn, locale) - cleanupRef.current = cleanup - - return () => { - cleanup() - cleanupRef.current = null - } - // Re-init when locale changes so all vanilla JS strings update - }, [locale]) - - return ( -
- - -
-
-
-
-
- -
-
-
- - ← - -
-

{t('svg_editor.title')}

-
{t('svg_editor.subtitle')}
-
-
-
- -
-
-

{t('svg_editor.file')}

- - - -
- -
-

{t('svg_editor.mode')}

- - - -
- - -
- - - - -
-
- -
-

{t('svg_editor.selected_element')}

-
- — -
- -
- -
- - -
-
- -
- - - - - - - - - - -
- - -
-
-
- -
- - -
-
-
-
- {t('svg_editor.polygon_editing')} -
- {t('svg_editor.polygon_drag')} -
- {t('svg_editor.polygon_insert')} -
- {t('svg_editor.polygon_delete')} -
- -
-
- -
-
- -
-

- {t('svg_editor.elements')} (0) -

- -
-
-
-
-
-
- ) -} - -function initSvgEditor( - canvas: HTMLDivElement, - canvasInner: HTMLDivElement, - _sidebar: HTMLDivElement, - t: TFn, - locale: Locale, -): () => void { - const ac = new AbortController() - const sig = { signal: ac.signal } - - let mode = 'select' - let selected: SVGElement | null = null - let polygonPoints: number[][] = [] - let dragging: SVGElement | null = null - let draggingHandle: { - vIdx: number - points: number[][] - originalPoint: number[] - polygon: SVGElement - } | null = null - let dragStart: { - x: number - y: number - snap?: ReturnType - siblingSnaps?: { el: SVGElement; snap: ReturnType }[] - } | null = null - let zoom = 1 - let svgRoot: SVGSVGElement | null = null - - const CATEGORY_TEMPLATES: Record = { - articulation: { color: '#fb5607', name: 'Articulations' }, - charniere: { color: '#d00000', name: 'Charnieres vertebrales' }, - 'cadran-crane': { color: '#06a77d', name: 'Cadrans du crane' }, - 'os-overlay': { color: '#f72585', name: 'Os overlay' }, - 'spine-zone': { color: '#7209b7', name: 'Zones colonne' }, - } - let CATEGORIES: Record< - string, - { color: string; name: string; visible: boolean; special?: string } - > = {} - - const DETAIL_ZONE_STYLE = { - fill: '#808080', - fillOpacity: '0.20', - stroke: '#606060', - strokeWidth: '2', - strokeDasharray: '8,4', - } - - const SPECIAL_BEHAVIORS = [ - { id: 'vertebral-precision', desc: 'Specify which vertebrae are involved' }, - { id: 'joint-detail', desc: 'Detail a joint (mobility, pain, etc.)' }, - ] - - const zoomContainer = document.getElementById('svg-editor-zoom-controls') - if (zoomContainer) { - zoomContainer.textContent = '' - const btnIn = document.createElement('button') - btnIn.textContent = '+' - btnIn.addEventListener('click', () => { - zoom *= 1.2 - applyZoom() - }, sig) - const btnOut = document.createElement('button') - btnOut.textContent = '−' - btnOut.addEventListener('click', () => { - zoom /= 1.2 - applyZoom() - }, sig) - const btnReset = document.createElement('button') - btnReset.textContent = '⌂' - btnReset.addEventListener('click', () => { - zoom = 1 - applyZoom() - }, sig) - zoomContainer.append(btnIn, btnOut, btnReset) - } - - let loadedFileName = 'horse_anatomy_edited.svg' - - const speciesList = getAllSpecies() - - setupGlobalListeners() - setupGlobalDragDrop() - showWelcomeScreen() - - function showWelcomeScreen() { - canvasInner.textContent = '' - const welcome = document.createElement('div') - welcome.className = 'welcome' - welcome.id = 'svg-editor-welcome' - - const icon = document.createElement('div') - icon.className = 'welcome-icon' - icon.textContent = '📐' - - const h2 = document.createElement('h2') - h2.textContent = t('svg_editor.welcome_title') - - const p = document.createElement('p') - p.textContent = t('svg_editor.welcome_text') - const code1 = document.createElement('code') - code1.textContent = 'data-anno-id' - const code2 = document.createElement('code') - code2.textContent = 'data-anno-category' - p.appendChild(code1) - p.appendChild(document.createTextNode(' & ')) - p.appendChild(code2) - p.appendChild(document.createTextNode(t('svg_editor.welcome_text_suffix'))) - - const tabBar = document.createElement('div') - tabBar.className = 'welcome-tabs' - const tabProject = document.createElement('button') - tabProject.className = 'welcome-tab active' - tabProject.textContent = t('svg_editor.source_project') - const tabUpload = document.createElement('button') - tabUpload.className = 'welcome-tab' - tabUpload.textContent = t('svg_editor.source_upload') - tabBar.append(tabProject, tabUpload) - - const tabContent = document.createElement('div') - tabContent.className = 'welcome-tab-content' - - function showProjectTab() { - tabProject.classList.add('active') - tabUpload.classList.remove('active') - tabContent.textContent = '' - buildProjectPicker(tabContent) - } - - function showUploadTab() { - tabUpload.classList.add('active') - tabProject.classList.remove('active') - tabContent.textContent = '' - buildUploadPicker(tabContent) - } - - tabProject.addEventListener('click', showProjectTab) - tabUpload.addEventListener('click', showUploadTab) - - welcome.append(icon, h2, p, tabBar, tabContent) - canvasInner.appendChild(welcome) - - showProjectTab() - - svgRoot = null - CATEGORIES = {} - selected = null - dragging = null - draggingHandle = null - refreshCategoryList() - refreshCategorySelects() - getEl('svg-editor-count').textContent = '0' - getEl('svg-editor-element-list').textContent = '' - getEl('svg-editor-edit-section').style.display = 'none' - getEl('svg-editor-file-btn').textContent = t('svg_editor.choose_file') - } - - function buildProjectPicker(container: HTMLElement) { - const speciesLabelEl = document.createElement('label') - speciesLabelEl.textContent = t('svg_editor.species') - const speciesSel = document.createElement('select') - speciesList.forEach((sp) => { - const opt = document.createElement('option') - opt.value = sp.id - opt.textContent = speciesLabel(sp, locale) - speciesSel.appendChild(opt) - }) - - const viewLabel = document.createElement('label') - viewLabel.textContent = t('svg_editor.view') - const viewSel = document.createElement('select') - - function populateViews() { - viewSel.textContent = '' - const sp = speciesList.find((s) => s.id === speciesSel.value) - if (!sp) return - const mainOpt = document.createElement('option') - mainOpt.value = sp.mainSvg - mainOpt.textContent = t('svg_editor.view_main') - viewSel.appendChild(mainOpt) - for (const [detailId, detailPath] of Object.entries(sp.details)) { - const opt = document.createElement('option') - opt.value = detailPath - opt.textContent = t('svg_editor.view_detail').replace('{name}', detailId) - viewSel.appendChild(opt) - } - } - populateViews() - speciesSel.addEventListener('change', populateViews) - - const loadBtn = document.createElement('button') - loadBtn.className = 'primary welcome-btn' - loadBtn.textContent = t('svg_editor.load') - loadBtn.addEventListener('click', () => { - const svgPath = viewSel.value - if (!svgPath) return - loadBtn.disabled = true - loadBtn.textContent = '...' - fetch(svgPath) - .then((r) => { - if (!r.ok) throw new Error(r.statusText) - return r.text() - }) - .then((svgText) => { - const filename = svgPath.split('/').pop() || 'anatomy_edited.svg' - loadedFileName = filename.replace('.svg', '_edited.svg') - loadSVG(svgText) - getEl('svg-editor-file-btn').textContent = t('svg_editor.change_file') - }) - .catch(() => { - alert(t('svg_editor.alert_invalid_svg')) - loadBtn.disabled = false - loadBtn.textContent = t('svg_editor.load') - }) - }) - - container.append(speciesLabelEl, speciesSel, viewLabel, viewSel, loadBtn) - } - - function buildUploadPicker(container: HTMLElement) { - const btn = document.createElement('button') - btn.className = 'primary welcome-btn' - btn.textContent = t('svg_editor.choose_file') - btn.addEventListener('click', () => { - const fi = document.getElementById('svg-editor-file-import') as HTMLInputElement | null - fi?.click() - }) - - const hint = document.createElement('div') - hint.className = 'welcome-hint' - hint.textContent = t('svg_editor.welcome_drag_hint') - - container.append(btn, hint) - } - - function setupGlobalDragDrop() { - canvas.addEventListener('dragover', (e) => { - e.preventDefault() - canvas.classList.add('dragging-over') - }, sig) - canvas.addEventListener('dragleave', (e) => { - if (e.target === canvas) canvas.classList.remove('dragging-over') - }, sig) - canvas.addEventListener('drop', (e) => { - e.preventDefault() - canvas.classList.remove('dragging-over') - const file = e.dataTransfer?.files[0] - if (file && (file.name.endsWith('.svg') || file.type === 'image/svg+xml')) { - loadedFileName = file.name.replace('.svg', '_edited.svg') - const reader = new FileReader() - reader.onload = (ev) => { - loadSVG(ev.target?.result as string) - getEl('svg-editor-file-btn').textContent = t('svg_editor.change_file') - } - reader.readAsText(file, 'UTF-8') - } else { - alert(t('svg_editor.alert_drop_svg')) - } - }, sig) - } - - /** Strip active content from an untrusted SVG: scripts, foreignObject, - * event-handler attributes (root included) and javascript: hrefs. */ - function sanitizeSvg(root: Element) { - root.querySelectorAll('script, foreignObject').forEach((el) => el.remove()) - for (const el of [root, ...root.querySelectorAll('*')]) { - for (const attr of [...el.attributes]) { - const isHandler = /^on/i.test(attr.name) - const isJsHref = /href$/i.test(attr.name) && /^\s*javascript:/i.test(attr.value) - if (isHandler || isJsHref) el.removeAttribute(attr.name) - } - } - } - - function loadSVG(svgText: string) { - const parser = new DOMParser() - const doc = parser.parseFromString(svgText, 'image/svg+xml') - const parsedSvg = doc.querySelector('svg') - if (!parsedSvg) { - alert(t('svg_editor.alert_invalid_svg')) - showWelcomeScreen() - return - } - - const imported = document.importNode(parsedSvg, true) - sanitizeSvg(imported) - canvasInner.textContent = '' - canvasInner.appendChild(imported) - svgRoot = canvasInner.querySelector('svg') - if (!svgRoot) { - alert(t('svg_editor.alert_invalid_svg')) - showWelcomeScreen() - return - } - - if (!svgRoot.getAttribute('viewBox')) { - const wAttr = svgRoot.getAttribute('width') - const hAttr = svgRoot.getAttribute('height') - const w = wAttr ? parseFloat(wAttr) : 1000 - const h = hAttr ? parseFloat(hAttr) : 1000 - svgRoot.setAttribute('viewBox', `0 0 ${w} ${h}`) - } - - svgRoot.removeAttribute('width') - svgRoot.removeAttribute('height') - - CATEGORIES = {} - selected = null - dragging = null - draggingHandle = null - zoom = 1 - - migrateOldAttributes() - normalizeDetailZones() - fixDuplicateIds() - detectCategories() - applyAllCategoryColors() - - setupSVGListeners() - refreshCategoryList() - refreshCategorySelects() - refreshElementList() - } - - function normalizeDetailZones() { - if (!svgRoot) return - svgRoot.querySelectorAll('[data-anno-opens-detail]').forEach((el) => { - el.classList.add('detail-zone') - if (el.getAttribute('fill') !== 'transparent') { - el.setAttribute('fill', DETAIL_ZONE_STYLE.fill) - if (!el.getAttribute('fill-opacity')) { - el.setAttribute('fill-opacity', DETAIL_ZONE_STYLE.fillOpacity) - } - if (el.tagName.toLowerCase() === 'polygon') { - el.setAttribute('stroke', DETAIL_ZONE_STYLE.stroke) - if (!el.getAttribute('stroke-dasharray')) { - el.setAttribute('stroke-dasharray', DETAIL_ZONE_STYLE.strokeDasharray) - } - } - } - }) - } - - function migrateOldAttributes() { - if (!svgRoot) return - const MIGRATIONS: [string, string][] = [ - ['data-bone-id', 'data-anno-id'], - ['data-bone-fr', 'data-anno-name-fr'], - ['data-bone-en', 'data-anno-name-en'], - ['data-category', 'data-anno-category'], - ['data-opens-detail', 'data-anno-opens-detail'], - ] - MIGRATIONS.forEach(([oldAttr, newAttr]) => { - svgRoot!.querySelectorAll(`[${oldAttr}]`).forEach((el) => { - if (!el.hasAttribute(newAttr)) { - el.setAttribute(newAttr, el.getAttribute(oldAttr)!) - } - el.removeAttribute(oldAttr) - }) - }) - } - - function fixDuplicateIds() { - if (!svgRoot) return - const byId: Record> = {} - svgRoot.querySelectorAll('[data-anno-id]').forEach((el) => { - const id = el.getAttribute('data-anno-id')! - const cat = el.getAttribute('data-anno-category') || 'unknown' - if (!byId[id]) byId[id] = {} - if (!byId[id][cat]) byId[id][cat] = [] - byId[id][cat].push(el) - }) - - for (const [id, byCat] of Object.entries(byId)) { - const cats = Object.keys(byCat) - if (cats.length > 1) { - cats.slice(1).forEach((cat) => { - const newId = id + '-' + cat - byCat[cat].forEach((el) => { - el.setAttribute('data-anno-id', newId) - if (el.getAttribute('id') === id) el.setAttribute('id', newId) - }) - }) - } - } - } - - function detectCategories() { - if (!svgRoot) return - svgRoot.querySelectorAll('[data-anno-category]').forEach((el) => { - const cat = el.getAttribute('data-anno-category')! - const special = el.getAttribute('data-anno-special') || '' - const storedName = el.getAttribute('data-anno-category-name') || '' - - if (CATEGORIES[cat]) { - if (special && !CATEGORIES[cat].special) { - CATEGORIES[cat].special = special - } - if (storedName && CATEGORIES[cat].name === cat) { - CATEGORIES[cat].name = storedName - } - return - } - - if (CATEGORY_TEMPLATES[cat]) { - CATEGORIES[cat] = { ...CATEGORY_TEMPLATES[cat], visible: true } - } else { - const sample = svgRoot!.querySelector( - `[data-anno-category="${cat}"]:not([fill="transparent"])`, - ) - const fill = sample ? sample.getAttribute('fill') : null - const color = fill && fill.startsWith('#') ? fill : '#00aaff' - CATEGORIES[cat] = { color, name: storedName || cat, visible: true } - } - if (special) CATEGORIES[cat].special = special - }) - } - - function applyAllCategoryColors() { - if (!svgRoot) return - for (const [cat, info] of Object.entries(CATEGORIES)) { - svgRoot.querySelectorAll(`[data-anno-category="${cat}"]`).forEach((el) => { - if (el.getAttribute('fill') === 'transparent') return - el.setAttribute('fill', info.color) - if (el.tagName.toLowerCase() === 'polygon') { - el.setAttribute('stroke', info.color) - } - }) - } - } - - function setupSVGListeners() { - if (!svgRoot) return - svgRoot.addEventListener('click', svgClickHandler, sig) - svgRoot.addEventListener('mousedown', svgMousedownHandler, sig) - svgRoot.addEventListener('contextmenu', svgContextMenuHandler, sig) - } - - function svgClickHandler(e: MouseEvent) { - if (mode === 'point') { - const p = getSVGPoint(e) - addCircleAt(p.x, p.y) - e.stopPropagation() - } else if (mode === 'polygon') { - const p = getSVGPoint(e) - polygonPoints.push([p.x, p.y]) - updatePolygonPreview() - e.stopPropagation() - } else if (mode === 'select') { - const target = e.target as Element - const midhandle = target.closest('.polygon-midhandle') - if (midhandle && selected && selected.tagName.toLowerCase() === 'polygon') { - const edgeIdx = parseInt(midhandle.getAttribute('data-edge-idx')!) - const points = parsePoints(selected.getAttribute('points')!) - const p = getSVGPoint(e) - points.splice(edgeIdx + 1, 0, [p.x, p.y]) - selected.setAttribute('points', pointsToStr(points)) - showPolygonHandles(selected) - e.stopPropagation() - return - } - if (target.closest('.polygon-handle')) { - e.stopPropagation() - return - } - const annoTarget = target.closest('[data-anno-id]') as SVGElement | null - if (annoTarget) { - selectElement(annoTarget) - e.stopPropagation() - } else { - deselect() - } - } - } - - function svgContextMenuHandler(e: MouseEvent) { - if ((e.target as Element).closest('.polygon-handle')) { - e.preventDefault() - } - } - - function svgMousedownHandler(e: MouseEvent) { - if (mode !== 'select') return - - const target = e.target as Element - const handle = target.closest('.polygon-handle') - if (handle && selected && selected.tagName.toLowerCase() === 'polygon') { - const vIdx = parseInt(handle.getAttribute('data-vertex-idx')!) - const points = parsePoints(selected.getAttribute('points')!) - - if (e.altKey || e.button === 2) { - if (points.length > 3) { - points.splice(vIdx, 1) - selected.setAttribute('points', pointsToStr(points)) - showPolygonHandles(selected) - } else { - alert(t('svg_editor.alert_min_3_vertices')) - } - e.preventDefault() - e.stopPropagation() - return - } - - const p = getSVGPoint(e) - draggingHandle = { - vIdx, - points, - originalPoint: [...points[vIdx]], - polygon: selected, - } - dragStart = { x: p.x, y: p.y } - e.preventDefault() - e.stopPropagation() - return - } - - if (target.classList.contains('polygon-midhandle')) { - return - } - - const annoTarget = target.closest('[data-anno-id]') as SVGElement | null - if (!annoTarget) return - selectElement(annoTarget) - dragging = annoTarget - const p = getSVGPoint(e) - const id = annoTarget.getAttribute('data-anno-id')! - const cat = annoTarget.getAttribute('data-anno-category') - const parent = annoTarget.parentNode as Element | null - const siblingSnaps: { el: SVGElement; snap: ReturnType }[] = [] - if (parent) { - parent.querySelectorAll(`[data-anno-id="${cssEscape(id)}"]`).forEach((sib) => { - if (sib === annoTarget) return - if (sib.getAttribute('data-anno-category') !== cat) return - const snap = snapshotPosition(sib as SVGElement) - if (snap) siblingSnaps.push({ el: sib as SVGElement, snap }) - }) - } - dragStart = { - x: p.x, - y: p.y, - snap: snapshotPosition(annoTarget), - siblingSnaps, - } - e.preventDefault() - } - - function onMouseMove(e: MouseEvent) { - if (draggingHandle) { - const p = getSVGPoint(e) - const dx = p.x - dragStart!.x - const dy = p.y - dragStart!.y - const newPoint = [ - draggingHandle.originalPoint[0] + dx, - draggingHandle.originalPoint[1] + dy, - ] - draggingHandle.points[draggingHandle.vIdx] = newPoint - draggingHandle.polygon.setAttribute( - 'points', - pointsToStr(draggingHandle.points), - ) - showPolygonHandles(draggingHandle.polygon) - return - } - - if (!dragging) return - const p = getSVGPoint(e) - const dx = p.x - dragStart!.x - const dy = p.y - dragStart!.y - moveElement(dragging, dx, dy, dragStart!.snap!) - dragStart!.siblingSnaps?.forEach(({ el: sibEl, snap }) => { - moveElement(sibEl, dx, dy, snap!) - }) - if (dragging === selected && dragging.tagName.toLowerCase() === 'polygon') { - showPolygonHandles(dragging) - } - updateCoordsDisplay() - } - - function onMouseUp() { - dragging = null - draggingHandle = null - dragStart = null - } - - function onKeyDown(e: KeyboardEvent) { - const tag = (e.target as Element).tagName - if (tag === 'INPUT' || tag === 'SELECT' || tag === 'TEXTAREA') return - if (e.key === 'Enter' && mode === 'polygon') finalizePolygon() - if (e.key === 'Escape') { - if (mode === 'polygon') cancelPolygon() - else deselect() - } - if (e.key === 'Delete' && selected) deleteSelected() - if (e.key === '1') setMode('select') - if (e.key === '2') setMode('point') - if (e.key === '3') setMode('polygon') - } - - function setupGlobalListeners() { - document.addEventListener('mousemove', onMouseMove, sig) - document.addEventListener('mouseup', onMouseUp, sig) - document.addEventListener('keydown', onKeyDown, sig) - - getEl('svg-editor-filter-input').addEventListener('input', refreshElementList, sig) - - ;['svg-editor-edit-fr', 'svg-editor-edit-en', 'svg-editor-edit-category', 'svg-editor-edit-lateral'].forEach( - (id) => { - getEl(id).addEventListener('change', applyEdit, sig) - }, - ) - - function syncSliderNum(rangeId: string, numId: string) { - const range = getEl(rangeId) as HTMLInputElement - const num = getEl(numId) as HTMLInputElement - range.addEventListener('input', () => { - num.value = range.value - if (selected) applyEdit() - }, sig) - num.addEventListener('input', () => { - const v = parseFloat(num.value) - if (!isNaN(v)) { - range.value = String( - Math.max(parseFloat(range.min), Math.min(parseFloat(range.max), v)), - ) - } - if (selected) applyEdit() - }, sig) - } - syncSliderNum('svg-editor-edit-radius', 'svg-editor-edit-radius-num') - syncSliderNum('svg-editor-edit-opacity', 'svg-editor-edit-opacity-num') - - ;(getEl('svg-editor-edit-opens-detail') as HTMLInputElement).addEventListener( - 'change', - () => { - const checked = (getEl('svg-editor-edit-opens-detail') as HTMLInputElement).checked - getEl('svg-editor-detail-target-row').style.display = checked ? 'block' : 'none' - getEl('svg-editor-osteo-fields').style.display = checked ? 'none' : 'block' - applyEdit() - }, - sig, - ) - getEl('svg-editor-edit-detail-target').addEventListener('change', applyEdit, sig) - getEl('svg-editor-edit-detail-target').addEventListener('input', () => { - if (selected) applyEdit() - }, sig) - - ;(getEl('svg-editor-file-import') as HTMLInputElement).addEventListener('change', (e) => { - const file = (e.target as HTMLInputElement).files?.[0] - if (!file) return - loadedFileName = file.name.replace('.svg', '_edited.svg') - const reader = new FileReader() - reader.onload = (ev) => { - loadSVG(ev.target?.result as string) - getEl('svg-editor-file-btn').textContent = t('svg_editor.change_file') - } - reader.readAsText(file, 'UTF-8') - ;(e.target as HTMLInputElement).value = '' - }, sig) - - getEl('svg-editor-file-btn').addEventListener('click', () => { - ;(getEl('svg-editor-file-import') as HTMLInputElement).click() - }, sig) - - getEl('svg-editor-export-btn').addEventListener('click', exportSVG, sig) - - getEl('svg-editor-mode-select').addEventListener('click', () => setMode('select'), sig) - getEl('svg-editor-mode-point').addEventListener('click', () => setMode('point'), sig) - getEl('svg-editor-mode-polygon').addEventListener('click', () => setMode('polygon'), sig) - getEl('svg-editor-finalize-polygon').addEventListener('click', finalizePolygon, sig) - getEl('svg-editor-cancel-polygon').addEventListener('click', cancelPolygon, sig) - getEl('svg-editor-add-cat-btn').addEventListener('click', addCategory, sig) - getEl('svg-editor-delete-btn').addEventListener('click', deleteSelected, sig) - getEl('svg-editor-restart-polygon').addEventListener('click', restartCurrentPolygon, sig) - } - - function getEl(id: string): HTMLElement { - return document.getElementById(id) as HTMLElement - } - - function getSVGPoint(evt: MouseEvent) { - const pt = svgRoot!.createSVGPoint() - pt.x = evt.clientX - pt.y = evt.clientY - return pt.matrixTransform(svgRoot!.getScreenCTM()!.inverse()) - } - - function setMode(m: string) { - if (!svgRoot && m !== 'select') { - alert(t('svg_editor.alert_upload_first')) - return - } - mode = m - canvas.className = 'svg-editor-canvas mode-' + m - document.querySelectorAll('[data-mode]').forEach((b) => { - b.classList.toggle('active', (b as HTMLElement).dataset.mode === m) - }) - getEl('svg-editor-polygon-controls').style.display = m === 'polygon' ? 'block' : 'none' - if (m !== 'polygon') cancelPolygon() - if (m !== 'select') { - deselect() - hidePolygonHandles() - } - } - - function snapshotPosition(svgEl: SVGElement) { - const tag = svgEl.tagName.toLowerCase() - if (tag === 'circle' || tag === 'ellipse') - return { - type: tag, - cx: parseFloat(svgEl.getAttribute('cx')!), - cy: parseFloat(svgEl.getAttribute('cy')!), - points: '', - } - if (tag === 'polygon') - return { type: 'polygon', cx: 0, cy: 0, points: svgEl.getAttribute('points')! } - return null - } - - function moveElement( - svgEl: SVGElement, - dx: number, - dy: number, - snap: NonNullable>, - ) { - if (snap.type === 'circle' || snap.type === 'ellipse') { - svgEl.setAttribute('cx', String(snap.cx + dx)) - svgEl.setAttribute('cy', String(snap.cy + dy)) - } else if (snap.type === 'polygon') { - const pts = snap.points - .split(/\s+/) - .filter((p: string) => p) - .map((p: string) => { - const [x, y] = p.split(',').map(Number) - return [(x + dx).toFixed(1), (y + dy).toFixed(1)] - }) - svgEl.setAttribute('points', pts.map((p: string[]) => p.join(',')).join(' ')) - } - } - - function cssEscape(s: string) { - return CSS.escape ? CSS.escape(s) : s.replace(/[^a-zA-Z0-9_-]/g, '\\$&') - } - - function selectElement(svgEl: SVGElement) { - deselect() - selected = svgEl - svgEl.classList.add('selected') - const id = svgEl.getAttribute('data-anno-id')! - const cat = svgEl.getAttribute('data-anno-category') - const parent = svgEl.parentNode as Element | null - if (parent) { - parent.querySelectorAll(`[data-anno-id="${cssEscape(id)}"]`).forEach((s) => { - if (s.getAttribute('data-anno-category') === cat) { - s.classList.add('selected') - } - }) - } - showEditPanel(svgEl) - if (svgEl.tagName.toLowerCase() === 'polygon') { - showPolygonHandles(svgEl) - } - refreshElementList() - } - - function deselect() { - document.querySelectorAll('.selected').forEach((svgEl) => svgEl.classList.remove('selected')) - hidePolygonHandles() - selected = null - getEl('svg-editor-edit-section').style.display = 'none' - refreshElementList() - } - - function showEditPanel(svgEl: SVGElement) { - getEl('svg-editor-edit-section').style.display = 'block' - ;(getEl('svg-editor-edit-fr') as HTMLInputElement).value = - svgEl.getAttribute('data-anno-name-fr') || '' - ;(getEl('svg-editor-edit-en') as HTMLInputElement).value = - svgEl.getAttribute('data-anno-name-en') || '' - ;(getEl('svg-editor-edit-category') as HTMLSelectElement).value = - svgEl.getAttribute('data-anno-category') || 'custom' - ;(getEl('svg-editor-edit-lateral') as HTMLSelectElement).value = - svgEl.getAttribute('data-anno-lateral') || '' - - const id = svgEl.getAttribute('data-anno-id')! - const cat = svgEl.getAttribute('data-anno-category') - const parent = svgEl.parentNode as Element | null - let visibleEl: SVGElement = svgEl - if (parent && id) { - const sibs = parent.querySelectorAll(`[data-anno-id="${cssEscape(id)}"]`) - sibs.forEach((s) => { - if ( - s.getAttribute('data-anno-category') === cat && - s.getAttribute('fill') !== 'transparent' - ) { - visibleEl = s as SVGElement - } - }) - } - - const opa = parseFloat(visibleEl.getAttribute('fill-opacity') || '0.65') - const opaPct = Math.round(opa * 100) - ;(getEl('svg-editor-edit-opacity') as HTMLInputElement).value = String(opaPct) - ;(getEl('svg-editor-edit-opacity-num') as HTMLInputElement).value = String(opaPct) - - const tag = svgEl.tagName.toLowerCase() - const radBlock = getEl('svg-editor-lbl-radius') - const radRow = getEl('svg-editor-radius-row') - const visibleTag = visibleEl.tagName.toLowerCase() - if (visibleTag === 'circle') { - radBlock.style.display = 'block' - radRow.style.display = 'flex' - const r = parseFloat(visibleEl.getAttribute('r') || '15') - ;(getEl('svg-editor-edit-radius') as HTMLInputElement).value = String(r) - ;(getEl('svg-editor-edit-radius-num') as HTMLInputElement).value = String(r) - } else { - radBlock.style.display = 'none' - radRow.style.display = 'none' - } - - const polyActions = getEl('svg-editor-polygon-edit-actions') - if (polyActions) polyActions.style.display = tag === 'polygon' ? 'block' : 'none' - - const opensDetail = - visibleEl.getAttribute('data-anno-opens-detail') || - svgEl.getAttribute('data-anno-opens-detail') || - '' - const checkbox = getEl('svg-editor-edit-opens-detail') as HTMLInputElement - const detailInput = getEl('svg-editor-edit-detail-target') as HTMLInputElement - const detailRow = getEl('svg-editor-detail-target-row') - const detailBlock = getEl('svg-editor-detail-toggle-block') - - const osteoFields = getEl('svg-editor-osteo-fields') - if (tag === 'polygon') { - detailBlock.style.display = 'block' - checkbox.checked = !!opensDetail - detailInput.value = opensDetail - detailRow.style.display = opensDetail ? 'block' : 'none' - osteoFields.style.display = opensDetail ? 'none' : 'block' - } else { - detailBlock.style.display = 'none' - checkbox.checked = false - detailInput.value = '' - osteoFields.style.display = 'block' - } - - updateCoordsDisplay() - } - - function updateCoordsDisplay() { - if (!selected) return - const tag = selected.tagName.toLowerCase() - let txt = '' - if (tag === 'circle' || tag === 'ellipse') { - txt = `cx=${Math.round(parseFloat(selected.getAttribute('cx')!))}, cy=${Math.round(parseFloat(selected.getAttribute('cy')!))}` - } else if (tag === 'polygon') { - const pts = selected - .getAttribute('points')! - .split(/\s+/) - .filter((p) => p).length - txt = t('svg_editor.polygon_vertices').replace('{count}', String(pts)) - } - getEl('svg-editor-coords-display').textContent = txt - } - - function applyEdit() { - if (!selected) return - const fr = (getEl('svg-editor-edit-fr') as HTMLInputElement).value.trim() - const en = (getEl('svg-editor-edit-en') as HTMLInputElement).value.trim() - const cat = (getEl('svg-editor-edit-category') as HTMLSelectElement).value - const lateral = (getEl('svg-editor-edit-lateral') as HTMLSelectElement).value - const opacityPct = (getEl('svg-editor-edit-opacity') as HTMLInputElement).value - const opacity = (parseFloat(opacityPct) / 100).toString() - const radius = (getEl('svg-editor-edit-radius') as HTMLInputElement).value - - const oldId = selected.getAttribute('data-anno-id')! - const oldCat = selected.getAttribute('data-anno-category') - const parent = selected.parentNode as Element | null - const siblings = parent - ? Array.from(parent.querySelectorAll(`[data-anno-id="${cssEscape(oldId)}"]`)).filter( - (s) => s.getAttribute('data-anno-category') === oldCat, - ) - : [selected] - - const opensDetailEnabled = (getEl('svg-editor-edit-opens-detail') as HTMLInputElement).checked - const detailTarget = (getEl('svg-editor-edit-detail-target') as HTMLInputElement).value.trim() - - siblings.forEach((s) => { - if (opensDetailEnabled && detailTarget) { - s.setAttribute('data-anno-opens-detail', detailTarget) - s.removeAttribute('data-anno-name-fr') - s.removeAttribute('data-anno-name-en') - s.removeAttribute('data-anno-category') - s.removeAttribute('data-anno-category-name') - s.removeAttribute('data-anno-special') - } else { - s.removeAttribute('data-anno-opens-detail') - s.removeAttribute('stroke-dasharray') - if (fr) s.setAttribute('data-anno-name-fr', fr) - if (en) s.setAttribute('data-anno-name-en', en) - if (cat) { - s.setAttribute('data-anno-category', cat) - if (CATEGORIES[cat]?.name) { - s.setAttribute('data-anno-category-name', CATEGORIES[cat].name) - } - const catSpecial = CATEGORIES[cat]?.special - if (catSpecial?.trim()) { - s.setAttribute('data-anno-special', catSpecial.trim()) - } else { - s.removeAttribute('data-anno-special') - } - } - if (lateral) { - s.setAttribute('data-anno-lateral', lateral) - } else { - s.removeAttribute('data-anno-lateral') - } - } - - if (opensDetailEnabled && detailTarget) { - let title = s.querySelector(':scope > title') as SVGTitleElement | null - if (!title) { - title = document.createElementNS('http://www.w3.org/2000/svg', 'title') as SVGTitleElement - s.insertBefore(title, s.firstChild) - } - title.textContent = 'Zoom: ' + detailTarget - if (s.getAttribute('fill') !== 'transparent') { - s.setAttribute('fill', DETAIL_ZONE_STYLE.fill) - s.setAttribute('fill-opacity', opacity || DETAIL_ZONE_STYLE.fillOpacity) - if (s.tagName.toLowerCase() === 'polygon') { - s.setAttribute('stroke', DETAIL_ZONE_STYLE.stroke) - s.setAttribute('stroke-width', DETAIL_ZONE_STYLE.strokeWidth) - s.setAttribute('stroke-dasharray', DETAIL_ZONE_STYLE.strokeDasharray) - } - } - s.classList.add('detail-zone') - } else { - s.classList.remove('detail-zone') - let title = s.querySelector(':scope > title') as SVGTitleElement | null - if (!title) { - title = document.createElementNS('http://www.w3.org/2000/svg', 'title') as SVGTitleElement - s.insertBefore(title, s.firstChild) - } - title.textContent = (fr || '') + (en ? ' / ' + en : '') - - if (s.getAttribute('fill') !== 'transparent' && cat && CATEGORIES[cat]) { - s.setAttribute('fill', CATEGORIES[cat].color) - if (s.tagName.toLowerCase() === 'polygon') { - s.setAttribute('stroke', CATEGORIES[cat].color) - } - } - if (opacity && s.getAttribute('fill') !== 'transparent') - s.setAttribute('fill-opacity', opacity) - - const stag = s.tagName.toLowerCase() - if (stag === 'circle' && radius) { - if (s.getAttribute('fill') === 'transparent') { - s.setAttribute('r', String(Math.max(1, parseFloat(radius) + 12))) - } else { - s.setAttribute('r', radius) - } - } - } - }) - - refreshElementList() - refreshCategoryList() - } - - function deleteSelected() { - if (!selected) return - if (!confirm(t('svg_editor.confirm_delete_element'))) return - const id = selected.getAttribute('data-anno-id')! - const cat = selected.getAttribute('data-anno-category') - const parent = selected.parentNode as Element | null - if (parent) { - parent.querySelectorAll(`[data-anno-id="${cssEscape(id)}"]`).forEach((s) => { - if (s.getAttribute('data-anno-category') === cat) s.parentNode?.removeChild(s) - }) - } - selected = null - getEl('svg-editor-edit-section').style.display = 'none' - refreshElementList() - refreshCategoryList() - } - - function addCircleAt(x: number, y: number) { - if (!svgRoot) return - const cat = (getEl('svg-editor-default-category') as HTMLSelectElement).value || 'custom' - const color = CATEGORIES[cat]?.color || '#00aaff' - - let overlayG = svgRoot.querySelector('#osteo-overlays') - if (!overlayG) { - overlayG = document.createElementNS('http://www.w3.org/2000/svg', 'g') - overlayG.setAttribute('id', 'osteo-overlays') - svgRoot.appendChild(overlayG) - } - - const id = 'point-' + Date.now().toString(36) - const frName = t('svg_editor.new_point_fr') - const enName = t('svg_editor.new_point_en') - - const hit = document.createElementNS('http://www.w3.org/2000/svg', 'circle') - hit.setAttribute('cx', String(Math.round(x))) - hit.setAttribute('cy', String(Math.round(y))) - hit.setAttribute('r', '28') - hit.setAttribute('fill', 'transparent') - hit.setAttribute('pointer-events', 'all') - hit.setAttribute('data-anno-id', id) - hit.setAttribute('data-anno-name-fr', frName) - hit.setAttribute('data-anno-name-en', enName) - hit.setAttribute('data-anno-category', cat) - if (CATEGORIES[cat]?.name) hit.setAttribute('data-anno-category-name', CATEGORIES[cat].name) - if (CATEGORIES[cat]?.special) hit.setAttribute('data-anno-special', CATEGORIES[cat].special!) - hit.setAttribute('style', 'cursor:pointer') - const t1 = document.createElementNS('http://www.w3.org/2000/svg', 'title') - t1.textContent = frName - hit.appendChild(t1) - overlayG.appendChild(hit) - - const vis = document.createElementNS('http://www.w3.org/2000/svg', 'circle') - vis.setAttribute('cx', String(Math.round(x))) - vis.setAttribute('cy', String(Math.round(y))) - vis.setAttribute('r', '16') - vis.setAttribute('fill', color) - vis.setAttribute('fill-opacity', '0.65') - vis.setAttribute('stroke', '#000') - vis.setAttribute('stroke-width', '1.5') - vis.setAttribute('pointer-events', 'none') - vis.setAttribute('id', id) - vis.setAttribute('data-anno-id', id) - vis.setAttribute('data-anno-name-fr', frName) - vis.setAttribute('data-anno-name-en', enName) - vis.setAttribute('data-anno-category', cat) - if (CATEGORIES[cat]?.name) vis.setAttribute('data-anno-category-name', CATEGORIES[cat].name) - if (CATEGORIES[cat]?.special) vis.setAttribute('data-anno-special', CATEGORIES[cat].special!) - const t2 = document.createElementNS('http://www.w3.org/2000/svg', 'title') - t2.textContent = frName - vis.appendChild(t2) - overlayG.appendChild(vis) - - setMode('select') - selectElement(hit as unknown as SVGElement) - refreshElementList() - refreshCategoryList() - setTimeout(() => (getEl('svg-editor-edit-fr') as HTMLInputElement).focus(), 50) - } - - function updatePolygonPreview() { - if (!svgRoot) return - svgRoot - .querySelectorAll('.polygon-preview, .polygon-preview-pt') - .forEach((p) => p.remove()) - if (polygonPoints.length < 1) return - - if (polygonPoints.length >= 2) { - const poly = document.createElementNS('http://www.w3.org/2000/svg', 'polygon') - poly.setAttribute('points', polygonPoints.map((p) => p.join(',')).join(' ')) - poly.classList.add('polygon-preview') - poly.setAttribute('pointer-events', 'none') - svgRoot.appendChild(poly) - } - polygonPoints.forEach(([x, y]) => { - const pt = document.createElementNS('http://www.w3.org/2000/svg', 'circle') - pt.setAttribute('cx', String(x)) - pt.setAttribute('cy', String(y)) - pt.setAttribute('r', '6') - pt.classList.add('polygon-preview-pt') - pt.setAttribute('pointer-events', 'none') - svgRoot!.appendChild(pt) - }) - } - - let _polygonRestartMemo: { - id: string - fr: string - en: string - cat: string - fill: string - fillOpacity: string - stroke: string - strokeWidth: string - } | null = null - - function finalizePolygon() { - if (!svgRoot) return - if (polygonPoints.length < 3) { - alert(t('svg_editor.alert_min_3')) - return - } - - const memo = _polygonRestartMemo - _polygonRestartMemo = null - - const cat = memo - ? memo.cat - : (getEl('svg-editor-default-category') as HTMLSelectElement).value || 'custom' - const color = memo ? memo.fill : CATEGORIES[cat]?.color || '#00aaff' - - let overlayG = svgRoot.querySelector('#osteo-overlays') - if (!overlayG) { - overlayG = document.createElementNS('http://www.w3.org/2000/svg', 'g') - overlayG.setAttribute('id', 'osteo-overlays') - svgRoot.appendChild(overlayG) - } - - const id = memo ? memo.id : 'zone-' + Date.now().toString(36) - const frName = memo ? memo.fr || t('svg_editor.new_zone_fr') : t('svg_editor.new_zone_fr') - const enName = memo ? memo.en || t('svg_editor.new_zone_en') : t('svg_editor.new_zone_en') - const poly = document.createElementNS('http://www.w3.org/2000/svg', 'polygon') - poly.setAttribute( - 'points', - polygonPoints.map((p) => p.map(Math.round).join(',')).join(' '), - ) - poly.setAttribute('fill', color) - poly.setAttribute('fill-opacity', memo ? memo.fillOpacity || '0.30' : '0.30') - poly.setAttribute('stroke', memo ? memo.stroke || color : color) - poly.setAttribute('stroke-width', memo ? memo.strokeWidth || '2' : '2') - poly.setAttribute('pointer-events', 'all') - poly.setAttribute('style', 'cursor:pointer') - poly.setAttribute('id', id) - poly.setAttribute('data-anno-id', id) - poly.setAttribute('data-anno-name-fr', frName) - poly.setAttribute('data-anno-name-en', enName) - poly.setAttribute('data-anno-category', cat) - if (CATEGORIES[cat]?.name) - poly.setAttribute('data-anno-category-name', CATEGORIES[cat].name) - if (CATEGORIES[cat]?.special) - poly.setAttribute('data-anno-special', CATEGORIES[cat].special!) - const titleEl = document.createElementNS('http://www.w3.org/2000/svg', 'title') - titleEl.textContent = - poly.getAttribute('data-anno-name-fr') + ' / ' + poly.getAttribute('data-anno-name-en') - poly.appendChild(titleEl) - overlayG.appendChild(poly) - - cancelPolygon() - setMode('select') - selectElement(poly as unknown as SVGElement) - refreshElementList() - refreshCategoryList() - if (!memo) setTimeout(() => (getEl('svg-editor-edit-fr') as HTMLInputElement).focus(), 50) - } - - function cancelPolygon() { - polygonPoints = [] - svgRoot - ?.querySelectorAll('.polygon-preview, .polygon-preview-pt') - .forEach((p) => p.remove()) - } - - function refreshCategoryList() { - const list = getEl('svg-editor-category-list') - - const activeEl = document.activeElement as HTMLElement | null - if (activeEl && list.contains(activeEl)) { - list.querySelectorAll('.cat-row').forEach((row) => { - const cat = (row as HTMLElement).dataset.cat! - const countEl = row.querySelector('.count') - if (countEl && svgRoot) { - const n = svgRoot.querySelectorAll( - `[data-anno-category="${cat}"]:not([fill="transparent"])`, - ).length - countEl.textContent = String(n) - } - }) - return - } - - list.textContent = '' - - if (Object.keys(CATEGORIES).length === 0) { - const emptyMsg = document.createElement('div') - emptyMsg.style.cssText = 'font-size:12px; color:var(--color-ink-muted); padding:8px; text-align:center;' - emptyMsg.textContent = t('svg_editor.no_categories') - list.appendChild(emptyMsg) - return - } - - for (const [cat, info] of Object.entries(CATEGORIES)) { - const count = svgRoot - ? svgRoot.querySelectorAll(`[data-anno-category="${cat}"]:not([fill="transparent"])`).length - : 0 - - const hasSpecial = !!(info.special?.trim()) - const row = document.createElement('div') - row.className = 'cat-row' - row.dataset.cat = cat - - const chk = document.createElement('input') - chk.type = 'checkbox' - chk.checked = info.visible - chk.title = 'Visibility' - - const colorInput = document.createElement('input') - colorInput.type = 'color' - colorInput.value = info.color - colorInput.title = 'Color' - - const nameSpan = document.createElement('span') - nameSpan.className = 'name' - nameSpan.title = cat - nameSpan.textContent = info.name - - const countSpan = document.createElement('span') - countSpan.className = 'count' - countSpan.textContent = String(count) - - const specialBtn = document.createElement('button') - specialBtn.className = 'special-btn' + (hasSpecial ? ' has-value' : '') - specialBtn.title = 'Special behavior' - specialBtn.textContent = '⚡' - - const delBtn = document.createElement('button') - delBtn.className = 'delete' - delBtn.title = 'Delete category' - delBtn.textContent = '×' - - row.append(chk, colorInput, nameSpan) - if (hasSpecial) { - const badge = document.createElement('span') - badge.className = 'special-badge' - badge.title = 'Behavior: ' + (info.special || '') - badge.textContent = '⚡ ' + (info.special || '') - row.appendChild(badge) - } - row.append(countSpan, specialBtn, delBtn) - - chk.addEventListener('change', () => { - info.visible = chk.checked - canvasInner.classList.toggle('hide-' + cat, !info.visible) - }) - - colorInput.addEventListener('change', () => { - info.color = colorInput.value - svgRoot?.querySelectorAll(`[data-anno-category="${cat}"]`).forEach((svgEl) => { - if (svgEl.getAttribute('fill') === 'transparent') return - svgEl.setAttribute('fill', info.color) - if (svgEl.tagName.toLowerCase() === 'polygon') { - svgEl.setAttribute('stroke', info.color) - } - }) - refreshElementList() - }) - - nameSpan.addEventListener('click', () => { - const newName = prompt('Rename category:', info.name) - if (newName?.trim()) { - info.name = newName.trim() - svgRoot?.querySelectorAll(`[data-anno-category="${cat}"]`).forEach((svgEl) => { - svgEl.setAttribute('data-anno-category-name', info.name) - }) - refreshCategoryList() - refreshCategorySelects() - } - }) - - specialBtn.addEventListener('click', () => openSpecialDialog(cat)) - delBtn.addEventListener('click', () => deleteCategory(cat)) - - list.appendChild(row) - } - } - - function refreshCategorySelects() { - const def = getEl('svg-editor-default-category') as HTMLSelectElement - const editSel = getEl('svg-editor-edit-category') as HTMLSelectElement - const defVal = def.value - const editVal = editSel.value - - def.textContent = '' - editSel.textContent = '' - - for (const [cat, info] of Object.entries(CATEGORIES)) { - const opt1 = document.createElement('option') - opt1.value = cat - opt1.textContent = info.name + ' (' + cat + ')' - def.appendChild(opt1) - - const opt2 = document.createElement('option') - opt2.value = cat - opt2.textContent = info.name + ' (' + cat + ')' - editSel.appendChild(opt2) - } - - if (defVal) def.value = defVal - if (editVal) editSel.value = editVal - } - - function openSpecialDialog(catId: string) { - const info = CATEGORIES[catId] - if (!info) return - const current = info.special || '' - - const lines = SPECIAL_BEHAVIORS.map((b, i) => `${i + 1}. ${b.id} — ${b.desc}`).join('\n') - const txt = `Special behavior for category "${info.name}". - -Suggestions: -${lines} - -Type a name (suggested or custom), or leave empty to remove. -Current: ${current || '(none)'}` - - const result = prompt(txt, current) - if (result === null) return - - const trimmed = result.trim() - info.special = trimmed - - svgRoot?.querySelectorAll(`[data-anno-category="${catId}"]`).forEach((svgEl) => { - if (trimmed) { - svgEl.setAttribute('data-anno-special', trimmed) - } else { - svgEl.removeAttribute('data-anno-special') - } - }) - - refreshCategoryList() - refreshElementList() - } - - function addCategory() { - const name = (getEl('svg-editor-new-cat-name') as HTMLInputElement).value.trim() - const color = (getEl('svg-editor-new-cat-color') as HTMLInputElement).value - if (!name) { - alert(t('svg_editor.alert_cat_name_required')) - return - } - const slug = name - .toLowerCase() - .normalize('NFD') - .replace(/[̀-ͯ]/g, '') - .replace(/[^a-z0-9]+/g, '-') - .replace(/^-|-$/g, '') - if (!slug) { - alert(t('svg_editor.alert_cat_invalid_name')) - return - } - - if (CATEGORIES[slug]) { - alert(t('svg_editor.alert_cat_exists')) - return - } - - CATEGORIES[slug] = { color, name, visible: true } - ;(getEl('svg-editor-new-cat-name') as HTMLInputElement).value = '' - refreshCategoryList() - refreshCategorySelects() - } - - function deleteCategory(cat: string) { - if (!svgRoot) return - const count = svgRoot.querySelectorAll( - `[data-anno-category="${cat}"]:not([fill="transparent"])`, - ).length - let msg = t('svg_editor.confirm_delete_cat').replace('{name}', CATEGORIES[cat].name) - if (count > 0) { - msg += t('svg_editor.confirm_delete_cat_count').replace('{count}', String(count)) - } - if (!confirm(msg)) return - - svgRoot.querySelectorAll(`[data-anno-category="${cat}"]`).forEach((svgEl) => { - svgEl.parentNode?.removeChild(svgEl) - }) - - delete CATEGORIES[cat] - refreshCategoryList() - refreshCategorySelects() - refreshElementList() - } - - function refreshElementList() { - if (!svgRoot) return - const filter = ((getEl('svg-editor-filter-input') as HTMLInputElement).value || '').toLowerCase() - const seen = new Set() - const items: { - id: string - fr: string - cat: string - catName: string - color: string - detail: string - }[] = [] - - svgRoot.querySelectorAll('[data-anno-id]').forEach((svgEl) => { - const id = svgEl.getAttribute('data-anno-id')! - if (seen.has(id)) return - const cat = svgEl.getAttribute('data-anno-category') || '' - seen.add(id) - - const fr = svgEl.getAttribute('data-anno-name-fr') || '' - const catName = CATEGORIES[cat] ? CATEGORIES[cat].name : cat || 'no cat.' - - if ( - filter && - !id.toLowerCase().includes(filter) && - !fr.toLowerCase().includes(filter) && - !catName.toLowerCase().includes(filter) - ) - return - - const visibleEl: Element = - svgRoot!.querySelector(`[data-anno-id="${cssEscape(id)}"]:not([fill="transparent"])`) || - svgEl - const color = visibleEl.getAttribute('fill') || '#888' - const detail = - visibleEl.getAttribute('data-anno-opens-detail') || - svgEl.getAttribute('data-anno-opens-detail') || - '' - - items.push({ id, fr, cat, catName, color, detail }) - }) - - items.sort((a, b) => (a.cat || '').localeCompare(b.cat || '') || a.fr.localeCompare(b.fr)) - - getEl('svg-editor-count').textContent = String(items.length) - - const list = getEl('svg-editor-element-list') - const selId = selected ? selected.getAttribute('data-anno-id') : null - list.textContent = '' - - items.forEach(({ id, fr, catName, color, detail }) => { - const div = document.createElement('div') - div.className = 'element-item' + (id === selId ? ' selected' : '') - div.dataset.id = id - - const swatch = document.createElement('span') - swatch.className = 'swatch' - swatch.style.background = color - - const nameSpan = document.createElement('span') - nameSpan.className = 'name' - nameSpan.textContent = detail ? 'Detail: ' + detail : fr || id - - const catSpan = document.createElement('span') - catSpan.className = 'cat' - catSpan.textContent = detail ? 'detail' : catName - - div.append(swatch, nameSpan, catSpan) - list.appendChild(div) - - div.addEventListener('click', () => { - const candidates = svgRoot!.querySelectorAll( - `[data-anno-id="${cssEscape(id)}"]`, - ) - let target: SVGElement | null = null - candidates.forEach((c) => { - if (target) return - if (c.getAttribute('fill') === 'transparent') return - target = c as SVGElement - }) - if (!target && candidates.length > 0) { - target = candidates[0] as SVGElement - } - if (target) { - setMode('select') - selectElement(target) - scrollSvgElementIntoView(target) - flashSelected(target) - } - }) - }) - } - - function parsePoints(str: string) { - return str - .trim() - .split(/\s+/) - .filter((p) => p) - .map((p) => p.split(',').map(Number)) - } - function pointsToStr(points: number[][]) { - return points.map((p) => p.map((v) => Math.round(v * 10) / 10).join(',')).join(' ') - } - - function showPolygonHandles(polygon: SVGElement) { - hidePolygonHandles() - if (!svgRoot) return - const points = parsePoints(polygon.getAttribute('points')!) - - let handlesG = svgRoot.querySelector('#polygon-handles') - if (!handlesG) { - handlesG = document.createElementNS('http://www.w3.org/2000/svg', 'g') - handlesG.setAttribute('id', 'polygon-handles') - svgRoot.appendChild(handlesG) - } - svgRoot.appendChild(handlesG) - - for (let i = 0; i < points.length; i++) { - const [x1, y1] = points[i] - const [x2, y2] = points[(i + 1) % points.length] - const mx = (x1 + x2) / 2 - const my = (y1 + y2) / 2 - const m = document.createElementNS('http://www.w3.org/2000/svg', 'circle') - m.setAttribute('cx', String(mx)) - m.setAttribute('cy', String(my)) - m.setAttribute('r', '6') - m.classList.add('polygon-midhandle') - m.setAttribute('data-edge-idx', String(i)) - const titleEl = document.createElementNS('http://www.w3.org/2000/svg', 'title') - titleEl.textContent = t('svg_editor.handle_insert') - m.appendChild(titleEl) - handlesG.appendChild(m) - } - - points.forEach(([x, y], i) => { - const h = document.createElementNS('http://www.w3.org/2000/svg', 'circle') - h.setAttribute('cx', String(x)) - h.setAttribute('cy', String(y)) - h.setAttribute('r', '8') - h.classList.add('polygon-handle') - h.setAttribute('data-vertex-idx', String(i)) - const titleEl = document.createElementNS('http://www.w3.org/2000/svg', 'title') - titleEl.textContent = t('svg_editor.handle_drag') - h.appendChild(titleEl) - handlesG!.appendChild(h) - }) - } - - function hidePolygonHandles() { - const g = svgRoot?.querySelector('#polygon-handles') - if (g) g.textContent = '' - } - - function restartCurrentPolygon() { - if (!selected || selected.tagName.toLowerCase() !== 'polygon') return - if (!confirm(t('svg_editor.confirm_redraw'))) return - _polygonRestartMemo = { - id: selected.getAttribute('data-anno-id') || '', - fr: selected.getAttribute('data-anno-name-fr') || '', - en: selected.getAttribute('data-anno-name-en') || '', - cat: selected.getAttribute('data-anno-category') || '', - fill: selected.getAttribute('fill') || '', - fillOpacity: selected.getAttribute('fill-opacity') || '', - stroke: selected.getAttribute('stroke') || '', - strokeWidth: selected.getAttribute('stroke-width') || '', - } - selected.parentNode?.removeChild(selected) - deselect() - setMode('polygon') - } - - function scrollSvgElementIntoView(svgEl: SVGElement) { - const elRect = svgEl.getBoundingClientRect() - const cRect = canvasInner.getBoundingClientRect() - - const visible = - elRect.left >= cRect.left && - elRect.right <= cRect.right && - elRect.top >= cRect.top && - elRect.bottom <= cRect.bottom - if (visible) return - - const dx = elRect.left + elRect.width / 2 - (cRect.left + cRect.width / 2) - const dy = elRect.top + elRect.height / 2 - (cRect.top + cRect.height / 2) - - canvasInner.scrollTo({ - left: canvasInner.scrollLeft + dx, - top: canvasInner.scrollTop + dy, - behavior: 'smooth', - }) - } - - function flashSelected(svgEl: SVGElement) { - const id = svgEl.getAttribute('data-anno-id') - const cat = svgEl.getAttribute('data-anno-category') - if (!id || !svgRoot) return - const all = svgRoot.querySelectorAll(`[data-anno-id="${cssEscape(id)}"]`) - all.forEach((e) => { - if (e.getAttribute('data-anno-category') !== cat) return - e.classList.remove('flashing') - void (e as HTMLElement).getBoundingClientRect() - e.classList.add('flashing') - setTimeout(() => e.classList.remove('flashing'), 1200) - }) - } - - function exportSVG() { - if (!svgRoot) { - alert(t('svg_editor.alert_no_svg_loaded')) - return - } - const clone = svgRoot.cloneNode(true) as SVGSVGElement - clone.querySelectorAll('.polygon-preview, .polygon-preview-pt').forEach((p) => p.remove()) - const handles = clone.querySelector('#polygon-handles') - if (handles) handles.remove() - clone.querySelectorAll('.selected, .flashing').forEach((p) => { - p.classList.remove('selected') - p.classList.remove('flashing') - }) - - const ser = new XMLSerializer() - const txt = `\n` + ser.serializeToString(clone) - - const blob = new Blob([txt], { type: 'image/svg+xml;charset=utf-8' }) - const url = URL.createObjectURL(blob) - const a = document.createElement('a') - a.href = url - a.download = loadedFileName - document.body.appendChild(a) - a.click() - document.body.removeChild(a) - URL.revokeObjectURL(url) - } - - function applyZoom() { - if (!svgRoot) return - svgRoot.style.transform = `scale(${zoom})` - svgRoot.style.transformOrigin = 'top left' - } - - return () => { ac.abort() } -} diff --git a/apps/app/src/components/brand/Footer.tsx b/apps/app/src/components/brand/Footer.tsx index 6d0bb587..84ff2c6b 100644 --- a/apps/app/src/components/brand/Footer.tsx +++ b/apps/app/src/components/brand/Footer.tsx @@ -1,4 +1,3 @@ -import { Link } from 'react-router-dom' import { useConfig } from '@/app/providers/ConfigProvider' import { useT } from '@/i18n/useT' @@ -9,14 +8,7 @@ export default function Footer() { return (

- © {year} {cfg.footerName}. {t('footer.all_rights_reserved')}{' '} - ·{' '} - - {t('footer.editors')} - + © {year} {cfg.footerName}. {t('footer.all_rights_reserved')}

diff --git a/apps/app/src/components/canvas/AnatomyCanvas.tsx b/apps/app/src/components/canvas/AnatomyCanvas.tsx index 17a410f4..791f6403 100644 --- a/apps/app/src/components/canvas/AnatomyCanvas.tsx +++ b/apps/app/src/components/canvas/AnatomyCanvas.tsx @@ -1,77 +1,83 @@ -import { useCallback, useEffect, useRef, useState } from 'react' -import { loadSvg } from '@/anatomy/svgLoader' -import { - getBoneIdFromEvent, - getAnnotatedElement, -} from '@/anatomy/svgConvention' -import type { BoneState } from '@/anatomy/types' +import { useCallback, useEffect, useRef } from 'react' +import { buildViewSvg, type ViewStates } from '@/anatomy/drawing' +import type { SheetIndex } from '@/services/sheetIndex' import { useLocaleStore } from '@/state/localeStore' import { pickLocaleLabel } from '@/i18n/pickLocaleLabel' export interface AnatomyCanvasProps { - src: string - boneStates: Map - onZoneClick: (boneId: string) => void + index: SheetIndex + viewId: string + states: ViewStates + onZoneClick: (annotationId: string, viewId: string) => void className?: string } +const ANNOTATED = '[data-anno-id]' + +function annotatedTarget(event: Event): Element | null { + const target = event.target + return target instanceof Element ? target.closest(ANNOTATED) : null +} + +/** + * One view of the sheet: the drawing plus the annotation layer generated + * from the document, rebuilt when the view changes and restyled in place + * when the selection changes. Clicks are delegated on `data-anno-id`. + */ export default function AnatomyCanvas({ - src, - boneStates, + index, + viewId, + states, onZoneClick, className = '', }: AnatomyCanvasProps) { const wrapperRef = useRef(null) const svgRef = useRef(null) const tooltipRef = useRef(null) - const [loadedSrc, setLoadedSrc] = useState(null) const locale = useLocaleStore((s) => s.locale) useEffect(() => { - let cancelled = false - const c = svgRef.current - if (!c) return - c.replaceChildren() - setLoadedSrc(null) - loadSvg(src).then((root) => { - if (cancelled || !c) return - c.appendChild(root) - setLoadedSrc(src) - }) - return () => { cancelled = true } - }, [src]) + const host = svgRef.current + if (!host) return + host.replaceChildren(buildViewSvg(index, viewId, states)) + // States are applied by the effect below; the build only needs the view. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [index, viewId]) useEffect(() => { - const c = svgRef.current - if (!c) return - const onClick = (e: Event) => { - const id = getBoneIdFromEvent(e) - if (id) onZoneClick(id) - } - c.addEventListener('click', onClick) - return () => c.removeEventListener('click', onClick) - }, [onZoneClick]) - - useEffect(() => { - const c = svgRef.current - if (!c || loadedSrc !== src) return - const all = c.querySelectorAll('[data-anno-id]') - all.forEach((el) => { - const id = el.getAttribute('data-anno-id') as string - const state = boneStates.get(id) - if (state && state !== 'default') el.setAttribute('data-state', state) + const host = svgRef.current + if (!host) return + host.querySelectorAll(ANNOTATED).forEach((el) => { + const state = states.get(el.getAttribute('data-anno-id') ?? '') + if (state) el.setAttribute('data-state', state) else el.removeAttribute('data-state') }) - }, [boneStates, loadedSrc, src]) + }, [states, index, viewId]) + + useEffect(() => { + const host = svgRef.current + if (!host) return + const onClick = (e: Event) => { + const id = annotatedTarget(e)?.getAttribute('data-anno-id') + if (id) onZoneClick(id, viewId) + } + host.addEventListener('click', onClick) + return () => host.removeEventListener('click', onClick) + }, [onZoneClick, viewId]) const showTooltip = useCallback( (el: Element, x: number, y: number) => { const tip = tooltipRef.current if (!tip) return - const fr = el.getAttribute('data-anno-name-fr') ?? '' - const en = el.getAttribute('data-anno-name-en') ?? '' - const label = pickLocaleLabel(fr, en, locale) - if (!label) { tip.style.opacity = '0'; return } + const label = pickLocaleLabel( + el.getAttribute('data-anno-name-fr') ?? '', + el.getAttribute('data-anno-name-en') ?? '', + locale, + ) + if (!label) { + tip.style.opacity = '0' + return + } tip.textContent = label tip.style.opacity = '1' tip.style.left = `${x + 12}px` @@ -80,46 +86,40 @@ export default function AnatomyCanvas({ [locale], ) - const hideTooltip = useCallback(() => { - const tip = tooltipRef.current - if (tip) tip.style.opacity = '0' - }, []) - useEffect(() => { - const c = svgRef.current - if (!c || loadedSrc !== src) return + const host = svgRef.current + if (!host) return + const hide = () => { + if (tooltipRef.current) tooltipRef.current.style.opacity = '0' + } const onMove = (e: MouseEvent) => { - const el = getAnnotatedElement(e) - if (el && !el.hasAttribute('data-anno-opens-detail')) { - const w = wrapperRef.current - if (!w) return - const rect = w.getBoundingClientRect() - showTooltip(el, e.clientX - rect.left, e.clientY - rect.top) - } else { - hideTooltip() - } + const el = annotatedTarget(e) + const wrapper = wrapperRef.current + if (!el || !wrapper || el.hasAttribute('data-anno-opens-view')) + return hide() + const rect = wrapper.getBoundingClientRect() + showTooltip(el, e.clientX - rect.left, e.clientY - rect.top) } - const onLeave = () => hideTooltip() - c.addEventListener('mousemove', onMove) - c.addEventListener('mouseleave', onLeave) + host.addEventListener('mousemove', onMove) + host.addEventListener('mouseleave', hide) return () => { - c.removeEventListener('mousemove', onMove) - c.removeEventListener('mouseleave', onLeave) + host.removeEventListener('mousemove', onMove) + host.removeEventListener('mouseleave', hide) } - }, [loadedSrc, src, showTooltip, hideTooltip]) + }, [showTooltip]) return (
-
+
) } diff --git a/apps/app/src/components/canvas/DetailModal.tsx b/apps/app/src/components/canvas/DetailModal.tsx index d3056126..3bbe1dae 100644 --- a/apps/app/src/components/canvas/DetailModal.tsx +++ b/apps/app/src/components/canvas/DetailModal.tsx @@ -1,25 +1,27 @@ import Dialog from '@/components/ui/Dialog' import AnatomyCanvas from './AnatomyCanvas' -import type { BoneState } from '@/anatomy/types' +import type { ViewStates } from '@/anatomy/drawing' +import type { SheetIndex } from '@/services/sheetIndex' import { useT } from '@/i18n/useT' export interface DetailModalProps { open: boolean onClose: () => void - detailSrc: string - detailId: string + index: SheetIndex + viewId: string title: string - boneStates: Map - onZoneClick: (boneId: string, detailId: string) => void + states: ViewStates + onZoneClick: (annotationId: string, viewId: string) => void } +/** A detail view of the sheet (a crop or its own drawing) in a dialog. */ export default function DetailModal({ open, onClose, - detailSrc, - detailId, + index, + viewId, title, - boneStates, + states, onZoneClick, }: DetailModalProps) { const t = useT() @@ -27,9 +29,10 @@ export default function DetailModal({
onZoneClick(id, detailId)} + index={index} + viewId={viewId} + states={states} + onZoneClick={onZoneClick} />

diff --git a/apps/app/src/components/observation/FindingsTreePicker.tsx b/apps/app/src/components/observation/FindingsTreePicker.tsx index 221aae5f..48734eab 100644 --- a/apps/app/src/components/observation/FindingsTreePicker.tsx +++ b/apps/app/src/components/observation/FindingsTreePicker.tsx @@ -1,75 +1,84 @@ import { useMemo, useState } from 'react' import { motion } from 'motion/react' import type { + Finding, + FindingCategory, FindingNode, - ZoneFindings, -} from '@/domain/schema/findings' -import type { Finding, LateralSide } from '@/domain/schema/observation' + FindingZone, + LateralSide, + LocalizedOptionalText, +} from '@faunosteo/domain' import Button from '@/components/ui/Button' +import { pickLabel } from '@/services/sheetIndex' import { useT } from '@/i18n/useT' import { useLocaleStore } from '@/state/localeStore' +import type { Locale } from '@/i18n/types' const levelVariants = { enter: (dir: 1 | -1) => ({ opacity: 0, x: dir * 32 }), center: { opacity: 1, x: 0 }, } +type TreeNode = FindingCategory | FindingNode + export interface FindingsTreePickerProps { - zoneId: string - tree: ZoneFindings + zone: FindingZone side?: LateralSide selected: Finding[] onChange: (next: Finding[]) => void } -function isLeaf(node: FindingNode): boolean { - return !node.children || node.children.length === 0 +function isLeaf(node: TreeNode): boolean { + return node.children.length === 0 } -function samePath(a: string[], b: string[]): boolean { - if (a.length !== b.length) return false - for (let i = 0; i < a.length; i += 1) { - if (a[i] !== b[i]) return false - } - return true +function samePath(a: readonly string[], b: readonly string[]): boolean { + return a.length === b.length && a.every((seg, i) => seg === b[i]) } -function pathStartsWith(full: string[], prefix: string[]): boolean { - if (full.length < prefix.length) return false - for (let i = 0; i < prefix.length; i += 1) { - if (full[i] !== prefix[i]) return false - } - return true +function pathStartsWith( + full: readonly string[], + prefix: readonly string[], +): boolean { + return ( + full.length >= prefix.length && prefix.every((seg, i) => full[i] === seg) + ) } function findNode( - categories: FindingNode[], - path: string[], -): FindingNode | undefined { - let nodes: FindingNode[] = categories - let node: FindingNode | undefined + categories: readonly FindingCategory[], + path: readonly string[], +): TreeNode | undefined { + let nodes: readonly TreeNode[] = categories + let node: TreeNode | undefined for (const segment of path) { node = nodes.find((n) => n.id === segment) if (!node) return undefined - nodes = node.children ?? [] + nodes = node.children } return node } +function descriptionOf(node: TreeNode, locale: Locale): string | undefined { + const text: LocalizedOptionalText | undefined = node.description + if (!text) return undefined + return ( + (locale === 'en' ? text.en || text.fr : text.fr || text.en) || undefined + ) +} + +/** + * Drill-down picker over one finding zone of the sheet. A finding is keyed + * by `(findingZoneId, path, side)`; labels are snapshotted at selection. + */ export default function FindingsTreePicker({ - zoneId, - tree, + zone, side, selected, onChange, }: FindingsTreePickerProps) { const t = useT() const locale = useLocaleStore((s) => s.locale) - const nameOf = (node: { name_fr: string; name_en: string }) => - locale === 'en' ? node.name_en : node.name_fr - const descOf = (node: { description_fr?: string; description_en?: string }) => - locale === 'en' ? node.description_en : node.description_fr - const [path, setPath] = useState([]) const [direction, setDirection] = useState<1 | -1>(1) @@ -86,74 +95,57 @@ export default function FindingsTreePicker({ setPath(path.slice(0, depth)) } - const currentNodes = useMemo(() => { - if (path.length === 0) return tree.categories - const node = findNode(tree.categories, path) - return node?.children ?? [] - }, [tree, path]) + const currentNodes = useMemo(() => { + if (path.length === 0) return zone.categories + return findNode(zone.categories, path)?.children ?? [] + }, [zone, path]) const focusedNode = useMemo( - () => (path.length === 0 ? undefined : findNode(tree.categories, path)), - [tree, path], + () => (path.length === 0 ? undefined : findNode(zone.categories, path)), + [zone, path], ) const breadcrumb = useMemo<{ label: string; depth: number }[]>(() => { - const pick = (z: { name_fr: string; name_en: string }) => - locale === 'en' ? z.name_en : z.name_fr - const crumbs: { label: string; depth: number }[] = [ - { label: pick(tree), depth: 0 }, - ] - let nodes: FindingNode[] = tree.categories + const crumbs = [{ label: pickLabel(zone.name, locale), depth: 0 }] + let nodes: readonly TreeNode[] = zone.categories path.forEach((seg, i) => { const n = nodes.find((x) => x.id === seg) if (n) { - crumbs.push({ label: pick(n), depth: i + 1 }) - nodes = n.children ?? [] + crumbs.push({ label: pickLabel(n.name, locale), depth: i + 1 }) + nodes = n.children } }) return crumbs - }, [tree, path, locale]) + }, [zone, path, locale]) - function matchesSide(f: Finding): boolean { - return f.zoneId === zoneId && f.side === side - } + const matches = (f: Finding) => f.findingZoneId === zone.id && f.side === side + const isLeafSelected = (leafPath: string[]) => + selected.some((f) => matches(f) && samePath(f.path, leafPath)) + const countSelectedUnder = (nodePath: string[]) => + selected.filter((f) => matches(f) && pathStartsWith(f.path, nodePath)) + .length - function isLeafSelected(leafPath: string[]): boolean { - return selected.some( - (f) => matchesSide(f) && samePath(f.path, leafPath), - ) - } - - function countSelectedUnder(nodePath: string[]): number { - let n = 0 - for (const f of selected) { - if (!matchesSide(f)) continue - if (!pathStartsWith(f.path, nodePath)) continue - n += 1 - } - return n - } - - function toggleLeaf(leafPath: string[], leaf: FindingNode) { + function toggleLeaf(leafPath: string[], leaf: TreeNode) { if (isLeafSelected(leafPath)) { onChange( - selected.filter( - (f) => !(matchesSide(f) && samePath(f.path, leafPath)), - ), + selected.filter((f) => !(matches(f) && samePath(f.path, leafPath))), ) return } const next: Finding = { - zoneId, + findingZoneId: zone.id, path: leafPath, - labelFrSnapshot: leaf.name_fr, - labelEnSnapshot: leaf.name_en, + labelFrSnapshot: leaf.name.fr, + labelEnSnapshot: leaf.name.en, } - if (leaf.requires_vet_referral) next.requiresVetReferral = true + if ('requires_vet_referral' in leaf && leaf.requires_vet_referral) + next.requiresVetReferral = true if (side) next.side = side onChange([...selected, next]) } + const focusedDescription = focusedNode && descriptionOf(focusedNode, locale) + return (

@@ -179,9 +171,9 @@ export default function FindingsTreePicker({ })}
- {focusedNode && descOf(focusedNode) && ( + {focusedDescription && (

- {descOf(focusedNode)} + {focusedDescription}

)} @@ -196,16 +188,16 @@ export default function FindingsTreePicker({ )} - + {currentNodes.length === 0 ? (
  • {t('findings.no_options')} @@ -213,16 +205,17 @@ export default function FindingsTreePicker({ ) : ( currentNodes.map((node) => { const nodePath = [...path, node.id] + const nodeLabel = pickLabel(node.name, locale) + const nodeDesc = descriptionOf(node, locale) if (isLeaf(node)) { - const checked = isLeafSelected(nodePath) - const nodeLabel = nameOf(node) - const nodeDesc = descOf(node) + const vet = + 'requires_vet_referral' in node && node.requires_vet_referral return (
  • ) } diff --git a/apps/app/src/components/observation/LateralityPicker.tsx b/apps/app/src/components/observation/LateralityPicker.tsx index 3d3547e3..c6b34bba 100644 --- a/apps/app/src/components/observation/LateralityPicker.tsx +++ b/apps/app/src/components/observation/LateralityPicker.tsx @@ -1,6 +1,6 @@ import Dialog from '@/components/ui/Dialog' import Button from '@/components/ui/Button' -import type { LateralSide } from '@/domain/schema/observation' +import type { LateralSide } from '@faunosteo/domain' import { useT } from '@/i18n/useT' export interface LateralityPickerProps { diff --git a/apps/app/src/components/observation/ObservationCard.tsx b/apps/app/src/components/observation/ObservationCard.tsx index 86de9ea6..57f5b845 100644 --- a/apps/app/src/components/observation/ObservationCard.tsx +++ b/apps/app/src/components/observation/ObservationCard.tsx @@ -1,16 +1,11 @@ import { useMemo, useState } from 'react' import type { - Observation, - ObservationZone, - Vertebra, + Finding, + FindingZone, LateralSide, -} from '@/domain/schema/observation' -import type { - SpeciesFindings, - ZoneFindings, -} from '@/domain/schema/findings' -import type { Bone } from '@/anatomy/types' -import { matchZoneFindings } from '@/lib/zoneMatch' + Observation, + ReportZone, +} from '@faunosteo/domain' import { AnimatePresence, motion } from 'motion/react' import Card from '@/components/ui/Card' import Badge from '@/components/ui/Badge' @@ -20,9 +15,9 @@ import Textarea from '@/components/ui/Textarea' import FindingsTreePicker from './FindingsTreePicker' import FreeTextFindingInput from './FreeTextFindingInput' import SeveritySelector from './SeveritySelector' +import { isObservable, pickLabel, type SheetIndex } from '@/services/sheetIndex' import { useT } from '@/i18n/useT' import { useLocaleStore } from '@/state/localeStore' -import { boneLabel } from '@/anatomy/labels' import type { Locale } from '@/i18n/types' export interface ObservationCardProps { @@ -36,35 +31,75 @@ export interface ObservationCardProps { canMoveUp: boolean canMoveDown: boolean // Editor body props (used only when expanded) - bones: Map - findings: SpeciesFindings | null + sheet: SheetIndex onChange: (next: Observation) => void onOpenVertebraPicker: (zoneIndex: number) => void onRemoveZone: (zoneIndex: number) => void } +/** Zone label: the sheet's current name, else the snapshot, else the id. */ +export function zoneLabel( + z: ReportZone, + sheet: SheetIndex, + locale: Locale, +): string { + const annotation = sheet.annotation(z.annotationId) + if (annotation) return pickLabel(sheet.name(annotation), locale) + const snapshot = + locale === 'en' + ? z.labelEnSnapshot || z.labelFrSnapshot + : z.labelFrSnapshot || z.labelEnSnapshot + return snapshot || z.annotationId +} + function describeZone( - z: ObservationZone, - bones: Map, + z: ReportZone, + sheet: SheetIndex, locale: Locale, t: (key: string) => string, ): string { - const label = boneLabel(bones.get(z.boneId), locale, z.boneId) + const label = zoneLabel(z, sheet, locale) if (z.vertebrae?.length) { - const vs = z.vertebrae - .map((v: Vertebra) => `${v.region}${v.index}`) - .join(', ') - return `${label} (${vs})` + return `${label} (${z.vertebrae.map((v) => `${v.region}${v.index}`).join(', ')})` } if (z.side) { - const sideLabel = t( - z.side === 'left' ? 'lateral.left_short' : 'lateral.right_short', - ) - return `${label} (${sideLabel})` + return `${label} (${t(z.side === 'left' ? 'lateral.left_short' : 'lateral.right_short')})` } return label } +interface ZoneTree { + zone: FindingZone + side?: LateralSide +} + +/** One picker per (finding zone, side) the observation's zones resolve to. */ +function zoneTrees(observation: Observation, sheet: SheetIndex): ZoneTree[] { + const seen = new Set() + const out: ZoneTree[] = [] + for (const z of observation.zones) { + const annotation = sheet.annotation(z.annotationId) + if (!isObservable(annotation) || !annotation.finding_zone_id) continue + const zone = sheet.findingZone(annotation.finding_zone_id) + if (!zone) continue + const key = z.side ? `${zone.id}:${z.side}` : zone.id + if (seen.has(key)) continue + seen.add(key) + out.push({ zone, side: z.side }) + } + return out +} + +/** Findings the sheet no longer holds at their path (migrated data, kept verbatim). */ +function unresolvedFindings( + observation: Observation, + sheet: SheetIndex, +): Finding[] { + return observation.findings.filter( + (f) => !sheet.nodeAt(f.findingZoneId, f.path), + ) +} + export default function ObservationCard({ observation, index, @@ -75,34 +110,37 @@ export default function ObservationCard({ onMoveDown, canMoveUp, canMoveDown, - bones, - findings, + sheet, onChange, onOpenVertebraPicker, onRemoveZone, }: ObservationCardProps) { const t = useT() const locale = useLocaleStore((s) => s.locale) - const nameOf = (z: { name_fr: string; name_en: string }) => - locale === 'en' ? z.name_en : z.name_fr - - // Per-zone picker accordion — only one tree picker open at a time, - // matching the observation-card accordion semantics. Closed by default - // so the card stays compact when first expanded. const [expandedZoneId, setExpandedZoneId] = useState(null) const zoneCount = observation.zones.length const findingCount = observation.findings.length + observation.freeTextFindings.length - - const zoneCountLabel = + const zoneCountLabel = t( zoneCount > 1 - ? t('observation.zone_label_plural') - : t('observation.zone_label_singular') - const findingCountLabel = + ? 'observation.zone_label_plural' + : 'observation.zone_label_singular', + ) + const findingCountLabel = t( findingCount > 1 - ? t('observation.finding_label_plural') - : t('observation.finding_label_singular') + ? 'observation.finding_label_plural' + : 'observation.finding_label_singular', + ) + + const trees = useMemo( + () => zoneTrees(observation, sheet), + [observation, sheet], + ) + const unresolved = useMemo( + () => unresolvedFindings(observation, sheet), + [observation, sheet], + ) function onHeaderKey(event: React.KeyboardEvent) { if (event.key === 'Enter' || event.key === ' ') { @@ -110,39 +148,15 @@ export default function ObservationCard({ onToggle() } } - - function stop(fn: () => void) { - return (event: React.MouseEvent) => { - event.stopPropagation() - fn() - } + const stop = (fn: () => void) => (event: React.MouseEvent) => { + event.stopPropagation() + fn() } - - const zonesArray = useMemo( - () => (findings ? Object.values(findings.zones) : []), - [findings], - ) - - const zonesWithTree = useMemo(() => { - if (zonesArray.length === 0) - return [] as { tree: ZoneFindings; side?: LateralSide }[] - const seen = new Set() - const out: { tree: ZoneFindings; side?: LateralSide }[] = [] - for (const z of observation.zones) { - const bone = bones.get(z.boneId) - if (!bone) continue - const tree = matchZoneFindings( - { fr: bone.fr, en: bone.en }, - zonesArray, - ) - if (!tree) continue - const key = z.side ? `${tree.id}:${z.side}` : tree.id - if (seen.has(key)) continue - seen.add(key) - out.push({ tree, side: z.side }) - } - return out - }, [observation.zones, bones, zonesArray]) + const removeFinding = (target: Finding) => + onChange({ + ...observation, + findings: observation.findings.filter((f) => f !== target), + }) return (
    - {t('observation.badge_n')}{index + 1} + + {t('observation.badge_n')} + {index + 1} + {observation.severity && ( ) : (
      - {observation.zones.map((z, i) => { - const b = bones.get(z.boneId) - const supportsVertebrae = - b?.special === 'vertebral-precision' - return ( -
    • - - {describeZone(z, bones, locale, t)} - {supportsVertebrae && ( - + {t('observation.unresolved_short')} + )} + {sheet.isSpine(z.annotationId) && ( - -
    • - ) - })} + )} + + + + ))}
    )}
    - {zonesWithTree.length === 0 ? ( + {trees.length === 0 ? (

    {observation.zones.length === 0 ? t('observation.findings_pick_zone_first') @@ -292,26 +315,19 @@ export default function ObservationCard({

    ) : (
      - {zonesWithTree.map(({ tree, side }) => { - const pickerKey = side - ? `${tree.id}:${side}` - : tree.id - const expanded = expandedZoneId === pickerKey + {trees.map(({ zone, side }) => { + const pickerKey = side ? `${zone.id}:${side}` : zone.id + const open = expandedZoneId === pickerKey const selectedCount = observation.findings.filter( - (f) => - f.zoneId === tree.id && f.side === side, + (f) => f.findingZoneId === zone.id && f.side === side, ).length - const selectedAria = `${selectedCount} ${ - selectedCount > 1 - ? t('findings.selected_plural') - : t('findings.selected_singular') - }` + const selectedAria = `${selectedCount} ${selectedCount > 1 ? t('findings.selected_plural') : t('findings.selected_singular')}` return (
    • - setExpandedZoneId(expanded ? null : pickerKey) + setExpandedZoneId(open ? null : pickerKey) } - aria-expanded={expanded} + aria-expanded={open} aria-controls={`findings-zone-${pickerKey}`} className="w-full flex items-center justify-between gap-2 px-3 py-2 text-left rounded-xl focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]/40" > - {nameOf(tree)} - {side && ` (${t(side === 'left' ? 'lateral.left' : 'lateral.right')})`} + {pickLabel(zone.name, locale)} + {side && + ` (${t(side === 'left' ? 'lateral.left' : 'lateral.right')})`} {selectedCount > 0 && ( - {expanded && ( + {open && (
      - onChange({ ...observation, findings: next }) + onChange({ + ...observation, + findings: next, + }) } />
      @@ -378,6 +397,40 @@ export default function ObservationCard({ )}
    + {unresolved.length > 0 && ( +
    + +

    + {t('observation.findings_unresolved_help')} +

    +
      + {unresolved.map((f, i) => ( +
    • + + {f.requiresVetReferral ? '⚠ ' : ''} + {locale === 'en' + ? f.labelEnSnapshot + : f.labelFrSnapshot} + {f.side && + ` (${t(f.side === 'left' ? 'lateral.left_short' : 'lateral.right_short')})`} + + +
    • + ))} +
    +
    + )} +
    void onMoveDown: (i: number) => void // Editor body props forwarded to each card - bones: Map - findings: SpeciesFindings | null + sheet: SheetIndex onChange: (i: number, next: Observation) => void onOpenVertebraPicker: (i: number, zoneIndex: number) => void onRemoveZone: (i: number, zoneIndex: number) => void @@ -29,8 +27,7 @@ export default function ObservationList({ onDelete, onMoveUp, onMoveDown, - bones, - findings, + sheet, onChange, onOpenVertebraPicker, onRemoveZone, @@ -64,8 +61,7 @@ export default function ObservationList({ onMoveDown={() => onMoveDown(i)} canMoveUp={i > 0} canMoveDown={i < observations.length - 1} - bones={bones} - findings={findings} + sheet={sheet} onChange={(next) => onChange(i, next)} onOpenVertebraPicker={(zoneIndex) => onOpenVertebraPicker(i, zoneIndex) diff --git a/apps/app/src/components/observation/SeveritySelector.tsx b/apps/app/src/components/observation/SeveritySelector.tsx index 16f22c53..996159fc 100644 --- a/apps/app/src/components/observation/SeveritySelector.tsx +++ b/apps/app/src/components/observation/SeveritySelector.tsx @@ -1,4 +1,4 @@ -import type { Severity } from '@/domain/schema/observation' +import type { Severity } from '@faunosteo/domain' import { useT } from '@/i18n/useT' export interface SeveritySelectorProps { @@ -6,17 +6,25 @@ export interface SeveritySelectorProps { onChange: (s: Severity | undefined) => void } -const SEVERITIES: Severity[] = ['légère', 'modérée', 'sévère'] +export const SEVERITIES: Severity[] = ['mild', 'moderate', 'severe'] const COLORS: Record = { - 'légère': 'border-[var(--severity-mild)] text-[var(--severity-mild)]', - 'modérée': 'border-[var(--severity-moderate)] text-[var(--severity-moderate)]', - 'sévère': 'border-[var(--severity-severe)] text-[var(--severity-severe)]', + mild: 'border-[var(--severity-mild)] text-[var(--severity-mild)]', + moderate: 'border-[var(--severity-moderate)] text-[var(--severity-moderate)]', + severe: 'border-[var(--severity-severe)] text-[var(--severity-severe)]', } -export default function SeveritySelector({ value, onChange }: SeveritySelectorProps) { +/** Severity codes are persisted; labels come from the dictionary (D8). */ +export default function SeveritySelector({ + value, + onChange, +}: SeveritySelectorProps) { const t = useT() return ( -
    +
    {SEVERITIES.map((s) => ( ))}
    @@ -89,26 +96,52 @@ export default function VertebraPicker({ {Array.from({ length: count }, (_, k) => k + 1).map((i) => ( toggle(activeRegion, i)} + active={has(active.code, i)} + onClick={() => toggle(active.code, i)} > - {activeRegion}{i} + {active.code} + {i} ))}
    - - + {canExtend && !showExtended && ( + + )} + {canExtend && showExtended && ( + + {t('vertebra.range_note') + .replace('{usual}', String(active.count)) + .replace('{min}', String(active.count_range?.min ?? active.count)) + .replace('{max}', String(maxCount))} + + )}
    - - + +
    ) diff --git a/apps/app/src/components/report/AnimalForm.tsx b/apps/app/src/components/report/AnimalForm.tsx index effc2527..c04f9b67 100644 --- a/apps/app/src/components/report/AnimalForm.tsx +++ b/apps/app/src/components/report/AnimalForm.tsx @@ -1,23 +1,36 @@ -import type { Animal, Owner } from '@/domain/schema/animal' +import type { Animal, LocalizedText, Owner } from '@faunosteo/domain' import Label from '@/components/ui/Label' import Input from '@/components/ui/Input' import Select from '@/components/ui/Select' -import { getAllSpecies, speciesLabel } from '@/domain/species/registry' +import { pickLabel } from '@/services/sheetIndex' import { useT } from '@/i18n/useT' import { useLocaleStore } from '@/state/localeStore' +export interface SpeciesOption { + id: string + name: LocalizedText +} + export interface AnimalFormProps { animal: Animal owner: Owner + /** Species that have a sheet in this build (one today). */ + species: readonly SpeciesOption[] onChangeAnimal: (next: Animal) => void onChangeOwner: (next: Owner) => void } -export default function AnimalForm({ animal, owner, onChangeAnimal, onChangeOwner }: AnimalFormProps) { +export default function AnimalForm({ + animal, + owner, + species, + onChangeAnimal, + onChangeOwner, +}: AnimalFormProps) { const t = useT() const locale = useLocaleStore((s) => s.locale) - const species = getAllSpecies() - const setA = (patch: Partial) => onChangeAnimal({ ...animal, ...patch }) + const setA = (patch: Partial) => + onChangeAnimal({ ...animal, ...patch }) return (
    @@ -31,25 +44,45 @@ export default function AnimalForm({ animal, owner, onChangeAnimal, onChangeOwne onChange={(e) => setA({ speciesId: e.target.value })} > {species.map((s) => ( - + ))}
    - setA({ name: e.target.value })} /> + setA({ name: e.target.value })} + />
    - setA({ breed: e.target.value || undefined })} /> + setA({ breed: e.target.value || undefined })} + />
    - setA({ age: e.target.value || undefined })} /> + setA({ age: e.target.value || undefined })} + />
    - onChangeOwner({ name: e.target.value })} /> + onChangeOwner({ name: e.target.value })} + />
    ) diff --git a/apps/app/src/components/report/ConclusionPanel.tsx b/apps/app/src/components/report/ConclusionPanel.tsx index 72757b8d..d73b8651 100644 --- a/apps/app/src/components/report/ConclusionPanel.tsx +++ b/apps/app/src/components/report/ConclusionPanel.tsx @@ -1,4 +1,4 @@ -import type { Report } from '@/domain/schema/report' +import type { Report } from '@faunosteo/domain' import Label from '@/components/ui/Label' import Textarea from '@/components/ui/Textarea' import NextAppointmentPicker from './NextAppointmentPicker' @@ -29,13 +29,26 @@ export default function ConclusionPanel({
    -