-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathOpenFoodFactsPower.user.js
2824 lines (2477 loc) · 126 KB
/
OpenFoodFactsPower.user.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ==UserScript==
// @name Open Food Facts power user script
// @description Helps power users in their day to day work. Key "?" shows help. This extension is a kind of sandbox to experiment features that could be added to Open Food Facts website.
// @namespace openfoodfacts.org
// @version 2024-12-20T11:15
// @include https://*.openfoodfacts.org/*
// @include https://*.openproductsfacts.org/*
// @include https://*.openbeautyfacts.org/*
// @include https://*.openpetfoodfacts.org/*
// @include https://*.pro.openfoodfacts.org/*
// @include https://*.openfoodfacts.net/*
// @include https://*.openfoodfacts.dev/*
// @include http://*.productopener.localhost/*
// @include http://*.openfoodfacts.localhost/*
// @include http://*.openfoodfacts.localhost:8080/*
// @include http://*.openpetfoodfacts.localhost:*/*
// @include http://*.openproductsfacts.localhost:*/*
// @include http://*.openbeautyfacts.localhost:*/*
// @exclude https://analytics.openfoodfacts.org/*
// @exclude https://api.folksonomy.openfoodfacts.org/*
// @exclude https://*.wiki.openfoodfacts.org/*
// @exclude https://wiki.openfoodfacts.org/*
// @exclude https://support.openfoodfacts.org/*
// @exclude https://translate.openfoodfacts.org/*
// @exclude https://donate.openfoodfacts.org/*
// @exclude https://hunger.openfoodfacts.org/*
// @exclude https://monitoring.openfoodfacts.org/*
// @exclude https://forum.openfoodfacts.org/*
// @exclude https://*blog.openfoodfacts.org/*
// @exclude https://*connect.openfoodfacts.org/*
// @exclude https://*connect-test.openfoodfacts.org/*
// @exclude https://contents.openfoodfacts.org/*
// @exclude https://mirabelle.openfoodfacts.org/*
// @exclude https://prices.openfoodfacts.org/*
// @exclude https://search.openfoodfacts.org/*
//
// @icon http://world.openfoodfacts.org/favicon.ico
// @updateURL https://github.com/openfoodfacts/power-user-script/raw/master/OpenFoodFactsPower.user.js
// @grant GM_getResourceText
// @require http://code.jquery.com/jquery-latest.min.js
// @require http://code.jquery.com/ui/1.12.1/jquery-ui.min.js
// @require https://cdn.jsdelivr.net/npm/jsbarcode@latest/dist/JsBarcode.all.min.js
// @author [email protected]
// ==/UserScript==
/* eslint-env jquery */
// Product Opener (Open Food Facts web app) uses:
// * jQuery 2.1.4: view-source:https://static.openfoodfacts.org/js/dist/jquery.js
// http://code.jquery.com/jquery-2.1.4.min.js
// * jQuery-UI 1.12.1: view-source:https://static.openfoodfacts.org/js/dist/jquery-ui.js
// http://code.jquery.com/ui/1.12.1/jquery-ui.min.js
// * Tagify 3.x: view-source:https://static.openfoodfacts.org/js/dist/tagify.min.js
// https://github.com/yairEO/tagify
// * Foundation 5 CSS Framework: https://sudheerdev.github.io/Foundation5CheatSheet/
// https://get.foundation/sites/docs-v5/
// See also: https://github.com/openfoodfacts/openfoodfacts-server/pull/2987
(function() {
'use strict';
const log_to_console = true; // true if you want to log activity
var version_user;
var version_date;
var proPlatform = false; // TODO: to be included in isPageType()
const pageType = isPageType(); // test page type
const corsProxyURL = "";
log("2024-12-20T11:15 - mode: " + pageType);
// Disable extension if the page is an API result; https://world.openfoodfacts.org/api/v0/product/3222471092705.json
if (pageType === "api") {
// TODO: allow keyboard shortcut to get back to product view?
var _code = window.location.href.match(/\/product\/(.*)\.json$/)[1];
var viewURL = document.location.protocol + "//" + document.location.host + "/product/" + _code;
log('press v to get back to product view: ' + viewURL);
$(document).on('keydown', function(event) {
if (event.key === 'v') {
window.open(viewURL, "_blank"); // open a new window
return;
}
});
return;
}
// Setup options
var zoomOption = false; // "true" allows zooming images with mouse wheel, while "false" disallow it
var listByRowsOption = false; // "true" automatically lists products by rows, while "false" not
//Hidden form for ingredients analysis used both in list mode and single products.
//Ingredients analysis takes its input from 'ingredients_text' for single products or from textarea with the id=i[product_id] when in a list
//but the language pages have the text in 'ingredients_text_xx'
//so we have to copy the text (in Copytext) before submitting the form
var analyse_form = document.createElement("form");
analyse_form.setAttribute("method", "get");
analyse_form.setAttribute("enctype", "multipart/form-data");
var txt = document.createElement('textarea');
txt.setAttribute('id', 'ingredients_text');
txt.setAttribute('name', 'ingredients_text');
txt.setAttribute('style', 'display:none;');
var sub = document.createElement('input');
sub.setAttribute('type', 'hidden');
sub.setAttribute('name', 'action');
sub.setAttribute('value', 'process');
analyse_form.appendChild(txt);
analyse_form.appendChild(sub);
document.body.appendChild(analyse_form);
// Open Food Facts power user
// * Main code by Charles Nepote (@CharlesNepote)
// * Barcode code by @harragastudios
// Firefox: add it via Greasemonkey or Tampermonkey extension: https://addons.mozilla.org/en-US/firefox/addon/greasemonkey/
// Chrome (not tested): add it with Tampermonkey: https://chrome.google.com/webstore/detail/tampermonkey/dhdgffkkebhmkfjojejmpbldmpobfkfo
// Main features
// * DESIGN (custom CSS with small improvements)
// * barcode highlighted with a sweet color
// * better distinguished sections
// * fields highlighted, current field highlighted
// * less margins for some elements
// * Smaller fixed validation bar
// * UI
// * help screen called with button [?] or keyboard shortcut (?) or (h)
// * zoom every images with mouse wheel; see http://www.jacklmoore.com/zoom/
// * show/hide barcode; keyboard shortcut (shift+B)
// * see https://github.com/openfoodfacts/openfoodfacts-server/issues/1728
// * Edit mode:
// * show hide help comments for each field (see help screen)
// * Firefox: Nutrition facts picture takes all the place available
// * Add "History" anchor in the nav bar
// * Ingredient lists: external link for each ingredient (appear when hovering rows)
// * keyboard shortcut to API product page (a)
// * keyboard shortcut to get back to view mode (v)
// * keyboard shortcut to enter edit mode: (e) in the current window, (E) in a new window
// * see Add "Edit" keyboard shortcut for logged users: https://github.com/openfoodfacts/openfoodfacts-server/issues/1852
// * keyboard shortcuts to help modify data without a mouse: P(roduct), Q(uality), B(rands), C(ategories), L(abels), I(ngredients), (e)N(ergy), F(ibers)
// * Quick links in the sidebar: page translation, category translation, Recent Changes, Hunger Game, categorization opportunities...
// * dedicated to list screens (facets, search results...):
// * "n" keyboard shortcut to reload the list without cache (&nocache=1 parameter), if it's not already the case
// * [alpha] keyboard shortcut to list products as a table containing ingredients and options to edit or delete ingredients
// (shift+L) ["L" for "list"]
// The LanguageTool Firefox extension is recommanded because it detects automatically the language of each field.
// https://addons.mozilla.org/en-US/firefox/addon/languagetool/
// * Inline edit of ingredients in list mode
// * Option to set ingredient textareas to fixed width font, to make it easier to see bad OCR,
// such as when it confuses "m" and "rn" (e.g. corn), lowercase l/L and uppercase i/I, etc.
//
// * FEATURES
// * [beta] transfer data from a language to another (use *very* carefully); keyboard shortcut (shift+T)
// * [beta] easily delete ingredients, by entering the list by rows mode (shift+L)
// * [alpha] allow flagging products for later review (shift+S)
// * https://github.com/openfoodfacts/openfoodfacts-server/issues/1408
// * Ask [email protected]
// * launch Google OCR if "Edit ingredients" is clicked in view mode
// * "[Products without brand that might be from this brand]" link, following product code
// * Links beside barcode number: Google and DuckDuckGo link for product barcode + Open Beauty Facts + Open Pet Food Facts + pro.openfoodfacts.dev
// * Product view: button to open an ingredient analysis popup
// * help screen: add "Similarly named products without a category" link
// * help screen: add "Product code search on Google" link
// * help screen: add links to Google/Yandex Reverse Image search (thanks Tacite for suggestion)
// * Edit mode:
// * Check serving size field
// * Add the ⇅ icon allowing to reverse kJ and kcals
// * Colorize icon ⇅ when kJ/kcal values are not coherent (ratio is displayed inside ⇅ tooltip)
// * Add fiew informations on the confirmation page:
// * Products issues:
// * To be completed (from "states_tags")
// * Quality errors tags (green message if none)
// * Quality warings tags (green message if none)
// * and a link to product edit
// * Going further
// * "XX products without brand that might be from this brand" link
// * Add a field to filter Recent Changes results (filter as you type)
// * DEPLOYMENT
// * Tampermonkey suggests to update the extension when one click to updateURL:
// https://gist.github.com/CharlesNepote/f6c675dce53830757854141c7ba769fc/raw/OpenFoodFactsPowerUser.user.js
// TODO
// * FEATURES
// * identify problematic fields based on quality feedbacks; https://world.openfoodfacts.org/api/v0/product/7502271153193.json
// * see "data_quality_errors_tags" array
// * On the fly quality checks in the product edit form (javascript): https://github.com/openfoodfacts/openfoodfacts-server/issues/1905
// * Add automatic detection of nutriments, see: https://robotoff.openfoodfacts.org/api/v1/predict/nutrient?ocr_url=https://static.openfoodfacts.org/images/products/841/037/511/0228/nutrition_pt.12.json
// * Easily delete ingredients when too buggy
// * Add few informations on the confirmation page:
// * Nutri-Score and NOVA if just calculated?
// * unknown ingredients
// * Product of a brand from a particular country, that are not present in this country (see @teolemon)
// * Keyboard shortcut to get back to view mode (v) => target=_self + prevent leaving page if changes are not saved
// * Mass edit (?) -- see https://github.com/roiKosmic/OFFMassUpdate/blob/master/js/content_script.js
// * Mass edit with regexp (with preview)
// * Mass deletion of a tag?
// * Mini Hunger Game (dedicated to categories?)
// * Revert from an old version
// * UI & DESIGN
// * Picture dates
// => in the list: change background color depending on the year?
// => in the product page: highlight in red when date is old?
// * Highlight products with old pictures (?)
// * Add a fixed menu button as in mass-updater
// * Highlight empty fields?
// * Select high resolution images on demand
// * Show special prompt when the nutrition photo has changed, but not the nutrition data itself: https://github.com/openfoodfacts/openfoodfacts-server/issues/1910
// * Show a special prompt when the ingredient list photo has changed, but not the ingredient list itself: https://github.com/openfoodfacts/openfoodfacts-server/issues/1909
// * BUGS
// * deal with products without official barcodes: https://fr.openfoodfacts.org/produit/2000050217197/mondose-exquisite-belgian-chocolates
// * wheelzoom transform image links to: data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaH..................
// * Some access keys dont seem to work, due to javascript library
// * See Support hitting the TAB key only once to quickly move to the next text field and then make entering text possible:
// https://github.com/openfoodfacts/openfoodfacts-server/issues/1245
// * focus on .tagsinput fields is not highlighted
// css
// See https://stackoverflow.com/questions/4376431/javascript-heredoc
var css = `
/*
* OFF web app already load jquery-ui.css but it doesn't work properly with "dialog" function.
* We add the CSS this way so that the embedded, relatively linked images load correctly.
* (Use //ajax... so that https or http is selected as appropriate to avoid "mixed content".)
*/
.ui-dialog {
position: absolute;
top: 0;
left: 0;
padding: .2em;
outline: 0;
}
.ui-dialog .ui-dialog-titlebar {
padding: .4em 1em;
position: relative;
}
.ui-dialog .ui-dialog-title {
float: left;
margin: .1em 0;
white-space: nowrap;
width: 90%;
overflow: hidden;
text-overflow: ellipsis;
}
.ui-dialog .ui-dialog-titlebar-close {
position: absolute;
right: .3em;
top: 50%;
width: 20px;
margin: -10px 0 0 0;
padding: 1px;
height: 20px;
}
.ui-dialog .ui-dialog-content {
position: relative;
border: 0;
padding: .5em 1em;
background: none;
overflow: auto;
}
.ui-dialog .ui-dialog-buttonpane {
text-align: left;
border-width: 1px 0 0 0;
background-image: none;
margin-top: .5em;
padding: .3em 1em .5em .4em;
}
.ui-dialog .ui-dialog-buttonpane .ui-dialog-buttonset {
float: right;
}
.ui-dialog .ui-dialog-buttonpane button {
margin: .5em .4em .5em 0;
cursor: pointer;
}
.ui-dialog .ui-resizable-n {
height: 2px;
top: 0;
}
.ui-dialog .ui-resizable-e {
width: 2px;
right: 0;
}
.ui-dialog .ui-resizable-s {
height: 2px;
bottom: 0;
}
.ui-dialog .ui-resizable-w {
width: 2px;
left: 0;
}
.ui-dialog .ui-resizable-se,
.ui-dialog .ui-resizable-sw,
.ui-dialog .ui-resizable-ne,
.ui-dialog .ui-resizable-nw {
width: 7px;
height: 7px;
}
.ui-dialog .ui-resizable-se {
right: 0;
bottom: 0;
}
.ui-dialog .ui-resizable-sw {
left: 0;
bottom: 0;
}
.ui-dialog .ui-resizable-ne {
right: 0;
top: 0;
}
.ui-dialog .ui-resizable-nw {
left: 0;
top: 0;
}
.ui-draggable .ui-dialog-titlebar {
cursor: move;
}
/** End of jquery-ui requirements **/
/* .row { width: 80% !important; margin: 0 0 !important; } */
/* Special color for barcode */
span[property="food:code"] { color: Olive; }
/* Enhancements to better distinguish sections: Product information, Ingredients and Nutriments facts */
#main_column > div > h2 { margin-top: 1.6rem !important;
margin-bottom: 0.2rem !important;
border-bottom: 1px solid lightgrey; }
/* Special background color for all input fieds */
textarea, .tagify, input[type=text] { background-color: LightYellow !important; }
input.nutriment_value { background-color: LightYellow; }
textarea:focus, .tagify__input:focus, .tagify:focus, input[type=text]:focus, input.nutriment_value:focus { background-color: lightblue !important; }
/* Small enhancements */
p { margin-bottom: 0.6rem; }
input[type=text] { margin: 1px 0; } /* reduce vertical space between fields and notes */
.note, .example { margin: 1px 0; }
label { margin-top: 10px; }
.data_table { margin-top: 7px; }
td { line-height: 1rem; }
input[type="checkbox"], input[type="radio"] { margin: 0; }
.data_table td, .data_table th { padding: .1rem .1rem .1rem .4rem; }
/*.data_table label { display: table-cell; }*/
#image_box_front { margin-bottom: 1rem !important; }
.unselectbuttondiv_front_fr {
text-align: center !important;
}
.unselectbutton_front_fr {
margin:0 0 0 0 !important;
}
/* Buttons Rotate left - Rotate right: 0.25rem vs 1.25 */
.cropbox > div > a { margin: 0 0 0.25rem; }
/* checkbox: Normalize colors and Photo on white background: try to remove the background */
.cropbox > label { margin-top: 3px; }
.cropbox > input { margin: 0 0 0.5rem 0; }
/* Reset margins of nutriments form */
input.nutriment_value { margin: 0 0 0 0; }
input.show_comparison {
margin: 0 0 0.2rem 0 !important;
}
/* --------------- Let panels use less space ----------------------- */
/* On the legacy website, in the "changes saved" page, the second panel is not seen without scrolling. */
.card-section { padding-top: 12px; padding-bottom: 10px; }
.panel_card { margin-bottom: 0.5rem !important }
.panel_title_card { margin-top: 0px; }
.panel_content_card { margin-top: 0px; }
.panel_title, .panel_content { padding-top: 0px !important; padding-bottom: 0.2rem !important; }
/* ---------------- Power User Script UI --------------------------- */
/* ------------------ Help box ------------------------------------- */
.pus_menu {
font-size: 0.9rem;
}
/* checkboxes in popup */
.pus_menu label {
margin-top: 0;
}
.pus_menu input[type=checkbox] {
margin-bottom: 0;
}
.ui-widget-content a {
color: #00f;
}
/* ------------------ Fixed menu buttons --------------------------- */
#pwe_help {
position:fixed;
left:0%;
top:3rem;
padding:0 0.7rem 0 0.7rem;
font-size:1.5rem;
background-color:red;
border-radius: 0 10px 10px 0;
z-index: 200;
}
#ing_analysis {
position:fixed;
left:0%;
top:5rem;
padding:0 0.7rem 0 0.7rem;
font-size:1.1rem;
width: 7rem;
background-color:red;
border-radius: 0 10px 10px 0;
z-index: 200;
}
#pwe_hide_text_fields {
position:fixed;
left:0%;
top:8rem;
padding:0 0.7rem 0 0.7rem;
font-size:1.1rem;
background-color:red;
border-radius: 0 10px 10px 0;
z-index: 200;
}
/* --------------- Hunger games logo search button --------------- */
.list_hunger_games_logo_search {
position: absolute;
top: 0;
right: 2.5em;
padding: 0 0.5em;
border-radius: 0.3em;
}
.list_hunger_games_logo_search:hover, .list_rotate_image_90:hover, .list_rotate_image_180:hover, .list_rotate_image_270:hover {
background-color: #aaf;
}
/* --------------- Rotate list product buttons --------------- */
.list_rotate_image_90 {
position: absolute;
top: 0;
right: 5em;
padding: 0 0.5em;
border-radius: 0.3em;
}
.list_rotate_image_180 {
position: absolute;
top: 0;
right: 7.5em;
padding: 0 0.5em;
border-radius: 0.3em;
}
.list_rotate_image_270 {
position: absolute;
top: 0;
right: 10em;
padding: 0 0.5em;
border-radius: 0.3em;
}
/* ---------------- /Power User Script UI -------------------------- */
/* ---------------- Height of input fields ------------------------- */
.tagify__input { margin: 4 px; } /* instead of 5px */
/* ---------------- Nutrition facts ------------------------- */
label[for="serving_size"] {
float: left;
margin-right: 10px;
}
#serving_size {
width: 30%;
}
input.nutriment_value { height: 1.9rem !important; }
select.nutriment_unit {
height: 1.9rem !important;
padding: .1rem .3rem !important;
}
#nutriment_fruits-vegetables-nuts-estimate_tr :first-child { max-inline-size: 25em; }
/* ---- Edit mode: Nutrition image as tall as Nutrition facts table ---- */
/* Works with Firefox, Chrome at least */
#nutrition_image_copy {
width: -moz-available;
height: 92%;
}
#nutrition_image_copy > img {
/* Vertical image: https://world.openfoodfacts.org/cgi/product.pl?type=edit&code=8002063211913 */
/* Horizontal image: https://world.openfoodfacts.org/cgi/product.pl?type=edit&code=0490711801117 */
height: 100%;/**/
width: 100%;/**/
/* https://hacks.mozilla.org/2015/02/exploring-object-fit/ */
object-fit:contain;
object-position: left;
}
/* ---- /Edit mode: Nutrition image as tall as Nutrition facts table ---- */
/* ------------------- Smaller fixed validation bar ---------------------- */
.bottom-validation { padding-top: .3rem; }
.bottom-validation > div > div { height: 2rem; }
/* ----------------- Varia ------------------------- */
.productLink::before {
content: " — ";
}
.hidden {
display: none;
}
.ingredient_td:hover .hidden {
display: inline;
}
/* ingredients box alternative font */
textarea.monospace {
font-family: Consolas, Lucida Console, monospace;
}
.ul[id^='products_'].search_results a.with_barcode { margin-top: 0; padding-top: 0; }
`;
// apply custom CSS
var s = document.createElement('style');
s.type = 'text/css';
s.innerHTML = css;
document.documentElement.appendChild(s);
// ***
// * Image zoom
// *
// Test image zoom with mouse wheel
// Don't forget to add: // @require https://cdn.jsdelivr.net/npm/wheelzoom
if(zoomOption) { wheelzoom(document.querySelectorAll('img')); } // doesn't work in edit mode
// Test image zoom with jquery-zoom
// Don't forget to add: // @require https://cdn.jsdelivr.net/npm/jquery-zoom
// $('img').zoom({ on:'grab' }); // add zoom // doesn't work
// $('img').trigger('zoom.destroy'); // remove zoom
// ***
// * Every modes, except "list"
// *
// Build variables
if(pageType !== "list") {
log("This is not a list.");
var code;
code = getURLParam("code")||$('span[property="food:code"]').html();
if (code === undefined) {
// product view needs more effort to get the product code.
// Using e.g. <link rel="canonical" href="https://uk.openfoodfacts.org/product/00994835/black-forest-christmas-pudding-marks-spencer">
// as it doesn't contain the code if the given code is not a valid entry.
var code2 = $('link[rel="canonical"]').attr("href").match('product/\([0-9]+\)');
if (code2 && code2[1]) {
code = code2[1];
//log("code2: "+ code2);
}
}
// Horrible hack to prevent issue introduced by https://github.com/openfoodfacts/openfoodfacts-server/pull/8223
if (pageType === "saved-product page") {
//log(document.getElementById('changes_saved').getElementsByClassName("warning")[0].href.match(/code=(.*)/)[1]);
code = document.getElementById('changes_saved').getElementsByClassName("warning")[0].href.match(/code=(.*)/)[1];
}
log("code: "+ code);
// build API product link; example: https://world.openfoodfacts.org/api/v0/product/737628064502.json
var apiProductURL = "/api/v0/product/" + code + ".json";
log("API: " + apiProductURL);
// build edit url
var editURL = document.location.protocol + "//" + document.location.host + "/cgi/product.pl?type=edit&code=" + code;
}
// ***
// * Every mode, except "api"
// *
// Add quick links in the sidebar: page translation, category translation, Recent Changes...
if (pageType !== "api") {
var pageLanguage = $("html").attr('lang'); // Get page language
log("Page language: " + pageLanguage);
if(pageLanguage === "en") { // Delete page language if "en" because we can't make the difference bewteen "en-GB" and "en-US"
pageLanguage = "";
}
// Non contextual links
// TODO: no more displayed since OFF redesign in 2022-10; put it elsewhere
$("#match").before(
`
<section class="row" id="match"><div class="large-12 column"><div class="card"><div class="card-section">
<p><a class="button tiny round secondary label" href="https://crowdin.com/project/openfoodfacts/${pageLanguage}">
Help page translation
</a>
<a class="button tiny round secondary label" href="/categories?translate=1">
Help category translations</a>
<a class="button tiny round secondary label" href="/cgi/recent_changes.pl?&page=1&page_size=100">
Recent Changes
</a>
<p id="hungerGameLink"><a class="button tiny round secondary label" href="https://hunger.openfoodfacts.org">
Hunger Game
</a></p>
</p>
</div></div></div></section>`
);
// Hunger Game contextual link
// TODO: display a number of opportunities.
/*var hungerGameDeepLink =
($("div[itemtype='https://schema.org/Brand']").length) ? "questions?type=brand&value_tag=" + normalizeTagName($("h1[itemprop='name']").text())
: (/label\/(.*)$/.test(document.URL) === true) ? "questions?type=label&value_tag=en:" + normalizeTagName(RegExp.$1)
: (($("div[itemtype='https://schema.org/Thing']").length) ? "questions?type=category&value_tag=en:" + normalizeTagName($("h1[itemprop='name']").text())
: "");
$("h1[itemprop='name']").append(
(hungerGameDeepLink ?
' <sup><a class="button tiny round secondary label" href="https://hunger.openfoodfacts.org/' + hungerGameDeepLink + '">' +
'Hunger Game</a></sup>' : "")
);*/
}
// Add external link to ingredient so it opens in a new window
if (pageType === "ingredients"){
$('#tagstable').find('tr').each(function(){
var tds = $(this).find('td');
var urlToIngredient;
$(this).children().addClass("ingredient_td");
if(tds.length != 0) {
urlToIngredient = tds.children().attr("href"); // /category/gouda/ingredient/dairy
}
$(this).find('td').children().after(' <a href="'+ urlToIngredient +'" target="_blank"><span class="hidden"> ↗ ↗ ↗ </span></a>');
});
}
// ***
// * Every mode, except "api", "list", "search-form"
// *
if (pageType === "edit" ||
pageType === "product view"||
pageType === "saved-product page") {
// Add product public link if we are on the pro platform
if(proPlatform) {
var publicURL = document.URL.replace(/\.pro\./gi, ".");
log("publicURL: "+publicURL);
$(".sidebar p:first").after('<p>> <a href="'+publicURL+'">Product public URL</a></p>');
}
// Add informations right after the barcode
if ($("#barcode_paragraph") && code !== undefined) {
// Icon for toggling graphical barcode
$("#barcode_paragraph").append(' <span id="toggleBarcodeLink" class="productLink" title="Show/hide graphical barcode">📲</span>');
$("#toggleBarcodeLink").on("click", function(){
toggleSingleBarcode(code);
});
// Find products from the same brand
var sameBrandProducts = code.replace(/[0-9][0-9][0-9][0-9]$/gi, "xxxx");
var sameBrandProductsURL = document.location.protocol +
"//" + document.location.host +
'/state/brands-to-be-completed/code/' +
sameBrandProducts;
$("#barcode_paragraph")
.append(' <span id="sameBrandProductLink" class="productLink">[<a href="' +
sameBrandProductsURL +
'" title="Products without brand that might be from this brand">'+
'Non-branded ϵ same brand?</a>]</span>');
// Google Link
var googleLink = 'https://www.google.com/search?q=' + code;
$("#barcode_paragraph")
.append(' <span id="googleLink" class="productLink">[<a href="' + googleLink +
'">G</a>]');
// DuckDuckGo Link
var duckLink = 'https://duckduckgo.com/?q=' + code;
$("#barcode_paragraph")
.append(' <span id="duckLink" class="productLink">[<a href="' + duckLink +
'">DDG</a>]');
// Link to Open Beauty Facts
var obfLink = 'https://world.openbeautyfacts.org/product/' + code;
productExists(corsProxyURL+obfLink,"#obfLinkStatus","","");
$("#barcode_paragraph")
.append(' <span id="obfLink" class="productLink">[<a href="' + obfLink +
'">obf.org</a>] (<span id="obfLinkStatus"></span>)');
// Link to Open Pet Food Facts
var opffLink = 'https://world.openpetfoodfacts.org/product/' + code;
productExists(corsProxyURL+opffLink,"#opffLinkStatus","","");
$("#barcode_paragraph")
.append(' <span id="opffLink" class="productLink">[<a href="' + opffLink +
'">opff.org</a>] (<span id="opffLinkStatus"></span>)');
// Link to .pro.openfoodfacts.dev
//var proDevLink = 'https://off:[email protected]/product/' + code;
var proDevLink = 'https://world.pro.openfoodfacts.dev/product/' + code;
productExists(corsProxyURL+proDevLink,"#proDevLinkStatus","off","off");
$("#barcode_paragraph")
.append(' <span id="devProPlatform" class="productLink">[<a href="' + proDevLink +
'">.pro.off.dev</a>] (<span id="proDevLinkStatus"></span>)');
// https://fr.openfoodfacts.org/etat/marques-a-completer/code/506036745xxxx&json=1
var sameBrandProductsJSON = sameBrandProductsURL + "&json=1";
log("Get JSON from: " + sameBrandProductsJSON);
$.getJSON(sameBrandProductsJSON, function(data) {
var nbOfSameBrandProducts = data.count;
log("nbOfSameBrandProducts: " + nbOfSameBrandProducts);
if($("#going-further")) $("#going-further").append('<li><span><a href="' +
sameBrandProductsURL +
'">' + nbOfSameBrandProducts +
' products without brand that might be from this brand</a></span>' +
'</li>');
if($("#barcode_paragraph")) $("#sameBrandProductLink").html(
'[<a href="' +
sameBrandProductsURL +
'" title="Products without brand that might be from this brand">'+
nbOfSameBrandProducts + ' non-branded ϵ same brand</a>]');
});
}
// Compute Google and Yandex reverse image search
var gReverseImageURL = "https://images.google.com/searchbyimage?image_url=";
var yReverseImageURL = "https://yandex.com/images/search?source=collections&url=";
var frontImgURL = $('meta[name="twitter:image"]').attr("content");
var ingredientsImgURL = ($('#image_box_ingredients a img').attr('srcset') ? $('#image_box_ingredients a img').attr('srcset').match(/(.*) (.*)/)[1] : "");
var nutritionImgURL = ($('#image_box_nutrition a img').attr('srcset') ? $('#image_box_nutrition a img').attr('srcset').match(/(.*) (.*)/)[1] : "");
// Help box based on page type: api|saved-product page|edit|list|search form|product view
var help = "<ul class='pus_menu'>" +
"<li>(?) or (h): this present help</li>" +
"<hr id='nav_keys'>" +
((pageType === "edit") ?
'<li><input class="pus-checkbox" type="checkbox" id="pus-helpers" checked><label for="pus-helpers">Field helpers</label></li>' +
'<li><input class="pus-checkbox" type="checkbox" id="pus-dist-free"><label for="pus-dist-free">Distraction free mode</label></li>':
"") +
((pageType === "edit" || pageType === "list") ?
'<li><input class="pus-checkbox" type="checkbox" id="pus-ingredients-font"><label for="pus-ingredients-font">Ingredients fixed-width font</label></li>':
"") +
((pageType === "product view" || pageType === "edit") ?
"<li>(Shift+b): show/hide <strong>barcode</strong></li>" +
"<li>(Alt+shift+key): direct access to (P)roduct name, (Q)uality, (B)rands, (C)ategories, (L)abels, (I)ngredients, e(N)ergy, (F)ibers</li>" +
"<hr>":
"") +
((pageType === "product view" || pageType === "api") ?
"<li>(e): edit current product in current window</li>" +
"<li>(E): edit product in a new window</li>":
"") +
((pageType === "product view" || pageType === "edit") ?
"<li id='api_product_page'>(a): <a href='" + apiProductURL + "'>API product page</a> (json)</li>":
"") +
"<li><a href='https://google.com/search?&q="+ code + "'>Product code search on Google</a></li>" +
"<li>Google Reverse Image search"+
(pageType !== "product view" ? " (view mode only)</li>" :
": " +
(frontImgURL ? "<a href='"+ gReverseImageURL + frontImgURL + "'>front</a>" : "")+
(ingredientsImgURL ? ", <a href='"+ gReverseImageURL + ingredientsImgURL + "'>ingredients</a>" : "") +
(nutritionImgURL ? ", <a href='"+ gReverseImageURL + nutritionImgURL + "'>nutrition</a>" : "")) +
"</li>" +
"<li>Yandex Reverse Image search"+
(pageType !== "product view" ? " (view mode only)</li>" :
": " +
(frontImgURL ? "<a href='"+ yReverseImageURL + frontImgURL + "'>front</a>" : "")+
(ingredientsImgURL ? ", <a href='"+ yReverseImageURL + ingredientsImgURL + "'>ingredients</a>" : "") +
(nutritionImgURL ? ", <a href='"+ yReverseImageURL + nutritionImgURL + "'>nutrition</a>" : "")) +
"</li>" +
"<li>(shift+T): <strong>transfer</strong> a product from a language to another, in edition mode only (use <strong>very</strong> carefully)</li>" +
"<li>(shift+S): <strong>flag</strong> product for later review (ask <a href='mailto:[email protected]'>[email protected]</a> for log access)</li>" +
"<hr>" +
(pageType === "product view" ?
"<li><a href='"+ sameBrandProductsURL + "'>" + sameBrandProducts + " products without a brand</a></li>" +
"<li><a href=\""+ getSimilarlyNamedProductsWithoutCategorySearchURL() + "\">Similarly named products without a category</a></li>":
"<li title='(view mode only)'>" + sameBrandProducts + " products without a brand</li>" +
"<li title='(view mode only)'>Similarly named products without a category</li>") +
"</ul>";
// Help icon fixed
$('body').append('<button id="pwe_help">?</button>');
//$('#select_country_li').insertAfter('<li id="pwe_help" style="font-size:2rem;background-color:red;">?</li>'); // issue: menu desappear when scrolling
// User help dialog
$("#pwe_help").click(function(){
togglePowerUserInfo(help);
toggleHelpers();
toggleIngredientsMonospace();
toggleDFMode();
});
if (pageType === "edit"){
//Ingredients analysis check - opens in new window
$('body').append('<button id="ing_analysis">Ingredients analysis</button>');
$("#ing_analysis").click(function(){
//log("analyse");
Copydata();
submitToPopup(analyse_form);
});
$('body').append('<button id="pwe_hide_text_fields">Hide fields</button>');
$("#pwe_hide_text_fields").click(function(){
toggleHideTextFieldsPopUp();
});
loadHideTextFieldsFromStorage();
}
if (pageType === "edit" || pageType === "product view") {
var history = document.getElementById("history");
if (history !== null) {
// add search field after "Changes history"
const historyInput = document.createElement("input");
history.after(historyInput);
var initalList = true;
// search term when the user fill a value
historyInput.addEventListener('input', function (input) {
const value = input.target.value;
let list = document.querySelector('#history_list').querySelectorAll('li');
// if search term is less than 2 characters, reset style and return
if (value.length < 2) {
if (initalList === false) list.forEach((x) => { x.style.color = '' });
initalList = true;
return;
}
initalList = false;
let re = new RegExp(value, 'i');
// highlight line in blue or grey weither it contains the searched term or not
list.forEach((x) => { x.style.color = (re.test(x.textContent)) ? 'blue' : 'grey' });
});
}
}
// Keyboard actions
$(document).on('keydown', function(event) {
log(event);
// If the key is not pressed inside a input field (ex. search product field)
if (
!$(event.target).is(':input')
&& !$(event.target).is('span.tagify__input')
&& !$(event.target).is('span.tagify__tag-text')
) {
// (Shift + B): toggle show/hide barcode
if (event.key === 'B') {
toggleSingleBarcode(code);
return;
}
// (a): api page in a new window
if ((pageType === "product view" || pageType == "edit") && event.key === 'a') {
window.open(apiProductURL, "_blank"); // open in an other window
return;
}
// (e): edit current product in current window
if ((pageType === "product view" || pageType === "saved-product page") && event.key === 'e') {
window.open(editURL, "_self"); // edit in current window
return;
}
// (E): edit current product in a new window
if (pageType === "product view" && event.key === 'E') {
window.open(editURL); // open a new window
return;
}
// (v): if in "edit" mode, switch to view mode
if (pageType !== "product view" && event.key === 'v') {
var viewURL = document.location.protocol + "//" + document.location.host + "/product/" + code;
window.open(viewURL, "_blank"); // open a new window
return;
}
// (I): ingredients
if (pageType === "edit" && event.key === 'i') {
toggleIngredientsMode();
return;
}
// (?): open help box
if (event.key === '?' || event.key === 'h') {
togglePowerUserInfo(help);
toggleHelpers();
toggleIngredientsMonospace();
toggleDFMode();
return;
}
// (S): Flag a product
// See "Add a flag button/API to put up a product for review when you're in a hurry": https://github.com/openfoodfacts/openfoodfacts-server/issues/1408
if (event.key === 'S') {
flagThisRevision();
return;
}
// (T): transfer a product from a language to another
if (event.key === 'T') {
if (pageType !== "edit") {
showPowerUserInfo('<p>Transfer only work in "edit" mode.</p>');
return;
}
// products to test: https://es-en.openfoodfacts.org/language/en:1/language/french
// https://europe-west1-openfoodfacts-1148.cloudfunctions.net/openfoodfacts-language-change?ol=fr&fl=es&code=7622210829580
// TODO: use detectLanguages() function
var array_langs = $("#sorted_langs").val().split(",");
var options_langs;
var transferServiceURL = "https://europe-west1-openfoodfacts-1148.cloudfunctions.net/openfoodfacts-language-change";
$.each(array_langs,function(i){
options_langs += '<option value="'+(array_langs[i])+'">'+(array_langs[i])+'</option>';
});
log("options_langs: "+options_langs);
var transfer = "<div id=\"dialog\" title=\"Dialog Form\">" +
'<form action="' + transferServiceURL + '" method="get">' +
"<label>Source language:</label>" +
"<select id=\"transfer_ol\" name=\"ol\">" +
options_langs +
"</select>" +
"<label>Target language:</label>" +
"<input id=\"transfer_fl\" name=\"fl\" type=\"text\">" +
"<input type=\"hidden\" name=\"code\" value=\""+ code + "\">" +
"<input id=\"transfer_submit\" type=\"button\" value=\"=> Transfer\">" +
"</form>" +
'<div id="transfer_result"></div>' +
"</div>";
showPowerUserInfo(transfer); // open a new window
$("#transfer_submit").click(function(){
var url = transferServiceURL +
"?ol=" + $("#transfer_ol").val() +
"&fl=" + $("#transfer_fl").val() +
"&code=" + code;
log("transfert url: "+url);
$.ajax({url: url, success: function(result){
$("#transfer_result").html(result);
}});
$("#transfer_result").html("<p>Page is going to reload in 5s...</p>");
setTimeout(function() {
location.reload(); // reload the page
}, 8000);
});
return;
}
}
});
}
// ***
// * View mode
// *
// Test if we are in a product view.
if (pageType === "product view") {
// Showing it directly on the product page, for emerging categories.
// https://world.openfoodfacts.org/cgi/search.pl?action=process&sort_by=unique_scans_n&page_size=20&action=display&tagtype_0=states&tag_contains_0=contains&tag_0=categories%20to%20be%20completed&search_terms=lasagne
var productName = $('h1[property="food:name"]').html().match(/(.*?)(( - .*)|$)/)[1]; // h1[property="food:name"] => Cerneaux noix de pécan - Vahiné - 50 g ℮
log("productName: " + productName);
var SearchUncategorizedProductsOpportunitiesDeepLink = encodeURI(productName);
$("#hungerGameLink").after(
((SearchUncategorizedProductsOpportunitiesDeepLink) ? '<p>'+
'> <a title="Categorization opportunities using Mass Edit"'+
'href="/cgi/search.pl?action=process&sort_by=unique_scans_n&page_size=20&action=display&tagtype_0=states&tag_contains_0=contains&tag_0=categories%20to%20be%20completed&search_terms=' +
SearchUncategorizedProductsOpportunitiesDeepLink + '">' +
'Categorization opportunities</a>' +
'</p>' : ""));
// For each different brand, if any, add a deep link to Hunger Game
// TODO: make this a parameter which can be saved from a session to another; something like:
// readParameter(isLinkToHungerGameForEachBrand)
let isLinkToHungerGameForEachBrand = true;
if(isLinkToHungerGameForEachBrand) {
$('[itemprop="brand"]').each(function() {
const brand = normalizeTagName($(this).text());
$(this).after(' <sup>[<a href="https://hunger.openfoodfacts.org/questions?value_tag=' + brand + '&type=brand" title="Hunger Game">Hunger Game</a>]</sup>');
});
}
// If ingredients are already entered, show results of the OCR
if($("#editingredients")[0]) {