# All files / composer/stores ComposerStore.js

25.4% Statements 240/945
19.5% Branches 109/559
18.02% Functions 31/172
26.35% Lines 224/850

    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
    1001
    1002
    1003
    1004
    1005
    1006
    1007
    1008
    1009
    1010
    1011
    1012
    1013
    1014
    1015
    1016
    1017
    1018
    1019
    1020
    1021
    1022
    1023
    1024
    1025
    1026
    1027
    1028
    1029
    1030
    1031
    1032
    1033
    1034
    1035
    1036
    1037
    1038
    1039
    1040
    1041
    1042
    1043
    1044
    1045
    1046
    1047
    1048
    1049
    1050
    1051
    1052
    1053
    1054
    1055
    1056
    1057
    1058
    1059
    1060
    1061
    1062
    1063
    1064
    1065
    1066
    1067
    1068
    1069
    1070
    1071
    1072
    1073
    1074
    1075
    1076
    1077
    1078
    1079
    1080
    1081
    1082
    1083
    1084
    1085
    1086
    1087
    1088
    1089
    1090
    1091
    1092
    1093
    1094
    1095
    1096
    1097
    1098
    1099
    1100
    1101
    1102
    1103
    1104
    1105
    1106
    1107
    1108
    1109
    1110
    1111
    1112
    1113
    1114
    1115
    1116
    1117
    1118
    1119
    1120
    1121
    1122
    1123
    1124
    1125
    1126
    1127
    1128
    1129
    1130
    1131
    1132
    1133
    1134
    1135
    1136
    1137
    1138
    1139
    1140
    1141
    1142
    1143
    1144
    1145
    1146
    1147
    1148
    1149
    1150
    1151
    1152
    1153
    1154
    1155
    1156
    1157
    1158
    1159
    1160
    1161
    1162
    1163
    1164
    1165
    1166
    1167
    1168
    1169
    1170
    1171
    1172
    1173
    1174
    1175
    1176
    1177
    1178
    1179
    1180
    1181
    1182
    1183
    1184
    1185
    1186
    1187
    1188
    1189
    1190
    1191
    1192
    1193
    1194
    1195
    1196
    1197
    1198
    1199
    1200
    1201
    1202
    1203
    1204
    1205
    1206
    1207
    1208
    1209
    1210
    1211
    1212
    1213
    1214
    1215
    1216
    1217
    1218
    1219
    1220
    1221
    1222
    1223
    1224
    1225
    1226
    1227
    1228
    1229
    1230
    1231
    1232
    1233
    1234
    1235
    1236
    1237
    1238
    1239
    1240
    1241
    1242
    1243
    1244
    1245
    1246
    1247
    1248
    1249
    1250
    1251
    1252
    1253
    1254
    1255
    1256
    1257
    1258
    1259
    1260
    1261
    1262
    1263
    1264
    1265
    1266
    1267
    1268
    1269
    1270
    1271
    1272
    1273
    1274
    1275
    1276
    1277
    1278
    1279
    1280
    1281
    1282
    1283
    1284
    1285
    1286
    1287
    1288
    1289
    1290
    1291
    1292
    1293
    1294
    1295
    1296
    1297
    1298
    1299
    1300
    1301
    1302
    1303
    1304
    1305
    1306
    1307
    1308
    1309
    1310
    1311
    1312
    1313
    1314
    1315
    1316
    1317
    1318
    1319
    1320
    1321
    1322
    1323
    1324
    1325
    1326
    1327
    1328
    1329
    1330
    1331
    1332
    1333
    1334
    1335
    1336
    1337
    1338
    1339
    1340
    1341
    1342
    1343
    1344
    1345
    1346
    1347
    1348
    1349
    1350
    1351
    1352
    1353
    1354
    1355
    1356
    1357
    1358
    1359
    1360
    1361
    1362
    1363
    1364
    1365
    1366
    1367
    1368
    1369
    1370
    1371
    1372
    1373
    1374
    1375
    1376
    1377
    1378
    1379
    1380
    1381
    1382
    1383
    1384
    1385
    1386
    1387
    1388
    1389
    1390
    1391
    1392
    1393
    1394
    1395
    1396
    1397
    1398
    1399
    1400
    1401
    1402
    1403
    1404
    1405
    1406
    1407
    1408
    1409
    1410
    1411
    1412
    1413
    1414
    1415
    1416
    1417
    1418
    1419
    1420
    1421
    1422
    1423
    1424
    1425
    1426
    1427
    1428
    1429
    1430
    1431
    1432
    1433
    1434
    1435
    1436
    1437
    1438
    1439
    1440
    1441
    1442
    1443
    1444
    1445
    1446
    1447
    1448
    1449
    1450
    1451
    1452
    1453
    1454
    1455
    1456
    1457
    1458
    1459
    1460
    1461
    1462
    1463
    1464
    1465
    1466
    1467
    1468
    1469
    1470
    1471
    1472
    1473
    1474
    1475
    1476
    1477
    1478
    1479
    1480
    1481
    1482
    1483
    1484
    1485
    1486
    1487
    1488
    1489
    1490
    1491
    1492
    1493
    1494
    1495
    1496
    1497
    1498
    1499
    1500
    1501
    1502
    1503
    1504
    1505
    1506
    1507
    1508
    1509
    1510
    1511
    1512
    1513
    1514
    1515
    1516
    1517
    1518
    1519
    1520
    1521
    1522
    1523
    1524
    1525
    1526
    1527
    1528
    1529
    1530
    1531
    1532
    1533
    1534
    1535
    1536
    1537
    1538
    1539
    1540
    1541
    1542
    1543
    1544
    1545
    1546
    1547
    1548
    1549
    1550
    1551
    1552
    1553
    1554
    1555
    1556
    1557
    1558
    1559
    1560
    1561
    1562
    1563
    1564
    1565
    1566
    1567
    1568
    1569
    1570
    1571
    1572
    1573
    1574
    1575
    1576
    1577
    1578
    1579
    1580
    1581
    1582
    1583
    1584
    1585
    1586
    1587
    1588
    1589
    1590
    1591
    1592
    1593
    1594
    1595
    1596
    1597
    1598
    1599
    1600
    1601
    1602
    1603
    1604
    1605
    1606
    1607
    1608
    1609
    1610
    1611
    1612
    1613
    1614
    1615
    1616
    1617
    1618
    1619
    1620
    1621
    1622
    1623
    1624
    1625
    1626
    1627
    1628
    1629
    1630
    1631
    1632
    1633
    1634
    1635
    1636
    1637
    1638
    1639
    1640
    1641
    1642
    1643
    1644
    1645
    1646
    1647
    1648
    1649
    1650
    1651
    1652
    1653
    1654
    1655
    1656
    1657
    1658
    1659
    1660
    1661
    1662
    1663
    1664
    1665
    1666
    1667
    1668
    1669
    1670
    1671
    1672
    1673
    1674
    1675
    1676
    1677
    1678
    1679
    1680
    1681
    1682
    1683
    1684
    1685
    1686
    1687
    1688
    1689
    1690
    1691
    1692
    1693
    1694
    1695
    1696
    1697
    1698
    1699
    1700
    1701
    1702
    1703
    1704
    1705
    1706
    1707
    1708
    1709
    1710
    1711
    1712
    1713
    1714
    1715
    1716
    1717
    1718
    1719
    1720
    1721
    1722
    1723
    1724
    1725
    1726
    1727
    1728
    1729
    1730
    1731
    1732
    1733
    1734
    1735
    1736
    1737
    1738
    1739
    1740
    1741
    1742
    1743
    1744
    1745
    1746
    1747
    1748
    1749
    1750
    1751
    1752
    1753
    1754
    1755
    1756
    1757
    1758
    1759
    1760
    1761
    1762
    1763
    1764
    1765
    1766
    1767
    1768
    1769
    1770
    1771
    1772
    1773
    1774
    1775
    1776
    1777
    1778
    1779
    1780
    1781
    1782
    1783
    1784
    1785
    1786
    1787
    1788
    1789
    1790
    1791
    1792
    1793
    1794
    1795
    1796
    1797
    1798
    1799
    1800
    1801
    1802
    1803
    1804
    1805
    1806
    1807
    1808
    1809
    1810
    1811
    1812
    1813
    1814
    1815
    1816
    1817
    1818
    1819
    1820
    1821
    1822
    1823
    1824
    1825
    1826
    1827
    1828
    1829
    1830
    1831
    1832
    1833
    1834
    1835
    1836
    1837
    1838
    1839
    1840
    1841
    1842
    1843
    1844
    1845
    1846
    1847
    1848
    1849
    1850
    1851
    1852
    1853
    1854
    1855
    1856
    1857
    1858
    1859
    1860
    1861
    1862
    1863
    1864
    1865
    1866
    1867
    1868
    1869
    1870
    1871
    1872
    1873
    1874
    1875
    1876
    1877
    1878
    1879
    1880
    1881
    1882
    1883
    1884
    1885
    1886
    1887
    1888
    1889
    1890
    1891
    1892
    1893
    1894
    1895
    1896
    1897
    1898
    1899
    1900
    1901
    1902
    1903
    1904
    1905
    1906
    1907
    1908
    1909
    1910
    1911
    1912
    1913
    1914
    1915
    1916
    1917
    1918
    1919
    1920
    1921
    1922
    1923
    1924
    1925
    1926
    1927
    1928
    1929
    1930
    1931
    1932
    1933
    1934
    1935
    1936
    1937
    1938
    1939
    1940
    1941
    1942
    1943
    1944
    1945
    1946
    1947
    1948
    1949
    1950
    1951
    1952
    1953
    1954
    1955
    1956
    1957
    1958
    1959
    1960
    1961
    1962
    1963
    1964
    1965
    1966
    1967
    1968
    1969
    1970
    1971
    1972
    1973
    1974
    1975
    1976
    1977
    1978
    1979
    1980
    1981
    1982
    1983
    1984
    1985
    1986
    1987
    1988
    1989
    1990
    1991
    1992
    1993
    1994
    1995
    1996
    1997
    1998
    1999
    2000
    2001
    2002
    2003
    2004
    2005
    2006
    2007
    2008
    2009
    2010
    2011
    2012
    2013
    2014
    2015
    2016
    2017
    2018
    2019
    2020
    2021
    2022
    2023
    2024
    2025
    2026
    2027
    2028
    2029
    2030
    2031
    2032
    2033
    2034
    2035
    2036
    2037
    2038
    2039
    2040
    2041
    2042
    2043
    2044
    2045
    2046
    2047
    2048
    2049
    2050
    2051
    2052
    2053
    2054
    2055
    2056
    2057

    7x

    56x

    7x

    7x

    7x

    7x

    7x

    7x

    7x

    7x

    7x
    1x

    7x
    56x

    7x

    7x

    7x
    1x

    7x
    23x

    656x

    25x
    25x

    25x
    25x
    19x
    19x

    19x

    19x

    19x

    19x

    19x

    19x

    19x

    19x
    19x
    19x
    19x

    19x

    19x

    19x

    19x

    19x

    19x
    3x

    3x

    3x

    3x

    3x
    3x

    3x

    3x

    3x
    3x

    3x

    3x

    3x

    3x

    19x

    148x

    7x

    25x
    25x

    31x

    133x
    15x

    15x

    7x

    7x

    7x

    7x

    7x

    7x
    7x
    7x

    7x
    7x
    7x

    7x

    7x

    7x

    7x

    7x

    7x

    7x

    7x

    7x

    7x

    7x

    7x

    7x

    7x

    7x

    7x

    7x

    7x
    3x

    3x

    3x
    3x
    3x

    3x
    1x

    3x

    7x

    7x

    7x

    7x

    7x

    7x

    7x

    7x

    7x

    2x
    2x
    2x

    2x

    2x
    2x

    2x
    2x

    2x
    2x
    2x
    2x

    2x

    2x
    2x
    2x

    7x

    7x

    7x

    7x

    7x

    7x

    7x

    7x

    7x

    7x

    7x

    7x

    7x

    6x
    6x
    6x
    6x

    6x
    6x

    6x
    6x
    6x
    6x

    6x

    6x
    6x
    6x

    7x

    7x

    7x

    7x

    7x

    7x

    7x

    7x

    7x

    7x

    7x
    8x

    7x

    7x

    7x

    7x

    7x

    7x

    7x

    7x

    7x

    7x

    7x

    7x

    7x

    7x

    7x

    7x

    7x
    1x

    7x
    6x
    6x

    7x
    7x

    7x
    7x
    7x

    7x

    7x

    7x
    7x

    1x

    1x
    1x

    1x

    6x

    6x

    6x

    6x

    7x
    45x
    45x

    45x

    2x
    2x

    6x
    6x

    7x
    7x

    7x
    7x

    1x
    1x

    22x
    22x

    45x

    7x

     import { EventEmitter } from 'events';
    import { EditorState, ContentState } from '@bufferapp/draft-js';
    import debounce from 'lodash.debounce';
    import findLastIndexOf from 'lodash.findlastindex';
    import cloneDeep from 'lodash.clonedeep';
    import twitterText from 'twitter-text';
    import AppDispatcher from '../dispatcher';
    import {
      ActionTypes, Services, AttachmentTypes, MediaTypes, ComposerInitiators,
      AppEnvironments, NotificationScopes, ErrorTypes, InstagramAspectRatioLimits,
    } from '../AppConstants';
    import AppStore from './AppStore';
    import AppActionCreators from '../action-creators/AppActionCreators';
    import ComposerActionCreators from '../action-creators/ComposerActionCreators';
    import { addShortLink as addEditorShortLink, replaceLink as replaceEditorLink }
      from '../utils/draft-js-custom-plugins/short-link';
    import NotificationStore from './NotificationStore';
    import NotificationActionCreators from '../action-creators/NotificationActionCreators';
    import { prepopulatedMentionStrategy, addPrepopulatedMention as addEditorPrepopulatedMention }
      from '../utils/draft-js-custom-plugins/prepopulated-autocomplete-mention';
    import { prepopulatedHashtagStrategy, addPrepopulatedHashtag as addEditorPrepopulatedHashtag }
      from '../utils/draft-js-custom-plugins/prepopulated-autocomplete-hashtag';
    import { HASHTAG_REGEX } from '../utils/draft-js-custom-plugins/hashtag';
    import { addImportedMention as addEditorImportedFacebookMention }
      from '../utils/draft-js-custom-plugins/imported-facebook-mention-entities';
    import removeFacebookAutocompleteEntities
      from '../utils/draft-js-custom-plugins/autocomplete/utils/removeFacebookAutocompleteEntities';
    import { resetEditorContents } from '../utils/draft-js-custom-plugins/editor-contents-reset';
    import events from '../utils/Events';

    import ValidationSuccess from '../lib/validation/ValidationSuccess';
    import validateDraft from '../lib/validation/ValidateDraft';

    // import { registerStore, sendToMonitor } from '../utils/devtools';

    const CHANGE_EVENT = 'change';

    const getNewDraft = (service) => ({
      id: service.name, // Unique identifier; currently that's the service name
      service, // Service data structure in AppConstants.js
      editorState: EditorState.createEmpty(),
      urls: [], // Urls contained in the text
      unshortenedUrls: [], // Urls unshortened by user
      link: null, // Link Attachment; data structure in getNewLink()
      tempImage: null, // Thumbnail of media actively considered for Media Attachment
      images: [], // Media Attachment (type: image), data structure in getNewImage()
      availableImages: [],
      video: null, // Media Attachment (type: video); data structure in getNewVideo()
      attachedMediaEditingPayload: null, // Referrence to the media object being actively edited
      gif: null, // Media Attachment (type: gif); data structure in getNewGif()
      retweet: null, // Data structure in getNewRetweet()
      characterCount: service.charLimit === null ? null : 0, // Only updated for services w/ char limit
      isEnabled: false,
      filesUploadProgress: new Map(), // Map of uploaderInstance <> integer(0-100)
      enabledAttachmentType:
        (service.canHaveAttachmentType(AttachmentTypes.MEDIA) &&
         !service.canHaveAttachmentType(AttachmentTypes.LINK)) ?
           AttachmentTypes.MEDIA : null,
      sourceLink: null, // Source url and page metadata; data structure in getNewSourceLink()
      isSaved: false,
      hasSavingError: false,
      shortLinkLongLinkMap: new Map(),
      scheduledAt: null,
      isPinnedToSlot: null, // null when scheduledAt is null, true/false otherwise
      instagramFeedback: [],
      locationId: null,
      locationName: null,
    });

    const isDraftEmpty = (draft) => (
      draft.editorState.getCurrentContent().getPlainText().length === 0 &&
      (draft.enabledAttachmentType !== AttachmentTypes.LINK || draft.link === null) &&
      (draft.enabledAttachmentType !== AttachmentTypes.MEDIA || draft.images.length === 0) &&
      (draft.enabledAttachmentType !== AttachmentTypes.MEDIA || draft.video === null) &&
      (draft.enabledAttachmentType !== AttachmentTypes.MEDIA || draft.gif === null) &&
      (draft.enabledAttachmentType !== AttachmentTypes.RETWEET || draft.retweet === null) &&
      draft.sourceLink === null
    );

    // Link Attachment factory
    const getNewLink =
      ({ url, title = null, description = null, thumbnail = null, thumbnailHttps = null,
        availableThumbnails = null, wasEdited = false }) =>
      ({ url, title, description, thumbnail, thumbnailHttps, availableThumbnails, wasEdited });

    // SourceLink Attachment factory (source url and its available images)
    const getNewSourceLink = (url) => ({
      url,
      availableImages: [],
    });

    // Available images factory
    const getNewAvailableImage = (image, sourceLink) => ({
      url: image.url,
      mediaType: MediaTypes.IMAGE,
      sourceLink,
      width: image.width,
      height: image.height,
    });

    // Image factory
    const getNewImage = ({ url, width = null, height = null, altText = null }) => ({
      url,
      mediaType: MediaTypes.IMAGE,
      width,
      height,
      altText,
    });

    // Gif factory
    const getNewGif = (gifUrl, gifStillUrl, width = null, height = null) => ({
      url: gifUrl,
      stillGifUrl: gifStillUrl,
      mediaType: MediaTypes.GIF,
      width,
      height,
    });

    // Video factory
    const getNewVideo =
      ({ uploadId = null, name, duration, durationMs, size, width, height, url, originalUrl,
        thumbnail, availableThumbnails, thumbOffset }) =>
      ({ uploadId, name, duration, durationMs, size, width, height, url, originalUrl,
        thumbnail, availableThumbnails, thumbOffset, mediaType: MediaTypes.VIDEO, wasEdited: false });

    // Retweet factory
    const getNewRetweet = ({ text, tweetId, userId, userName, userDisplayName, tweetUrl, avatarUrl }) =>
      ({ text, tweetId, userId, userName, userDisplayName, tweetUrl, avatarUrl });

    const getNewInstagramFeedbackObj = ({ message, composerId = 'instagram', code = undefined }) =>
      ({ message, composerId, code });

    const getInitialState = () => ({
      drafts: Services.map((service) => getNewDraft(service)),
      draftsSharedData: {
        uploadedImages: [],
        uploadedGifs: [],
        processingVideos: new Map(), // uploadId <> [drafId, uploaderInstance]
        uploadedVideos: [],
      },
      meta: {
        lastInteractedWithComposerId: null,
        forceEditorFocus: false,
      },
    });

    let state = getInitialState();

    // Register with Redux DevTools (uncomment to enable)
    // registerStore('composer', state);

    const softResetState = () => {
      const newState = getInitialState();

      // The only data to preserve is the enabled state of each draft
      newState.drafts = newState.drafts.map((newDraft) => {
        const { isEnabled, editorState } = state.drafts.find(({ id }) => id === newDraft.id);

        return {
          ...newDraft,
          isEnabled,
          editorState: resetEditorContents(editorState),
        };
      });

      state = newState;
    };

    const eventShowUpgradeModal = () => {
      events.trigger('show-upgrade-modal');
    }

    const ComposerStore = Object.assign({}, EventEmitter.prototype, {
      emitChange: () => ComposerStore.emit(CHANGE_EVENT),
      addChangeListener: (callback) => ComposerStore.on(CHANGE_EVENT, callback),
      removeChangeListener: (callback) => ComposerStore.removeListener(CHANGE_EVENT, callback),

      getEnabledDrafts: () => state.drafts.filter((draft) => draft.isEnabled),
      getDrafts: () => state.drafts,

      getInvalidEnabledDraftsFeedback: () => {
        const { hasIGDirectVideoFlip } = AppStore.getUserData();
        const selectedIgProfiles = AppStore.getSelectedProfilesForService('instagram');
        const hasSomeIGDirectProfilesSelected =
          selectedIgProfiles.filter((profile) => profile.instagramDirectEnabled).length > 0;
        return ComposerStore.getEnabledDrafts().reduce((invalidDraftsFeedback, draft) => {
          const contentState = draft.editorState.getCurrentContent();
          const hasText = contentState.hasText();
          const hasLinkAttached =
            draft.enabledAttachmentType === AttachmentTypes.LINK && draft.link !== null;
          const hasRetweetAttached =
            draft.enabledAttachmentType === AttachmentTypes.RETWEET && draft.retweet !== null;
          const hasMediaAttached =
            draft.enabledAttachmentType === AttachmentTypes.MEDIA &&
            (draft.images.length > 0 || draft.video !== null || draft.gif !== null);
          const hasAnyAttachment = hasLinkAttached || hasRetweetAttached || hasMediaAttached;

          const hasRequiredAttachmentAttached =
            draft.service.requiredAttachmentType === null ||
            (draft.service.requiredAttachmentType === AttachmentTypes.LINK && hasLinkAttached) ||
            (draft.service.requiredAttachmentType === AttachmentTypes.RETWEET && hasRetweetAttached) ||
            (draft.service.requiredAttachmentType === AttachmentTypes.MEDIA && hasMediaAttached);

          const isSourceUrlUnrequiredOrValid =
            !draft.service.canHaveSourceUrl ||
            draft.sourceLink === null ||
            twitterText.isValidUrl(draft.sourceLink.url, true, false);

          const hasRequiredText =
            !draft.service.requiresText || hasText;

          let hasTooManyHashtags = false;
          Eif (draft.service.maxHashtagsInText !== null) {
            const text = contentState.getPlainText();
            const matches = text.match(HASHTAG_REGEX);

            hasTooManyHashtags = (
              matches !== null &&
              matches.length > draft.service.maxHashtagsInText
            );
          }

          // For now only validate with validateDraft method the Instagram w/ video drafts.
          // Although in the future we can move all the validation there and remove it
          // from ComposerStore.
          let validationResult = new ValidationSuccess();

          // Only validate videos if they have the IG Direct Video feature
          // and there is at least one IG business profile selected
          Eif (draft.service.name === 'instagram' &&
            hasIGDirectVideoFlip &&
            hasSomeIGDirectProfilesSelected) {
            validationResult = validateDraft(draft);
          }

          const isInvalid =
            (!hasText && !hasAnyAttachment) ||
            !hasRequiredAttachmentAttached ||
            !hasRequiredText ||
            !isSourceUrlUnrequiredOrValid ||
            hasTooManyHashtags ||
            validationResult.isInvalid();

          if (isInvalid) {
            const messages = [];
            let requiredAttachmentCopy;
            let canHaveImageOrGifAttachment;
            let canHaveVideoAttachment;
            switch (draft.service.requiredAttachmentType) {
              case AttachmentTypes.LINK:
                requiredAttachmentCopy = 'a link preview';
                break;

              case AttachmentTypes.RETWEET:
                requiredAttachmentCopy = 'a retweet';
                break;

              case AttachmentTypes.MEDIA:
                canHaveImageOrGifAttachment =
                  draft.service.canHaveSomeMediaAttachmentTypes([MediaTypes.IMAGE, MediaTypes.GIF]);
                canHaveVideoAttachment = draft.service.canHaveMediaAttachmentType(MediaTypes.VIDEO);

                Eif (canHaveImageOrGifAttachment && canHaveVideoAttachment) {
                  requiredAttachmentCopy = 'an image or video';
                } else if (canHaveImageOrGifAttachment) {
                  requiredAttachmentCopy = 'an image';
                } else if (canHaveVideoAttachment) {
                  requiredAttachmentCopy = 'a video';
                }
                break;
              default:
                break;
            }

            Iif (!hasRequiredAttachmentAttached && !hasRequiredText) {
              messages.push(`Please include ${requiredAttachmentCopy} and some text`);
            } else Eif (!hasRequiredAttachmentAttached) {
              messages.push(`Please include ${requiredAttachmentCopy}`);
            } else if (!hasRequiredText) {
              messages.push('Please include some text');
            } else if (!hasText && !hasAnyAttachment) {
              messages.push('Please include at least some text or an attachment');
            }

            Iif (!isSourceUrlUnrequiredOrValid) {
              messages.push('Please include a valid source url or leave the source url blank');
            }

            Iif (hasTooManyHashtags) {
              messages.push(`At most ${draft.service.maxHashtagsInText} hashtags can be used`);
            }

            Iif (validationResult.isInvalid()) {
              messages.push(validationResult.message);
            }

            invalidDraftsFeedback.push({ draft, messages });
          }

          return invalidDraftsFeedback;
        }, []);
      },

      getDraft: (id) => state.drafts.find((draft) => draft.id === id),
      getDraftText: (id) => ComposerStore.getDraft(id).editorState.getCurrentContent().getPlainText(),

      getDraftLinkUrl: (id) => {
        const link = ComposerStore.getDraft(id).link;
        return link ? link.url : null;
      },

      doesDraftHaveLinkAttachment: (id) => ComposerStore.getDraft(id).link !== null,
      doesDraftHaveRetweetAttachment: (id) => ComposerStore.getDraft(id).retweet !== null,
      doesDraftHaveAttachmentEnabled: (id) => ComposerStore.getDraft(id).enabledAttachmentType !== null,
      doesDraftHaveLinkAttachmentEnabled: (id) =>
        ComposerStore.getDraft(id).enabledAttachmentType === AttachmentTypes.LINK,
      doesDraftHaveSourceLink: (id) => ComposerStore.getDraft(id).sourceLink !== null,
      doesDraftHaveLocation: (id) => ComposerStore.getDraft(id).locationId !== null,

      isDraftEnabled: (id) => ComposerStore.getDraft(id).isEnabled,
      isDraftLocked: (id) => ComposerStore.getDraft(id).isSaved,

      getDraftsSharedData: () => state.draftsSharedData,

      areAllDraftsSaved: () => {
        const enabledDrafts = ComposerStore.getEnabledDrafts();
        return enabledDrafts.length > 0 && enabledDrafts.every((draft) => draft.isSaved);
      },

      // Retrieve long link from shortLinkLongLinkMap (if url is long link already, return url)
      getCanonicalUrl: (url) => {
        const matchingDraft = state.drafts.find((draft) => draft.shortLinkLongLinkMap.has(url));
        if (matchingDraft) return matchingDraft.shortLinkLongLinkMap.get(url);

        return url;
      },

      // scheduledAt and isPinnedToSlot are the same across all drafts
      getScheduledAt: () => state.drafts[0].scheduledAt,
      isPinnedToSlot: () => state.drafts[0].isPinnedToSlot,

      getMeta: () => state.meta,

      /**
       * Do not use: synchronous "dispatches" go against Flux's ideas, this method
       * is only used in a single place to prevent a race condition.
       */
       // eslint-disable-next-line no-use-before-define
      _syncDispatch: (payload) => onDispatchedPayload(payload),
    });

    // Should be used for composition with functions that are passed a draft id as first argument.
    // It would have been awesome to compose this as a decorator on top of non-class methods,
    // alas this isn't part of the spec yet.
    const monitorComposerLastInteractedWith = (fn) => (draftId, ...restArgs) => {
      Iif (draftId === 'omni' || draftId === AppStore.getAppState().expandedComposerId) {
        state.meta.lastInteractedWithComposerId = draftId;
      }

      return fn(draftId, ...restArgs);
    };

    const updateDraftHasSavingError = (id, hasSavingError) => {
      ComposerStore.getDraft(id).hasSavingError = hasSavingError;
    };

    const clearDraftInlineErrors = (id) => {
      const notifications = NotificationStore.getVisibleNotifications().filter((notif) =>
        notif.scope === `${NotificationScopes.UPDATE_SAVING}-${ErrorTypes.INLINE}-${id}` ||
        notif.scope === `${NotificationScopes.PROFILE_QUEUE_LIMIT}-${id}`
      );
      notifications.forEach((notif) => NotificationActionCreators.removeNotification(notif.id));
    };

    const enableDraft = monitorComposerLastInteractedWith(
      (id, markAppAsLoadedWhenDone) => {
        let shouldPreventRerender = false;

        Iif (ComposerStore.isDraftLocked(id)) return !shouldPreventRerender;

        /**
         * Dashboard-specific rules:
         * - If omnibox is disabled, and there's only a single and empty composer currently
         *   enabled, then enabling a new draft will enable the omnibox, effectively keeping
         *   a single composer visible (the omnibox's)
         * - If omnibox is disabled, and there are multiple or non-empty composers currently
         *   enabled, then enabling a new draft will show an additional composer, which will
         *   be prefilled with the previous composer's contents
         */
        const { appEnvironment } = AppStore.getMetaData();
        const isDashboardEnv = appEnvironment === AppEnvironments.WEB_DASHBOARD;
        Iif (isDashboardEnv) {
          const { isOmniboxEnabled } = AppStore.getAppState();

          if (!isOmniboxEnabled) {
            const enabledDrafts = ComposerStore.getEnabledDrafts();
            const hasOneEmptyEnabledDraft =
              enabledDrafts.length === 1 && isDraftEmpty(enabledDrafts[0]);

            if (hasOneEmptyEnabledDraft) {
              AppActionCreators.updateOmniboxState(true);
              shouldPreventRerender = true;
            } else if (enabledDrafts.length >= 1) {
              copyDraftContents({
                draftFrom: ComposerStore.getDraft(state.meta.lastInteractedWithComposerId),
                draftsTo: [ComposerStore.getDraft(id)],
              });
            }
          }
        }

        ComposerStore.getDraft(id).isEnabled = true;
        ComposerActionCreators.updateInstagramState();
        Iif (markAppAsLoadedWhenDone) AppActionCreators.markAppAsLoaded();

        return !shouldPreventRerender;
      }
    );

    const disableDraft = (id) => {
      let shouldPreventRerender = false;

      if (ComposerStore.isDraftLocked(id)) return !shouldPreventRerender;
      ComposerStore.getDraft(id).isEnabled = false;

      // Disable omnibox mode if needed
      const { isOmniboxEnabled } = AppStore.getAppState();
      const enabledDrafts = ComposerStore.getEnabledDrafts();
      const hasOneEnabledDraft = enabledDrafts.length === 1;

      if (isOmniboxEnabled && hasOneEnabledDraft) {
        AppActionCreators.updateOmniboxState(null);
        copyDraftContents({ draftsTo: enabledDrafts });
        shouldPreventRerender = true;
      }

      NotificationActionCreators.removeComposerOmniboxNotices(id);

      return !shouldPreventRerender;
    };

    const getFirstNonNullOrUndefined = (...values) => (
      values.find((v) => typeof v !== 'undefined' && v !== null)
    );

    const handleDraftInitialTextMentions = (editorState, contentState) => {
      contentState.getBlockMap().forEach((contentBlock) => {
        prepopulatedMentionStrategy(
          contentBlock,
          (...indices) => {
            editorState = addEditorPrepopulatedMention(editorState, contentBlock, indices);
          }
        );
      });

      return editorState;
    };

    const handleDraftInitialTextHashtags = (editorState, contentState) => {
      contentState.getBlockMap().forEach((contentBlock) => {
        prepopulatedHashtagStrategy(
          contentBlock,
          (...indices) => {
            editorState = addEditorPrepopulatedHashtag(editorState, contentBlock, indices);
          }
        );
      });

      return editorState;
    };

    const handleDraftInitialFacebookMentions = (editorState, contentState, entities) => {
      entities.forEach(({ indices, ...entityData }) => {
        // Use a Map for entity data in order to expose a similar API as
        // draft-js-mention-plugin, which uses ImmutableJS
        const entityDataMap = new Map(Object.entries(entityData));

        editorState = addEditorImportedFacebookMention(editorState, indices, {
          mention: entityDataMap,
        });
      });

      return editorState;
    };

    const setDraftInitialText = ({
      id,
      text,
      url,
      facebookMentionEntities,
      via,
      composerInitiator,
      isPrefillingExistingUpdate,
      isEditing,
    }) => {
      const draft = ComposerStore.getDraft(id);

      if (draft.enabledAttachmentType === AttachmentTypes.RETWEET) {
        const retweetMark = 'RT @';

        if (text.includes(retweetMark)) {
          text = text.substring(0, text.indexOf(` ${retweetMark}`));
          const hasRetweetComment = text.length !== 0;
          if (!hasRetweetComment) return;
        }
      }

      const shouldAppendUrl = (
        draft.service.name !== 'pinterest' &&
        (draft.service.name !== 'instagram' ||
         !ComposerInitiators.ImageBufferButtons.includes(composerInitiator))
      );

      const initialText = [
        text,
        shouldAppendUrl ? url : null,
        via ? `via @${via}` : null,
      ].filter((val) => val).join(' ');

      /**
       * willGetOverridenByOmnibox is a patch that serves to prevent the Facebook
       * text-prefilling notification below from showing up when MC starts with the
       * omnibox and other composers still get prefilled on load (hence queueing that
       * tooltip on load, despite the fact that the omnibox's contents will override
       * what was prefilled into Facebook anyway, making the tooltip unnecessary).
       * TODO: A better way of doing this will be to refactor how MC loads -> currently
       * all drafts are prefilled on load (omnibox and social networks); instead we'll
       * want only the omnibox to be prefilled, or only the social networks to be
       * prefilled if the omnibox isn't enabled. It'll be less wasteful, and will
       * remove the need for patches like willGetOverridenByOmnibox which should ideally
       * not exist. Most (if not all) actions created from loadInitialMetaData() will
       * need to be refactored to only target either the omnibox or the other drafts.
       */
      const willGetOverridenByOmnibox =
        AppStore.getAppState().isOmniboxEnabled && !draft.service.isOmni;

      if (
        draft.service.doesRequireHumanInteractionToUpdateText &&
        !isPrefillingExistingUpdate &&
        !willGetOverridenByOmnibox
      ) {
        NotificationActionCreators.queueInfo({
          scope: `${NotificationScopes.COMPOSER_NOTICE_NOT_PREFILLED}-${draft.service.name}`,
          message: `<a href="https://faq.buffer.com/article/589-why-the-browser-extension-${''
                    }doesnt-pull-in-text-for-facebook" className={styles.composerInfoMessageLink}
                    target="_blank" rel="noopener noreferrer">Why is it necessary to manually
                    enter a message for Facebook?</a>`,
          onlyCloseOnce: true,
        });
        return;
      }

      /**
       * Show a message warning users about posting duplicate content on Twitter
       */
      if (
        draft.service.shouldShowDuplicateContentWarning &&
        isPrefillingExistingUpdate &&
        !isEditing
      ) {
        NotificationActionCreators.queueInfo({
          scope: NotificationScopes.TWITTER_DUPLICATE_CONTENT_WARNING,
          message: `Twitter does not allow posting multiple tweets that are “substantially similar”. Please make sure to modify your tweet before scheduling to avoid risking account suspension! <a href="https://faq.buffer.com/article/937-publish-twitter-limitations" className={styles.composerInfoMessageLink}
                    target="_blank" rel="noopener noreferrer">Learn more</a>`,
        });
      }

      // Ensure only a single content block gets created by createFromText() by
      // splitting initialText with a regex that matches nothing
      const zeroMatchDelimiter = /$./;
      const contentState = ContentState.createFromText(initialText, zeroMatchDelimiter);

      let editorState = EditorState.createWithContent(contentState);
      editorState = EditorState.moveSelectionToEnd(editorState);

      const shouldEnableTwitterMentionAutocomplete = draft.service.name === 'twitter';
      if (shouldEnableTwitterMentionAutocomplete) {
        editorState = handleDraftInitialTextMentions(editorState, contentState);
      }

      const shouldEnableTwitterHashtagAutocomplete = draft.service.name === 'twitter';
      if (shouldEnableTwitterHashtagAutocomplete) {
        editorState = handleDraftInitialTextHashtags(editorState, contentState);
      }

      const shouldEnableFacebookMentionAutocomplete = draft.service.name === 'facebook';
      if (shouldEnableFacebookMentionAutocomplete && facebookMentionEntities !== null) {
        editorState =
          handleDraftInitialFacebookMentions(editorState, contentState, facebookMentionEntities);
      }

      draft.editorState = editorState;

      ComposerActionCreators.updateDraftCharacterCount(id);
    };

    const setDraftsInitialText = ({
      text,
      url,
      facebookMentionEntities,
      via,
      composerInitiator,
      isPrefillingExistingUpdate,
      isEditing,
    }) => {
      state.drafts.forEach((draft) =>
        setDraftInitialText({
          id: draft.id,
          text,
          url,
          facebookMentionEntities,
          via,
          composerInitiator,
          isPrefillingExistingUpdate,
          isEditing,
        })
      );
    };

    const setDraftEditorState = monitorComposerLastInteractedWith(
      (id, editorState) => {
        ComposerStore.getDraft(id).editorState = editorState;
        ComposerActionCreators.updateDraftCharacterCount(id);
      }
    );

    const updateDraftIsSaved = (id) => {
      ComposerStore.getDraft(id).isSaved = true;
    };

    const debouncedUpdateDraftSourceLinkDataActionCreator = debounce((id, url) => {
      ComposerActionCreators.updateDraftSourceLinkData(id, url);
    }, 250);

    const updateDraftSourceLink = monitorComposerLastInteractedWith(
      (id, url) => {
        const draft = ComposerStore.getDraft(id);
        if (!draft.service.canHaveSourceUrl) return;

        if (url === '' || url === null) {
          draft.sourceLink = null;
        } else {
          draft.sourceLink = getNewSourceLink(url);

          const isValidUrl = twitterText.isValidUrl(url, true, false);
          if (isValidUrl) debouncedUpdateDraftSourceLinkDataActionCreator(id, url);
        }
      }
    );

    const updateDraftSourceLinkData = (id, { url, images = [] }) => {
      if (!ComposerStore.doesDraftHaveSourceLink(id)) return;

      const draftSourceLink = ComposerStore.getDraft(id).sourceLink;

      Object.assign(draftSourceLink, {
        url,
        availableImages: images.map((image) => getNewImage({
          url: image.url,
          width: image.width,
          height: image.height,
        })),
      });
    };

    const updateDraftLocation = monitorComposerLastInteractedWith(
      (id, locationId, locationName) => {
        const draft = ComposerStore.getDraft(id);

        if (!draft.service.canHaveLocation) return;

        const previousLocationIsEmpty = draft.locationName === null;
        if (previousLocationIsEmpty) {
          AppActionCreators.trackUserAction(['composer', 'location', 'started_adding_location']);
        }

        draft.locationId = locationId;
        draft.locationName = locationName;
      }
    );

    const updateDraftScheduledAt = monitorComposerLastInteractedWith(
      (id, timestamp, isPinnedToSlot = false) => {
        const draft = ComposerStore.getDraft(id);
        draft.scheduledAt = timestamp;
        draft.isPinnedToSlot = isPinnedToSlot;
      }
    );

    const updateDraftListPlaces = (id, places) => {
      const draft = ComposerStore.getDraft(id);
      draft.places = places;
    };

    const updateInstagramDraftThumbnail = (id, thumbOffset, thumbnail) => {
      const draft = ComposerStore.getDraft(id);
      if (draft.video) {
        draft.video.thumbnail = thumbnail;
        draft.video.thumbOffset = thumbOffset;
      }
    };

    const getDraftCharacterCount = (id, text) => {
      const draft = ComposerStore.getDraft(id);

      Iif (draft.service.name === 'twitter') {
        const mockAttachmentLink = 'https://pbs.twimg.com/media/XXXXXX';
        const mockAttachmentText = ` ${mockAttachmentLink}`;

        if (draft.enabledAttachmentType === AttachmentTypes.MEDIA) {
          if (draft.video !== null) {
            const willVideoBeNativeOnTwitter =
              draft.video.size < draft.service.nativeVideoSizeLimit &&
              draft.video.durationMs < draft.service.nativeVideoDurationLimit * 1000;
            const willVideoLinkBeAddedToText = !willVideoBeNativeOnTwitter;

            if (willVideoLinkBeAddedToText) text += mockAttachmentText;
          }
        }

        return twitterText.getTweetLength(text);
      }

      Eif (draft.service.name === 'instagram') {
        const charCount = (text && text.length) || 0;
        let lineBreakLength = 0;

        if (text && text.match(/\n/g)) {
          lineBreakLength = text.match(/\n/g).length;
        }
        return charCount + lineBreakLength;
      }

      if (draft.service.name === 'pinterest') {
        let charCount = text.length;
        if (draft.enabledAttachmentType === AttachmentTypes.MEDIA && draft.video !== null) {
          charCount += 52;
        }
        return charCount;
      }

      if (draft.service.name === 'linkedin') {
        let charCount = text.length;

        const urls = twitterText.extractUrls(text);
        const hasLinkAttached =
          draft.enabledAttachmentType === AttachmentTypes.LINK && draft.link !== null;

        // Add 24 chars for images and videos
        if (draft.enabledAttachmentType === AttachmentTypes.MEDIA) {
          if (draft.images.length > 0) charCount += 24;
          if (draft.video !== null) charCount += 24;
        }

        // Add 24 chars for link
        if (hasLinkAttached) charCount += 24;

        // If there are urls in the text, subtract the url length from the charCount
        // and add back 24 chars for each url
        if (urls.length > 0) {
          let accountedForUrlsCount = urls.length;
          let totalUrlLength = 0;

          // Don't count url if it's the link url
          const isAttachedLinkInText = hasLinkAttached && urls.includes(draft.link.url);
          if (isAttachedLinkInText) accountedForUrlsCount--;

          for (const url of urls) {
            totalUrlLength += url.length;
          }

          charCount -= totalUrlLength;
          charCount += accountedForUrlsCount * 24;
        }

        return charCount;
      }

      throw new Error('No character counting rules implemented for this service');
    };

    const updateDraftCharacterCount = monitorComposerLastInteractedWith(
      (id, didEditorStateChange) => {
        const draft = ComposerStore.getDraft(id);
        if (draft.service.charLimit === null) return;

        const draftText = ComposerStore.getDraftText(id);
        draft.characterCount = getDraftCharacterCount(id, draftText);

        // If the character count was updated as a result of a change that didn't
        // originate from the editor itself, we need to give the editor an opportunity
        // to re-render the highlighter's decorator ourselves. A prop is used to tell
        // the editor to re-render decorators. The editor itself sets that prop back
        // to false using the draft reference.
        if (!didEditorStateChange) draft.forceDecoratorsRerender = true;
      }
    );

    const mapShortLinkWithLongLink = (id, shortLink, longLink) => {
      const draft = ComposerStore.getDraft(id);
      draft.shortLinkLongLinkMap.set(shortLink, longLink);
    };

    const unmapShortLinkWithLongLink = (id, link) => {
      const draft = ComposerStore.getDraft(id);
      draft.shortLinkLongLinkMap.delete(link);
    };

    /**
     * Loop over each block of text in the editor, and update the list of all urls
     * within the composer + detect new and removed ones
     */
    const parseDraftTextLinks = (id) => {
      const draft = ComposerStore.getDraft(id);
      const contentState = draft.editorState.getCurrentContent();
      const parsedUrls = [];

      contentState.getBlockMap().forEach((contentBlock) => {
        const text = contentBlock.getText();
        const parsedUrlsWithIndices = twitterText.extractUrlsWithIndices(text);

        parsedUrls.push(...parsedUrlsWithIndices.map((urlWithIndices) => urlWithIndices.url));
      });

      const newUrls = parsedUrls.filter((url) => !draft.urls.includes(url));
      const removedUrls = draft.urls.filter((url) => !parsedUrls.includes(url));

      draft.urls = parsedUrls;

      if (newUrls.length) ComposerActionCreators.handleNewDraftLinks(id, newUrls);
      if (removedUrls.length) ComposerActionCreators.handleRemovedDraftLinks(id, removedUrls);

      if (newUrls.length || removedUrls.length) ComposerActionCreators.updateDraftCharacterCount(id);
    };

    const handleNewDraftLinks = (id, newUrls) => {
      const draft = ComposerStore.getDraft(id);

      // If link attachment is disabled, update it with first newly-added url
      if (!ComposerStore.doesDraftHaveLinkAttachmentEnabled(id)) {
        ComposerActionCreators.updateDraftLink(id, newUrls[0]);

        // If no attachment is currently enabled, bring link attachment up with new link
        if (!ComposerStore.doesDraftHaveAttachmentEnabled(id)) {
          ComposerActionCreators.toggleAttachment(id, AttachmentTypes.LINK);
        }
      }

      // Shorten newly-added links if not unshortened before
      newUrls.forEach((newUrl) => {
        const wasUnshortenedBefore = draft.unshortenedUrls.includes(newUrl);
        if (!wasUnshortenedBefore) ComposerActionCreators.shortenDraftLink(id, newUrl);
      });

      // Add images scraped from new links to list of available images
      newUrls.forEach((newUrl) => ComposerActionCreators.updateDraftLinkAvailableImages(id, newUrl));
    };

    const handleRemovedDraftLinks = (id, removedUrls) => {
      const draft = ComposerStore.getDraft(id);

      removedUrls.forEach((removedUrl) => {
        // Remove from available images those whose source link has been removed
        ComposerActionCreators.removeDraftLinkAvailableImages(id, removedUrl);

        // Forget this link was possibly unshortened before to allow shortening it
        // again if re-added
        const unshortenedUrlIndex = draft.unshortenedUrls.indexOf(removedUrl);
        if (unshortenedUrlIndex !== -1) draft.unshortenedUrls.splice(unshortenedUrlIndex, 1);

        unmapShortLinkWithLongLink(id, removedUrl);
      });
    };

    /**
     * One-stop shop for updating draft link data. When a new link attachment is created,
     * if a piece of link attachment data that could be retrieved from the scraper is
     * missing, the scraper will be automatically invoked to retrieve more data.
     *
     * @param {string} id - Draft id
     * @param {object} linkData - Contains any number of link data properties
     * @param {object} meta
     * @param {boolean} meta.isNewLinkAttachment - Whether a new link is being attached,
     *                                             or an existing one being updated
     * @param {boolean} meta.comesFromDirectUserAction - Whether e.g. a keypress led to
     *                                                   linkData being updated
     *
     * The values from both meta.isNewLinkAttachment and meta.comesFromDirectUserAction
     * will determine how linkData is used. If meta.isNewLinkAttachment is true, linkData
     * will replace all previous values, and missing data will be reset to null. If it's
     * false, then linkData will be composed onto the existing link attachment's data.
     * Some properties can be customized by users and are valuable to keep around when new
     * link attachement data is set (e.g. after scraping a link). That's the case of
     * link.title, link.description, and link.thumbnail. When meta.comesFromDirectUserAction
     * is false, these properties will never be overridden by new linkData. When it's true,
     * these properties will always take new values from new linkData (if provided).
     *
     * Example usage:
     *
     * 1. Creating a new empty link attachment:
     *
     *    updateDraftLinkData(id, { url }, {
     *      isNewLinkAttachment: true,
     *      comesFromDirectUserAction: false,
     *    })
     *
     * 2. Updating a link attachment's title when users manually edit it:
     *
     *    updateDraftLinkData(id, { title }, {
     *      isNewLinkAttachment: false,
     *      comesFromDirectUserAction: true,
     *    })
     *
     * 3. Update a link attachment's data after scraping the page:
     *
     *    updateDraftLinkData(id, scrapedData, {
     *      isNewLinkAttachment: false,
     *      comesFromDirectUserAction: false,
     *    })
     */
    const updateDraftLinkData = monitorComposerLastInteractedWith(
      (id, linkData, meta) => {
        const { isNewLinkAttachment, comesFromDirectUserAction } = meta;
        const draft = ComposerStore.getDraft(id);

        const {
          url = null, title = null, description = null, thumbnail = null,
          availableThumbnails = null,
        } = linkData;

        if (!draft.service.canHaveAttachmentType(AttachmentTypes.LINK)) return;

        const hasLinkAttachment = draft.link !== null;
        const hasAvailableThumbnails = availableThumbnails !== null && availableThumbnails.length > 0;
        const fallBackToLinkAttachmentData = !isNewLinkAttachment && hasLinkAttachment;
        const prioritizeLinkAttachmentData = fallBackToLinkAttachmentData && !comesFromDirectUserAction;

        // In some situations (e.g. editing an update that has a custom thumbnail in the dashboard),
        // an attached thumbnail won't be found among the scraped availableThumbnails: this flag is used
        // to know when to insert such an attached thumbnail into the collection of availableThumbnails
        // so that navigating between available thumbnails doesn't lose this initial thumbnail.
        const hasUnavailableThumbnailAttached = (
          draft.link !== null && draft.link.thumbnail !== null && availableThumbnails !== null &&
          !availableThumbnails.some((thumb) => thumb.url === draft.link.thumbnail.url)
        );

        draft.link = getNewLink({
          url: getFirstNonNullOrUndefined(
            url,
            fallBackToLinkAttachmentData ? draft.link.url : null
          ),
          title: getFirstNonNullOrUndefined(
            prioritizeLinkAttachmentData ? draft.link.title : null,
            title !== null ? title.replace(/\n/g, '') : null, // Strip out line breaks
            fallBackToLinkAttachmentData ? draft.link.title : null
          ),
          description: getFirstNonNullOrUndefined(
            prioritizeLinkAttachmentData ? draft.link.description : null,
            description,
            fallBackToLinkAttachmentData ? draft.link.description : null
          ),
          thumbnail: getFirstNonNullOrUndefined(
            thumbnail !== null ? getNewImage({ url: thumbnail }) : null,
            fallBackToLinkAttachmentData ? draft.link.thumbnail : null,
            (hasAvailableThumbnails ?
              getNewImage({
                url: availableThumbnails[0].url,
                width: availableThumbnails[0].width,
                height: availableThumbnails[0].height,
              }) :
              null)
          ),
          thumbnailHttps: null,
          availableThumbnails: getFirstNonNullOrUndefined(
            (availableThumbnails !== null ?
              [
                ...(hasUnavailableThumbnailAttached ? [draft.link.thumbnail] : []),
                ...availableThumbnails.map((thumb) => getNewImage({ url: thumb.url, width: thumb.width, height: thumb.height })),
              ] :
              null),
            fallBackToLinkAttachmentData ? draft.link.availableThumbnails : null
          ),
          wasEdited:
            (isNewLinkAttachment ?
              false :
              comesFromDirectUserAction || !!(draft.link && draft.link.wasEdited)),
        });

        // If the link is missing some data that we could retrieve by scraping it, do so
        const scrapableProps = ['title', 'description', 'availableThumbnails'];
        const isAnyScrapablePropMissing = scrapableProps.some((prop) => draft.link[prop] === null);
        if (isAnyScrapablePropMissing) ComposerActionCreators.scrapeDraftLinkData(id, url);

        if (isNewLinkAttachment) AppActionCreators.refreshFacebookDomainOwnershipData();
      }
    );

    const updateDraftFileUploadProgress = (id, uploaderInstance, progress) => {
      const { filesUploadProgress } = ComposerStore.getDraft(id);

      if (progress !== null) filesUploadProgress.set(uploaderInstance, progress);
      else filesUploadProgress.delete(uploaderInstance);
    };

    const addDraftImage = monitorComposerLastInteractedWith(
      (id, image) => {
        const draft = ComposerStore.getDraft(id);
        const hasAttachedVideo = draft.video !== null;
        const hasAttachedGif = draft.gif != null;

        const currentlyUploadingImagesCount = draft.filesUploadProgress.size;
        // + 1 to ensure we take into account current image we're adding
        const newImagesOverflow =
          draft.images.length + currentlyUploadingImagesCount - draft.service.maxAttachableImagesCount + 1;
        const needsToMakeRoomForNewImages = newImagesOverflow > 0;

        Iif (!draft.service.canHaveAttachmentType(AttachmentTypes.MEDIA)) return;
        Iif (!draft.service.canHaveMediaAttachmentType(MediaTypes.IMAGE)) return;

        Iif (needsToMakeRoomForNewImages) draft.images.splice(-newImagesOverflow, newImagesOverflow);
        Iif (hasAttachedVideo) draft.video = null; // Override video
        Iif (hasAttachedGif) draft.gif = null; // Override gif
        updateDraftAttachedMediaEditingPayload(id, null);

        draft.images.push(image);

        ComposerActionCreators.draftImageAdded(id, image.url);
        ComposerActionCreators.updateDraftCharacterCount(id, { didEditorStateChange: false });
        Eif (draft.id === 'instagram') ComposerActionCreators.updateInstagramState();
      }
    );

    const updateDraftVideoThumbnail = monitorComposerLastInteractedWith(
      (id, thumbnail) => {
        const draft = ComposerStore.getDraft(id);
        if (!draft.service.canEditVideoAttachment) return;

        draft.video.thumbnail = thumbnail;
        draft.video.wasEdited = true;
      }
    );

    const updateDraftVideoTitle = monitorComposerLastInteractedWith(
      (id, title) => {
        const draft = ComposerStore.getDraft(id);
        if (!draft.service.canEditVideoAttachment) return;

        draft.video.name = title;
        draft.video.wasEdited = true;
      }
    );

    const updateDraftLinkThumbnail = monitorComposerLastInteractedWith(
      (id, thumbnail) => {
        const draft = ComposerStore.getDraft(id);
        draft.link.thumbnail = thumbnail;
        draft.link.thumbnailHttps = thumbnail.url;

        // TODO: merge updateDraftLinkThumbnail() into updateDraftLinkData()
        draft.link.wasEdited = true;
      }
    );

    const selectNextLinkThumbnail = monitorComposerLastInteractedWith(
      (draftId) => {
        const draft = ComposerStore.getDraft(draftId);
        const availableThumbnails = draft.link.availableThumbnails;
        const currThumbnailIndex = findLastIndexOf(availableThumbnails, (thumbnail) =>
          thumbnail.url === draft.link.thumbnail.url);
        let nextThumbnail;

        if (currThumbnailIndex === availableThumbnails.length - 1) {
          nextThumbnail = availableThumbnails[0];
        } else {
          nextThumbnail = availableThumbnails[currThumbnailIndex + 1];
        }

        ComposerActionCreators.updateDraftLinkThumbnail(draftId, nextThumbnail);
      }
    );

    const selectPreviousLinkThumbnail = monitorComposerLastInteractedWith(
      (draftId) => {
        const draft = ComposerStore.getDraft(draftId);
        const availableThumbnails = draft.link.availableThumbnails;
        const currThumbnailIndex = availableThumbnails.findIndex((thumbnail) =>
          thumbnail.url === draft.link.thumbnail.url
        );
        let prevThumbnail;

        if (currThumbnailIndex === 0) {
          prevThumbnail = availableThumbnails[availableThumbnails.length - 1];
        } else {
          prevThumbnail = availableThumbnails[currThumbnailIndex - 1];
        }

        ComposerActionCreators.updateDraftLinkThumbnail(draftId, prevThumbnail);
      }
    );

    const addDraftLinkAvailableThumbnail = (id, thumbnail) => {
      const draft = ComposerStore.getDraft(id);
      if (draft.link.availableThumbnails === null) draft.link.availableThumbnails = [];
      draft.link.availableThumbnails.unshift(thumbnail);
    };

    const addDraftUploadedLinkThumbnail = (id, url, width, height) => {
      const draftsSharedData = ComposerStore.getDraftsSharedData();
      const formattedImage = getNewImage({ url, width, height });

      /**
       * It's important for the three collections below to share the same formattedImage
       * reference, so that a change made in one location propagates to all other places
       * seamlessly.
       * TODO: Re-implement this logic in an immutable fashion: it'll be a bit more work
       * to manually search and update all places where an image can be stored, but it'll
       * be much more solid.
       */
      updateDraftLinkThumbnail(id, formattedImage);
      addDraftLinkAvailableThumbnail(id, formattedImage);
      draftsSharedData.uploadedImages.push(formattedImage);
    };

    const addDraftUploadedImage = (draftId, url, width, height) => {
      const draftsSharedData = ComposerStore.getDraftsSharedData();
      const formattedImage = getNewImage({ url, width, height });

      /**
       * It's important for the two collections below to share the same formattedImage
       * reference, so that a change made in one location propagates to all other places
       * seamlessly.
       * TODO: Re-implement this logic in an immutable fashion: it'll be a bit more work
       * to manually search and update all places where an image can be stored, but it'll
       * be much more solid.
       */
      draftsSharedData.uploadedImages.push(formattedImage);
      addDraftImage(draftId, formattedImage);
    };

    const addAutoUploadedImage = (url, altText) => {
      const draftsSharedData = ComposerStore.getDraftsSharedData();
      const formattedImage = getNewImage({ url, altText });

      /**
       * It's important for the two collections below to share the same formattedImage
       * reference, so that a change made in one location propagates to all other places
       * seamlessly.
       * TODO: Re-implement this logic in an immutable fashion: it'll be a bit more work
       * to manually search and update all places where an image can be stored, but it'll
       * be much more solid.
       */
      draftsSharedData.uploadedImages.push(formattedImage);
      state.drafts.forEach((draft) => addDraftImage(draft.id, formattedImage));
    };

    const removeDraftImage = monitorComposerLastInteractedWith(
      (id, image) => {
        const draft = ComposerStore.getDraft(id);
        const imageIndex = draft.images.indexOf(image);

        draft.images.splice(imageIndex, 1);

        ComposerActionCreators.updateDraftCharacterCount(id, { didEditorStateChange: false });
        if (draft.id === 'instagram') ComposerActionCreators.updateInstagramState();
      }
    );

    // TODO: Refactor to not rely on reference mutations
    const updateImageAltText = (image, altText) => {
      image.altText = altText;
    };

    /**
     * TODO: Refactor to not rely on reference mutations
     * This method is currently only called when auto-uploading images (i.e. auto-attached
     * images on app load), so the two collections where we're sure to be able to find
     * them at any point in time are draftsSharedData.uploadedImages/uploadedGifs.
     * Find the image there and mutate it. This is quite brittle, hence the todo above.
     */
    const updateUploadedImageDimensions = (url, width, height) => {
      const draftsSharedData = ComposerStore.getDraftsSharedData();
      const collections = [draftsSharedData.uploadedImages, draftsSharedData.uploadedGifs];
      let image;

      collections.some((imageCollection) => (
        image = imageCollection.find((uploadedImage) => uploadedImage.url === url)
      ));

      image.width = width;
      image.height = height;
    };

    /**
     * Note: When adding to the draft a video that already exists within the app, it's
     * important to pass the video object's reference around rather than creating a new
     * equivalent video object, since those references are compared in different places
     * using === to establish if we're looking at the same video or not.
     */
    const addDraftVideo = monitorComposerLastInteractedWith(
      (id, video) => {
        const draft = ComposerStore.getDraft(id);
        const hasAttachedImages = draft.images.length > 0;
        const hasAttachedVideo = draft.video !== null;
        const hasAttachedGif = draft.gif !== null;

        Iif (!draft.service.canHaveAttachmentType(AttachmentTypes.MEDIA)) return;
        Iif (!draft.service.canHaveMediaAttachmentType(MediaTypes.VIDEO)) return;

        if (hasAttachedImages) draft.images.splice(0); // Override images
        if (hasAttachedVideo) draft.video = null; // Override video
        Iif (hasAttachedGif) draft.gif = null;
        updateDraftAttachedMediaEditingPayload(id, null);

        draft.video = cloneDeep(video);

        ComposerActionCreators.draftVideoAdded(id, video);
        ComposerActionCreators.updateDraftCharacterCount(id, { didEditorStateChange: false });
        Eif (draft.id === 'instagram') ComposerActionCreators.updateInstagramState();
      }
    );

    const addSharedUploadedVideo = (videoData) => {
      const draftsSharedData = ComposerStore.getDraftsSharedData();
      draftsSharedData.uploadedVideos.push(videoData);
    };

    const finishAddingProcessedVideo = (videoData) => {
      const processingVideos = state.draftsSharedData.processingVideos;

      if (!processingVideos.has(videoData.uploadId)) return;

      const [draftId, uploaderInstance] = processingVideos.get(videoData.uploadId);
      const video = getNewVideo(videoData);

      addDraftVideo(draftId, video);
      addSharedUploadedVideo(video);
      updateDraftFileUploadProgress(draftId, uploaderInstance, null);
    };

    const removeDraftVideo = monitorComposerLastInteractedWith(
      (id) => {
        ComposerStore.getDraft(id).video = null;
        updateDraftAttachedMediaEditingPayload(id, null);
        ComposerActionCreators.updateDraftCharacterCount(id, { didEditorStateChange: false });
        if (id === 'instagram') ComposerActionCreators.updateInstagramState();
      }
    );

    const addDraftGif = monitorComposerLastInteractedWith(
      (id, gif) => {
        const draft = ComposerStore.getDraft(id);
        const hasAttachedImages = draft.images.length > 0;
        const hasAttachedVideo = draft.video !== null;

        if (!draft.service.canHaveAttachmentType(AttachmentTypes.MEDIA)) return;
        if (!draft.service.canHaveMediaAttachmentType(MediaTypes.GIF)) return;

        if (hasAttachedImages) draft.images.splice(0); // Override images
        if (hasAttachedVideo) draft.video = null; // Override video
        updateDraftAttachedMediaEditingPayload(id, null);
        draft.gif = gif;

        ComposerActionCreators.draftGifAdded(id, gif.url);
        ComposerActionCreators.updateDraftCharacterCount(id, { didEditorStateChange: false });
      }
    );

    const addDraftUploadedGif = (draftId, url, stillGifUrl, width, height) => {
      const draftsSharedData = ComposerStore.getDraftsSharedData();
      const formattedGif = getNewGif(url, stillGifUrl, width, height);

      /**
       * It's important for the two collections below to share the same formattedGif
       * reference, so that a change made in one location propagates to all other places
       * seamlessly.
       * TODO: Re-implement this logic in an immutable fashion: it'll be a bit more work
       * to manually search and update all places where an image can be stored, but it'll
       * be much more solid.
       */
      draftsSharedData.uploadedGifs.push(formattedGif);
      addDraftGif(draftId, formattedGif);
    };

    const addAutoUploadedGif = (url, stillGifUrl) => {
      const draftsSharedData = ComposerStore.getDraftsSharedData();
      const formattedGif = getNewGif(url, stillGifUrl);

      /**
       * It's important for the two collections below to share the same formattedGif
       * reference, so that a change made in one location propagates to all other places
       * seamlessly.
       * TODO: Re-implement this logic in an immutable fashion: it'll be a bit more work
       * to manually search and update all places where an image can be stored, but it'll
       * be much more solid.
       */
      draftsSharedData.uploadedGifs.push(formattedGif);
      state.drafts.forEach((draft) => addDraftGif(draft.id, formattedGif));
    };

    const removeDraftGif = monitorComposerLastInteractedWith(
      (id) => {
        ComposerStore.getDraft(id).gif = null;
        updateDraftAttachedMediaEditingPayload(id, null);
        ComposerActionCreators.updateDraftCharacterCount(id, { didEditorStateChange: false });
      }
    );

    const addDraftProcessingVideo = (draftId, uploaderInstance, uploadId) => {
      state.draftsSharedData.processingVideos.set(uploadId, [draftId, uploaderInstance]);
    };

    // This method can be called very often (onMouseMove), so make sure the store
    // only emits a change if a change actually happened to prevent over-rendering
    const updateDraftTempImage = (id, url) => {
      const draft = ComposerStore.getDraft(id);

      if (draft.tempImage !== url) {
        draft.tempImage = url;
        return true;
      }

      return false;
    };

    // Remove draft temp image in all cases if no image is specified, otherwise only
    // remove the passed draft temp image if it's specified
    const removeDraftTempImage = (id, url = null) => {
      if (url === null || ComposerStore.getDraft(id).tempImage === url) {
        updateDraftTempImage(id, null);
      }
    };

    const updateDraftAttachedMediaEditingPayload = (id, media) => {
      ComposerStore.getDraft(id).attachedMediaEditingPayload = media;
    };

    const addDraftRetweet = (id, retweetData) => {
      const draft = ComposerStore.getDraft(id);

      if (!draft.service.canHaveAttachmentType(AttachmentTypes.RETWEET)) return;

      const retweet = getNewRetweet(retweetData);
      draft.retweet = retweet;

      ComposerActionCreators.updateDraftCharacterCount(id, { didEditorStateChange: false });
    };

    const disableDraftAttachment = (id) => {
      const draft = ComposerStore.getDraft(id);
      draft.enabledAttachmentType = null;

      ComposerActionCreators.attachmentToggled(id);
      ComposerActionCreators.updateDraftCharacterCount(id, { didEditorStateChange: false });
    };

    const enableDraftAttachment = (id, attachmentType) => {
      const draft = ComposerStore.getDraft(id);

      if (!draft.service.canHaveAttachmentType(attachmentType)) return;

      // Link Attachment doesn't have a suggestion mode: don't enable it if no link attached
      if (attachmentType === AttachmentTypes.LINK && !ComposerStore.doesDraftHaveLinkAttachment(id)) {
        return;
      }

      // Retweet Attachment doesn't have a suggestion mode: don't enable it if no retweet attached
      if (attachmentType === AttachmentTypes.RETWEET &&
        !ComposerStore.doesDraftHaveRetweetAttachment(id)) {
        return;
      }

      draft.enabledAttachmentType = attachmentType;

      ComposerActionCreators.attachmentToggled(id);
      ComposerActionCreators.updateDraftCharacterCount(id, { didEditorStateChange: false });
      if (id === 'instagram') ComposerActionCreators.updateInstagramState();
    };

    const toggleDraftAttachment = monitorComposerLastInteractedWith(
      (id, attachmentType) => {
        const draft = ComposerStore.getDraft(id);
        const shouldDisableAttachment = (draft.enabledAttachmentType === attachmentType);

        if (shouldDisableAttachment) {
          disableDraftAttachment(id);
        } else {
          enableDraftAttachment(id, attachmentType);
        }

        if (id === 'instagram') ComposerActionCreators.updateInstagramState();
      }
    );

    const replaceDraftLinkWithShortlink = (id, link, shortLink) => {
      const draft = ComposerStore.getDraft(id);
      let editorState = draft.editorState;
      const contentState = editorState.getCurrentContent();

      contentState.getBlockMap().forEach((contentBlock) => {
        const text = contentBlock.getText();
        const parsedUrlsWithIndices = twitterText.extractUrlsWithIndices(text);
        const parsedUrl =
          parsedUrlsWithIndices.find((urlWithIndices) => urlWithIndices.url === link);

        if (!parsedUrl) return;

        // The shorten endpoint also handles utm params, so what we think is a short link
        // could also be a long link with utm params added, depending on the user's prefs!
        // Differentiate between the two, and use the appropriate modifier :)
        const bareLink = link.replace(/(\?|#).*$/, ''); // Strip query + fragment for proper comparison
        const isReallyShortLink = !shortLink.includes(bareLink);

        if (isReallyShortLink) {
          editorState = addEditorShortLink(editorState, contentBlock, {
            link,
            shortLink,
            indices: parsedUrl.indices,
          });
        } else {
          editorState = replaceEditorLink(editorState, contentBlock, {
            oldLink: link,
            newLink: shortLink,
            indices: parsedUrl.indices,
          });
        }
      });

      draft.editorState = editorState;

      ComposerActionCreators.parseDraftTextLinks(id);
    };

    const addDraftUnshortenedLink = (id, unshortenedLink) => {
      const draft = ComposerStore.getDraft(id);
      draft.unshortenedUrls.push(unshortenedLink);
    };

    const addDraftAvailableImages = (id, images, sourceLink) => {
      const draft = ComposerStore.getDraft(id);

      const newAvailableImages = images.map((image) => {
        const formattedImage = getNewImage({
          url: image.url,
          width: image.width,
          height: image.height,
        });

        return getNewAvailableImage(formattedImage, sourceLink);
      });

      draft.availableImages = draft.availableImages.concat(newAvailableImages);
    };

    const removeDraftAvailableImages = (id, sourceLink) => {
      const draft = ComposerStore.getDraft(id);

      draft.availableImages = draft.availableImages.filter((availableImage) =>
        availableImage.sourceLink !== sourceLink);
    };

    const addOmniNotice = (message, draftId) => {
      NotificationActionCreators.queueInfo({
        scope: NotificationScopes.MC_OMNIBOX_EDIT_NOTICE,
        message,
        onlyCloseOnce: false,
        data: { id: draftId, type: 'notice' },
      });
    };

    const getEditedImagesMessage = (service) => {
      let message;
      if (service.maxAttachableImagesCount === 1) {
        message = `${service.formattedName} only allows one image, so we used your first image :)`;
      } else {
        message = `${service.formattedName} only allows ${service.maxAttachableImagesCount}
        images, so we kept the first ${service.maxAttachableImagesCount} images :)`;
      }
      return message;
    };

    const copyDraftMedia = (draftFrom, draftTo) => {
      if (draftFrom.images.length > 0 && draftTo.service.canHaveMediaAttachmentType(MediaTypes.IMAGE)) {
        let imagesToAttach = draftFrom.images;
        if (draftFrom.images.length > draftTo.service.maxAttachableImagesCount) {
          imagesToAttach = draftFrom.images.slice(0, draftTo.service.maxAttachableImagesCount);
          const message = getEditedImagesMessage(draftTo.service);
          addOmniNotice(message, draftTo.id);
        }
        imagesToAttach.forEach((image) => addDraftImage(draftTo.id, image));
        enableDraftAttachment(draftTo.id, AttachmentTypes.MEDIA);
      } else if (draftFrom.gif !== null) {
        if (!draftTo.service.canHaveMediaAttachmentType(MediaTypes.GIF)) {
          const message = `${draftTo.service.formattedName} doesn't allow GIFs, so we've removed it for you!`;
          addOmniNotice(message, draftTo.id);
          return;
        }
        addDraftGif(draftTo.id, draftFrom.gif);
        enableDraftAttachment(draftTo.id, AttachmentTypes.MEDIA);
      } else if (draftFrom.video !== null) {
        if (!draftTo.service.canHaveMediaAttachmentType(MediaTypes.VIDEO)) {
          const message = `${draftTo.service.formattedName} doesn't allow videos, so we've removed it for you!`;
          addOmniNotice(message, draftTo.id);
          return;
        }
        addDraftVideo(draftTo.id, draftFrom.video);
        enableDraftAttachment(draftTo.id, AttachmentTypes.MEDIA);
      }
    };

    const copyDraftTextData = (draftFrom, draftTo) => {
      const editorState =
        draftFrom.service.name === 'facebook' && draftTo.service.name !== 'facebook' ?
        removeFacebookAutocompleteEntities(draftFrom.editorState) : draftFrom.editorState;

      setDraftEditorState(draftTo.id, editorState);

      draftTo.urls = draftFrom.urls;
      draftTo.unshortenedUrls = draftFrom.unshortenedUrls;
      draftTo.shortLinkLongLinkMap = draftFrom.shortLinkLongLinkMap;
    };

    const copyDraftContents = ({
      draftFrom = ComposerStore.getDraft('omni'),
      draftsTo = state.drafts,
    } = {}) => {
      draftsTo.forEach((draft) => {
        const service = draft.service;
        if (service.isOmni || draft === draftFrom) return;

        // eslint-disable-next-line no-use-before-define
        clearDraft(draft.id, { preserveEnabledState: true });

        // Add text and data related to text
        copyDraftTextData(draftFrom, draft);
        draft.sourceLink = draftFrom.sourceLink;

        draft.availableImages = draftFrom.availableImages;

        // Add attachments
        const enabledAttachmentType = draftFrom.enabledAttachmentType;
        if (enabledAttachmentType) {
          switch (enabledAttachmentType) {
            case AttachmentTypes.LINK: {
              if (!service.canHaveAttachmentType(enabledAttachmentType)) {
                const message = `${draft.service.formattedName} doesn't allow link attachments, so we removed it for you!`;
                addOmniNotice(message, draft.id);
                return;
              }

              if (!service.canEditLinkAttachment && draftFrom.link.wasEdited) {
                const message = `${draft.service.formattedName} doesn't allow editing links, so we kept the original link attachment for you!`;
                addOmniNotice(message, draft.id);
              }

              if (draftFrom.link !== null) {
                const linkDataToReuse = service.canEditLinkAttachment ? {
                  url: draftFrom.link.url,
                  title: draftFrom.link.title,
                  description: draftFrom.link.description,
                  thumbnail: draftFrom.link.thumbnail !== null ? draftFrom.link.thumbnail.url : null,
                } : {
                  url: draftFrom.link.url,
                };

                updateDraftLinkData(draft.id, linkDataToReuse, {
                  isNewLinkAttachment: true,
                  comesFromDirectUserAction: false,
                });
                enableDraftAttachment(draft.id, AttachmentTypes.LINK);
              }

              break;
            }

            case AttachmentTypes.MEDIA: {
              const { isFreeUser } = AppStore.getUserData();

              if (!service.canHaveAttachmentType(enabledAttachmentType)) {
                const message = `${draft.service.formattedName} doesn't allow image attachments, so we removed the images for you!`;
                addOmniNotice(message, draft.id);
                return;
              }

              if (
                draftFrom.video !== null &&
                draftFrom.video.wasEdited &&
                !service.canEditVideoAttachment &&
                isFreeUser
              ) {
                const message = '​​Please upgrade to our Pro plan to select a custom video thumbnail for Instagram.';
                addOmniNotice(message, draft.id);
              }

              if (
                draftFrom.video !== null &&
                draftFrom.video.wasEdited &&
                !service.canEditVideoAttachment &&
                !isFreeUser
              ) {
                // Confirmed that Instagram is currently the only service that can't edit video attachment
                const message = 'To select a custom thumbnail for Instagram, please click to open the Instagram composer.';
                addOmniNotice(message, draft.id);
              }

              copyDraftMedia(draftFrom, draft);
              break;
            }

            case AttachmentTypes.RETWEET: {
              if (!service.canHaveAttachmentType(enabledAttachmentType)) {
                const message = `${draft.service.formattedName} doesn't allow retweet attachments, so we removed it for you!`;
                addOmniNotice(message, draft.id);
                return;
              }

              draft.retweet = draftFrom.retweet;
              break;
            }

            default:
              break;
          }
        }
      });

      // Let draftFrom remain the last active draft, so that networks that are added
      // immediately after still use the same draft as reference (instead of a
      // possibly more restricted other network, e.g. Twitter)
      state.meta.lastInteractedWithComposerId = draftFrom.id;
      ComposerActionCreators.updateInstagramState();
    };

    const clearDraft = (id, { preserveEnabledState = false } = {}) => {
      const draft = ComposerStore.getDraft(id);
      const emptyDraft = getNewDraft(draft.service);

      if (preserveEnabledState) emptyDraft.isEnabled = draft.isEnabled;

      Object.assign(draft, emptyDraft);
    };

    const clearOmniboxDraftWhenEnabling = (willBeEnabled) => {
      if (willBeEnabled) clearDraft('omni');
    };

    const parseDraftsTextLinks = () => {
      const enabledDrafts = ComposerStore.getEnabledDrafts();
      enabledDrafts.forEach((draft) => parseDraftTextLinks(draft.id));
    };

    const passesImageAspectRatioTest = (image) => {
      Eif (!image.width || !image.height) return true;
      const ratio = image.width / image.height;
      return ((ratio >= InstagramAspectRatioLimits.min) && (ratio <= InstagramAspectRatioLimits.max));
    };

    const passesVideoAspectRatioTest = ({ video, service }) => {
      const aspectRatio = video.width / video.height;
      return ((aspectRatio >= service.videoMinAspectRatio) &&
        (aspectRatio <= service.videoMaxAspectRatio));
    };

    const updateInstagramDraftsFeedback = () => {
      const { hasIGDirectVideoFlip } = AppStore.getUserData();
      const instagramDraft =
        ComposerStore.getEnabledDrafts().filter((draft) => draft.id === 'instagram')[0];
      Iif (!instagramDraft) return;
      instagramDraft.instagramFeedback = [];

      const selectedIgProfiles = AppStore.getSelectedProfilesForService('instagram');
      const hasSomeEnabledProfiles =
        selectedIgProfiles.filter((profile) => profile.instagramDirectEnabled).length > 0;
      const hasSomeDisabledProfiles =
        selectedIgProfiles.filter((profile) => !profile.instagramDirectEnabled).length > 0;
      if (hasSomeEnabledProfiles &&
          instagramDraft.enabledAttachmentType === AttachmentTypes.MEDIA &&
          instagramDraft.images.length > 0) {
        Iif (passesImageAspectRatioTest(instagramDraft.images[0]) === false) {
          instagramDraft.instagramFeedback.push(getNewInstagramFeedbackObj({
            message: `Due to Instagram limitations, we can't post images directly to Instagram with aspect
            ratios outside the range 4:5 to 1.91:1. You will receive a Reminder to post manually when the time comes!`,
            composerId: 'instagram',
            code: 'ASPECT_RATIO',
          }));
          return;
        } else Eif (instagramDraft.images.length > 1) {
          instagramDraft.instagramFeedback.push(getNewInstagramFeedbackObj({
            message: 'Due to Instagram limitations, we can\'t post galleries on your behalf. You will receive a Reminder to post manually when the time comes!',
            composerId: 'instagram',
            code: 'GALLERY',
          }));
          return;
        }
      } else Eif (hasSomeEnabledProfiles && hasIGDirectVideoFlip &&
        instagramDraft.enabledAttachmentType === AttachmentTypes.MEDIA &&
        instagramDraft.video) {
        Iif (passesVideoAspectRatioTest(instagramDraft) === false) {
          instagramDraft.instagramFeedback.push(getNewInstagramFeedbackObj({
            message: `Due to Instagram limitations, we can't post videos directly to Instagram with aspect
            ratios outside the range 4:5 to 16:9. You will receive a Reminder to post manually when the time comes!`,
            composerId: 'instagram',
            code: 'ASPECT_RATIO',
          }));
          return;
        }
      }

      Iif (!hasIGDirectVideoFlip) {
        if (hasSomeEnabledProfiles &&
            instagramDraft.enabledAttachmentType === AttachmentTypes.MEDIA &&
            instagramDraft.video !== null) {
          instagramDraft.instagramFeedback.push(getNewInstagramFeedbackObj({
            message: `Due to Instagram limitations, we can't post videos on your behalf.
            You will receive a Reminder to post manually when the time comes!`,
            composerId: 'instagram',
            code: 'VIDEO',
          }));
          return;
        }
      }

      Iif (hasSomeEnabledProfiles && hasSomeDisabledProfiles) {
        instagramDraft.instagramFeedback.push(getNewInstagramFeedbackObj({
          message: `Some of your accounts aren't enabled for Direct Scheduling,
                    we'll send out Reminders for those accounts.`,
          composerId: 'instagram',
          code: 'NOT_ENABLED',
        }));
      }
    };

    const onDispatchedPayload = (payload) => {
      const action = payload.action;
      let shouldEmitChange = true;
      let video;

      switch (action.actionType) {
        case ActionTypes.COMPOSER_SET_DRAFTS_INITIAL_TEXT:
          setDraftsInitialText(action);
          break;

        case ActionTypes.COMPOSER_UPDATE_DRAFT_EDITOR_STATE:
          setDraftEditorState(action.id, action.editorState);
          break;

        case ActionTypes.UPDATE_DRAFT_IS_SAVED:
          updateDraftIsSaved(action.id);
          break;

        case ActionTypes.COMPOSER_UPDATE_DRAFT_CHARACTER_COUNT:
          updateDraftCharacterCount(action.id, action.didEditorStateChange);
          break;

        case ActionTypes.COMPOSER_PARSE_DRAFT_TEXT_LINKS:
          parseDraftTextLinks(action.id);
          break;

        case ActionTypes.COMPOSER_PARSE_DRAFTS_TEXT_LINKS:
          parseDraftsTextLinks();
          break;

        case ActionTypes.COMPOSER_HANDLE_NEW_DRAFT_TEXT_LINKS:
          handleNewDraftLinks(action.id, action.newUrls);
          break;

        case ActionTypes.COMPOSER_HANDLE_REMOVED_DRAFT_TEXT_LINKS:
          handleRemovedDraftLinks(action.id, action.removedUrls);
          break;

        case ActionTypes.COMPOSER_UPDATE_DRAFTS_SCHEDULED_AT:
          state.drafts.forEach((draft) => {
            updateDraftScheduledAt(draft.id, action.scheduledAt, action.isPinnedToSlot);
          });
          break;

        case ActionTypes.COMPOSER_UPDATE_DRAFT_LINK_DATA:
          updateDraftLinkData(action.id, action.linkData, action.meta);
          break;

        case ActionTypes.COMPOSER_UPDATE_DRAFTS_LINK_DATA:
          state.drafts.forEach((draft) =>
            updateDraftLinkData(draft.id, action.linkData, action.meta));
          break;

        case ActionTypes.COMPOSER_ADD_DRAFT_IMAGE:
          addDraftImage(action.id, action.image);
          break;

        case ActionTypes.COMPOSER_UPDATE_DRAFT_LINK_THUMBNAIL:
          updateDraftLinkThumbnail(action.id, action.thumbnail);
          break;

        case ActionTypes.COMPOSER_UPDATE_DRAFT_VIDEO_THUMBNAIL:
          updateDraftVideoThumbnail(action.id, action.thumbnail);
          break;

        case ActionTypes.COMPOSER_UPDATE_DRAFT_VIDEO_TITLE:
          updateDraftVideoTitle(action.id, action.title);
          break;

        case ActionTypes.COMPOSER_ADD_DRAFTS_IMAGE:
          state.drafts.forEach((draft) => addDraftImage(draft.id, action.image));
          break;

        case ActionTypes.COMPOSER_ADD_DRAFTS_GIF:
          state.drafts.forEach((draft) => addDraftGif(draft.id, action.gif));
          break;

        case ActionTypes.COMPOSER_UPDATE_DRAFT_SOURCE_LINK:
          updateDraftSourceLink(action.id, action.url);
          break;

        case ActionTypes.COMPOSER_UPDATE_DRAFTS_SOURCE_LINK:
          state.drafts.forEach((draft) => updateDraftSourceLink(draft.id, action.url));
          break;

        case ActionTypes.COMPOSER_UPDATE_DRAFT_SOURCE_LINK_DATA:
          updateDraftSourceLinkData(action.id, action.linkData);
          break;

        case ActionTypes.COMPOSER_UPDATE_DRAFT_LOCATION:
          updateDraftLocation(action.id, action.locationId, action.locationName);
          break;

        case ActionTypes.COMPOSER_UPDATE_DRAFTS_LOCATION:
          state.drafts.forEach((draft) => updateDraftLocation(draft.id, action.locationId, action.locationName));
          break;

        case ActionTypes.COMPOSER_UPDATE_DRAFT_LIST_PLACES:
          updateDraftListPlaces(action.id, action.places);
          break;

        case ActionTypes.COMPOSER_UPDATE_INSTAGRAM_DRAFT_THUMBNAIL:
          updateInstagramDraftThumbnail(action.id, action.thumbOffset, action.thumbnail);
          break;

        case ActionTypes.COMPOSER_DRAFT_IMAGE_ADDED:
          removeDraftTempImage(action.id, action.url);
          break;

        case ActionTypes.COMPOSER_REMOVE_DRAFT_IMAGE:
          removeDraftImage(action.id, action.image);
          break;

        case ActionTypes.COMPOSER_ADD_DRAFT_VIDEO:
          addDraftVideo(action.id, action.video);
          break;

        case ActionTypes.COMPOSER_ADD_DRAFT_GIF:
          addDraftGif(action.id, action.gif);
          break;

        case ActionTypes.COMPOSER_DRAFT_VIDEO_ADDED:
          removeDraftTempImage(action.id, action.video.thumbnail);
          break;

        case ActionTypes.COMPOSER_DRAFT_GIF_ADDED:
          removeDraftTempImage(action.id, action.url);
          break;

        case ActionTypes.COMPOSER_REMOVE_DRAFT_VIDEO:
          removeDraftVideo(action.id, action.videoUrl);
          break;

        case ActionTypes.COMPOSER_REMOVE_DRAFT_GIF:
          removeDraftGif(action.id, action.gifUrl);
          break;

        case ActionTypes.COMPOSER_UPDATE_DRAFT_TEMP_IMAGE:
          shouldEmitChange = updateDraftTempImage(action.id, action.url);
          break;

        case ActionTypes.COMPOSER_REMOVE_DRAFT_TEMP_IMAGE:
          removeDraftTempImage(action.id);
          break;

        case ActionTypes.COMPOSER_UPDATE_DRAFT_ATTACHED_MEDIA_EDITING_PAYLOAD:
          updateDraftAttachedMediaEditingPayload(action.id, action.media);
          break;

        case ActionTypes.COMPOSER_ADD_DRAFTS_RETWEET:
          state.drafts.forEach((draft) => addDraftRetweet(draft.id, action.retweetData));
          break;

        case ActionTypes.COMPOSER_TOGGLE_DRAFT_ATTACHMENT:
          toggleDraftAttachment(action.id, action.type);
          break;

        case ActionTypes.COMPOSER_ENABLE_DRAFTS_ATTACHMENT:
          state.drafts.forEach((draft) => enableDraftAttachment(draft.id, action.type));
          break;

        case ActionTypes.COMPOSER_ENABLE:
          shouldEmitChange = enableDraft(action.id, action.markAppAsLoadedWhenDone);
          break;

        case ActionTypes.COMPOSER_DISABLE:
          shouldEmitChange = disableDraft(action.id);
          break;

        case ActionTypes.UPDATE_DRAFT_HAS_SAVING_ERROR:
          updateDraftHasSavingError(action.id, action.hasSavingError);
          break;

        case ActionTypes.COMPOSER_CLEAR_INLINE_ERRORS:
          clearDraftInlineErrors(action.id);
          break;

        case ActionTypes.COMPOSER_DRAFT_LINK_SHORTENED:
          monitorComposerLastInteractedWith(() => {
            replaceDraftLinkWithShortlink(action.id, action.link, action.shortLink);
            mapShortLinkWithLongLink(action.id, action.shortLink, action.link);
          })();
          break;

        case ActionTypes.COMPOSER_DRAFT_LINK_UNSHORTENED:
          monitorComposerLastInteractedWith(() => {
            addDraftUnshortenedLink(action.id, action.unshortenedLink);
            parseDraftTextLinks(action.id);
            unmapShortLinkWithLongLink(action.id, action.shortLink);
          })();
          break;

        case ActionTypes.COMPOSER_DRAFT_LINK_RESHORTENED:
          monitorComposerLastInteractedWith(() => {
            parseDraftTextLinks(action.id);
            mapShortLinkWithLongLink(action.id, action.shortLink, action.link);
          })();
          break;

        case ActionTypes.COMPOSER_ADD_DRAFT_AVAILABLE_IMAGES:
          addDraftAvailableImages(action.id, action.images, action.sourceLink);
          break;

        case ActionTypes.COMPOSER_REMOVE_DRAFT_AVAILABLE_IMAGES:
          removeDraftAvailableImages(action.id, action.sourceLink);
          break;

        case ActionTypes.COMPOSER_DRAFT_FILE_UPLOAD_STARTED:
          monitorComposerLastInteractedWith(() => {
            updateDraftFileUploadProgress(action.id, action.uploaderInstance, 0);
          })();
          break;

        case ActionTypes.COMPOSER_DRAFT_FILE_UPLOAD_PROGRESS:
          updateDraftFileUploadProgress(action.id, action.uploaderInstance, action.progress);
          break;

        case ActionTypes.COMPOSER_ADD_DRAFT_UPLOADED_IMAGE:
          updateDraftFileUploadProgress(action.id, action.uploaderInstance, null);
          // Order matters, this should remain last
          addDraftUploadedImage(action.id, action.url, action.width, action.height);
          break;

        case ActionTypes.COMPOSER_ADD_DRAFT_UPLOADED_LINK_THUMBNAIL:
          addDraftUploadedLinkThumbnail(action.id, action.url, action.width, action.height);
          updateDraftFileUploadProgress(action.id, action.uploaderInstance, null);
          break;

        case ActionTypes.COMPOSER_ADD_DRAFT_UPLOADED_VIDEO:
          addDraftProcessingVideo(action.id, action.uploaderInstance, action.uploadId);
          break;

        case ActionTypes.COMPOSER_ADD_DRAFT_UPLOADED_GIF:
          addDraftUploadedGif(action.id, action.url, action.stillGifUrl, action.width, action.height);
          updateDraftFileUploadProgress(action.id, action.uploaderInstance, null);
          break;

        case ActionTypes.COMPOSER_VIDEO_PROCESSED:
          finishAddingProcessedVideo(action.processedVideoData);
          break;

        case ActionTypes.COMPOSER_ADD_DRAFTS_AUTO_UPLOADED_IMAGE:
          addAutoUploadedImage(action.url, action.altText);
          break;

        case ActionTypes.COMPOSER_ADD_DRAFTS_AUTO_UPLOADED_GIF:
          addAutoUploadedGif(action.url, action.stillGifUrl);
          break;

        case ActionTypes.COMPOSER_UPDATE_NEXT_LINK_THUMBNAIL:
          selectNextLinkThumbnail(action.draftId);
          break;

        case ActionTypes.COMPOSER_UPDATE_PREVIOUS_LINK_THUMBNAIL:
          selectPreviousLinkThumbnail(action.draftId);
          break;

        case ActionTypes.COMPOSER_UPDATE_IMAGE_ALT_TEXT:
          updateImageAltText(action.image, action.altText);
          break;

        case ActionTypes.COMPOSER_UPDATE_UPLOADED_IMAGE_DIMENSIONS:
          updateUploadedImageDimensions(action.url, action.width, action.height);
          updateInstagramDraftsFeedback();
          break;

        case ActionTypes.COMPOSER_APPLY_OMNI_UPDATE:
          copyDraftContents();
          AppActionCreators.updateOmniboxState(false);
          break;

        case ActionTypes.APP_UPDATE_OMNIBOX_STATE:
          clearOmniboxDraftWhenEnabling(action.isEnabled);
          break;

        case ActionTypes.COMPOSER_ADD_DRAFTS_AUTO_UPLOADED_VIDEO:
          video = getNewVideo(action.video);
          addSharedUploadedVideo(video);
          state.drafts.forEach((draft) => addDraftVideo(draft.id, video));
          break;

        case ActionTypes.COMPOSER_DRAFTS_PREVENT_AUTO_ATTACHING_URLS:
          state.drafts.forEach((draft) => { draft.urls = action.urls; });
          break;

        case ActionTypes.COMPOSER_FORCE_FOCUS:
          state.meta.forceEditorFocus = true;
          break;

        case ActionTypes.COMPOSER_STOP_FORCE_FOCUS:
          state.meta.forceEditorFocus = false;
          break;

        case ActionTypes.APP_RESET:
          state = getInitialState();
          break;

        case ActionTypes.COMPOSER_UPDATE_INSTAGRAM_STATE:
          updateInstagramDraftsFeedback();
          break;

        case ActionTypes.APP_SOFT_RESET:
          softResetState();
          break;

        case ActionTypes.EVENT_SHOW_UPGRADE_MODAL:
          eventShowUpgradeModal();
          break;

        default:
          shouldEmitChange = false;
          break;
      }

      if (shouldEmitChange) ComposerStore.emitChange();

      // (uncomment to enable Redux DevTools)
      // sendToMonitor('composer', action, state);
    };

    AppDispatcher.register(onDispatchedPayload);

    export default ComposerStore;
    export { getDraftCharacterCount };