We use cosmological simulations to study a characteristic evolution pattern of high redshift galaxies. Early, stream-fed, highly perturbed, gas-rich discs undergo phases of dissipative contraction into compact, star-forming systems (blue nuggets) at z~4-2. The peak of gas compaction marks the onset of central gas depletion and inside-out quenching into compact ellipticals (red nuggets) by z~2. These are sometimes surrounded by gas rings or grow extended dry stellar envelopes. The compaction occurs at a roughly constant specific star-formation rate (SFR), and the quenching occurs at a constant stellar surface density within the inner kpc ($\Sigma_1$). Massive galaxies quench earlier, faster, and at a higher $\Sigma_1$ than lower-mass galaxies, which compactify and attempt to quench more than once. This evolution pattern is consistent with the way galaxies populate the SFR-radius-mass space, and with gradients and scatter across the main sequence. The compaction is triggered by an intense inflow episode, involving (mostly minor) mergers, counter-rotating streams or recycled gas, and is commonly associated with violent disc instability. The contraction is dissipative, with the inflow rate >SFR, and the maximum $\Sigma_1$ anti-correlated with the initial spin parameter, as predicted by Dekel & Burkert (2014). The central quenching is triggered by the high SFR and stellar/supernova feedback (possibly also AGN feedback) due to the high central gas density, while the central inflow weakens as the disc vanishes. Suppression of fresh gas supply by a hot halo allows the long-term maintenance of quenching once above a threshold halo mass, inducing the quenching downsizing.