file_path stringlengths 3 280 | file_language stringclasses 66 values | content stringlengths 1 1.04M | repo_name stringlengths 5 92 | repo_stars int64 0 154k | repo_description stringlengths 0 402 | repo_primary_language stringclasses 108 values | developer_username stringlengths 1 25 | developer_name stringlengths 0 30 | developer_company stringlengths 0 82 |
|---|---|---|---|---|---|---|---|---|---|
src/pages/index.js | JavaScript | import React from 'react'
import { graphql, Link } from 'gatsby'
function IndexPage({ data: { allGraphCmsPost } }) {
return (
<div className="divide-y divide-gray-200">
<div className="pt-6 pb-8 space-y-2 md:space-y-5">
<h1 className="text-3xl leading-9 font-extrabold text-gray-900 tracking-tight sm:text-4xl sm:leading-10 md:text-6xl md:leading-14">
Latest
</h1>
<p className="text-lg leading-7 text-gray-500">
Our latest blog posts.
</p>
</div>
<ul className="divide-y divide-gray-200">
{allGraphCmsPost.nodes.map((post) => {
return (
<li key={post.id} className="py-12">
<article className="space-y-2 xl:grid xl:grid-cols-4 xl:space-y-0 xl:items-baseline">
<dl>
<dt className="sr-only">Published on</dt>
<dd className="text-base leading-6 font-medium text-gray-500">
<time dateTime={post.date}>{post.date}</time>
</dd>
</dl>
<div className="space-y-5 xl:col-span-3">
<div className="space-y-6">
<h2 className="text-2xl leading-8 font-bold tracking-tight">
<Link
to={`/posts/${post.slug}`}
className="text-gray-900"
>
{post.title}
</Link>
</h2>
{post.excerpt && (
<div className="prose max-w-none text-gray-500">
{post.excerpt}
</div>
)}
</div>
<div className="text-base leading-6 font-medium">
<Link
to={`/posts/${post.slug}`}
className="text-purple-500 hover:text-purple-600"
aria-label={`Read "${post.title}"`}
>
Read more →
</Link>
</div>
</div>
</article>
</li>
)
})}
</ul>
</div>
)
}
export const indexPageQuery = graphql`
{
allGraphCmsPost(sort: { fields: date, order: DESC }) {
nodes {
id
date: formattedDate
excerpt
slug
title
}
}
}
`
export default IndexPage
| ynnoj/2020-08-28-dynamic-content-in-gatsby | 2 | 📹 Dynamic content in Gatsby with Apollo Client | JavaScript | ynnoj | Jonathan Steele | stripe |
src/styles/index.css | CSS | @tailwind base;
@tailwind components;
@tailwind utilities;
| ynnoj/2020-08-28-dynamic-content-in-gatsby | 2 | 📹 Dynamic content in Gatsby with Apollo Client | JavaScript | ynnoj | Jonathan Steele | stripe |
src/templates/blog-post.js | JavaScript | import React from 'react'
import { graphql, Link } from 'gatsby'
import Img from 'gatsby-image'
import { MDXRenderer } from 'gatsby-plugin-mdx'
import { useQuery, gql } from '@apollo/client'
const COMMENTS_QUERY = gql`
query PostCommentsQuery($id: ID!) {
comments(where: { post: { id: $id } }) {
id
content {
text
}
email
name
}
}
`
function BlogPostTemplate({
data: { authorImage, coverImage },
pageContext: { nextPost, page, previousPost },
}) {
const { data, error: commentsError, loading: commentsLoading } = useQuery(
COMMENTS_QUERY,
{
variables: { id: page.remoteId },
}
)
return (
<article>
<header className="pt-6 lg:pb-10">
<div className="space-y-1 text-center">
<dl className="space-y-10">
<div>
<dt className="sr-only">Published on</dt>
<dd className="text-base leading-6 font-medium text-gray-500">
<time dateTime={page.date}>{page.date}</time>
</dd>
</div>
</dl>
<div>
<h1 className="text-3xl leading-9 font-extrabold text-gray-900 tracking-tight sm:text-4xl sm:leading-10 md:text-5xl md:leading-14">
{page.title}
</h1>
</div>
</div>
</header>
<div
className="divide-y lg:divide-y-0 divide-gray-200 lg:grid lg:grid-cols-4 lg:col-gap-6 pb-16 lg:pb-20"
style={{ gridTemplateRows: 'auto 1fr' }}
>
<dl className="pt-6 pb-10 lg:pt-11 lg:border-b lg:border-gray-200">
<dt className="sr-only">Author</dt>
<dd>
<ul className="flex justify-center lg:block space-x-8 sm:space-x-12 lg:space-x-0 lg:space-y-8">
<li className="flex space-x-2">
<Img
fluid={authorImage.localFile.childImageSharp.fluid}
className="w-10 h-10 rounded-full"
fadeIn={false}
/>
<dl className="flex-1 text-sm font-medium leading-5">
<dt className="sr-only">Name</dt>
<dd className="text-gray-900">{page.author.name}</dd>
{page.author.title && (
<React.Fragment>
<dt className="sr-only">Title</dt>
<dd className="text-gray-500">{page.author.title}</dd>
</React.Fragment>
)}
</dl>
</li>
</ul>
</dd>
</dl>
<div className="divide-y divide-gray-200 lg:pb-0 lg:col-span-3 lg:row-span-2">
{coverImage && (
<Img
fluid={coverImage.localFile.childImageSharp.fluid}
className="mb-8 rounded"
fadeIn={false}
/>
)}
<div className="prose max-w-none pt-10 pb-8">
<MDXRenderer>{page.content.markdownNode.childMdx.body}</MDXRenderer>
</div>
<div>
<p>{commentsLoading ? 'Loading post comments' : null}</p>
<p>{commentsError ? 'Error loading post comments!' : null}</p>
{data?.comments.length ? (
<ul>
{data.comments.map((comment) => (
<div>
<p>{comment.email}</p>
<p>{comment.name}</p>
<p>{comment.content.text}</p>
</div>
))}
</ul>
) : (
<p>No comments (yet).</p>
)}
</div>
</div>
<footer className="text-sm font-medium leading-5 divide-y divide-gray-200 lg:col-start-1 lg:row-start-2">
{(nextPost || previousPost) && (
<div className="space-y-8 py-8">
{nextPost && (
<div>
<h2 className="text-xs tracking-wide uppercase text-gray-500">
Next Post
</h2>
<div className="text-purple-500 hover:text-purple-600">
<Link to={`/posts/${nextPost.slug}`}>{nextPost.title}</Link>
</div>
</div>
)}
{previousPost && (
<div>
<h2 className="text-xs tracking-wide uppercase text-gray-500">
Previous Post
</h2>
<div className="text-purple-500 hover:text-purple-600">
<Link to={`/posts/${previousPost.slug}`}>
{previousPost.title}
</Link>
</div>
</div>
)}
</div>
)}
<div className="pt-8">
<Link to="/" className="text-purple-500 hover:text-purple-600">
← Back to the blog
</Link>
</div>
</footer>
</div>
</article>
)
}
export const pageQuery = graphql`
fragment AssetFields on GraphCMS_Asset {
id
localFile {
childImageSharp {
fluid(maxWidth: 600) {
...GatsbyImageSharpFluid
}
}
}
}
query BlogPostQuery($id: String!) {
authorImage: graphCmsAsset(
authorAvatar: {
elemMatch: { posts: { elemMatch: { id: { in: [$id] } } } }
}
) {
...AssetFields
}
coverImage: graphCmsAsset(
coverImagePost: { elemMatch: { id: { eq: $id } } }
) {
...AssetFields
}
}
`
export default BlogPostTemplate
| ynnoj/2020-08-28-dynamic-content-in-gatsby | 2 | 📹 Dynamic content in Gatsby with Apollo Client | JavaScript | ynnoj | Jonathan Steele | stripe |
src/templates/default-page.js | JavaScript | import React from 'react'
import { MDXRenderer } from 'gatsby-plugin-mdx'
function DefaultPageTemplate({ pageContext: { page } }) {
return (
<div className="divide-y divide-gray-200">
<div className="pt-6 pb-8 space-y-2 md:space-y-5">
<h1 className="text-3xl leading-9 font-extrabold text-gray-900 tracking-tight sm:text-4xl sm:leading-10 md:text-6xl md:leading-14">
{page.title}
</h1>
{page.subtitle && (
<p className="text-lg leading-7 text-gray-500">{page.subtitle}</p>
)}
</div>
<div className="pb-16 lg:pb-20">
<div className="prose max-w-none pt-10 pb-8">
<MDXRenderer>{page.content.markdownNode.childMdx.body}</MDXRenderer>
</div>
</div>
</div>
)
}
export default DefaultPageTemplate
| ynnoj/2020-08-28-dynamic-content-in-gatsby | 2 | 📹 Dynamic content in Gatsby with Apollo Client | JavaScript | ynnoj | Jonathan Steele | stripe |
tailwind.config.js | JavaScript | module.exports = {
purge: [],
theme: {
extend: {
lineHeight: {
'11': '2.75rem',
'12': '3rem',
'13': '3.25rem',
'14': '3.5rem',
},
},
},
variants: {},
plugins: [require('@tailwindcss/typography'), require('@tailwindcss/ui')],
}
| ynnoj/2020-08-28-dynamic-content-in-gatsby | 2 | 📹 Dynamic content in Gatsby with Apollo Client | JavaScript | ynnoj | Jonathan Steele | stripe |
lib/graphCmsClient.js | JavaScript | import { GraphQLClient } from 'graphql-request'
export default new GraphQLClient(process.env.GRAPHCMS_ENDPOINT, {
headers: {
Authorization: `Bearer ${process.env.GRAPHCMS_TOKEN}`,
},
})
| ynnoj/2020-11-17-nextjs-internationalized-routing | 3 | 📹 Internationalized routing with Next.js | JavaScript | ynnoj | Jonathan Steele | stripe |
next.config.js | JavaScript | module.exports = {
i18n: {
locales: ['en', 'de'],
defaultLocale: 'en',
},
}
| ynnoj/2020-11-17-nextjs-internationalized-routing | 3 | 📹 Internationalized routing with Next.js | JavaScript | ynnoj | Jonathan Steele | stripe |
pages/[id].js | JavaScript | import { gql } from 'graphql-request'
import graphCmsClient from '../lib/graphCmsClient'
function ProductPage({ product }) {
return <pre>{JSON.stringify(product, null, 2)}</pre>
}
export async function getStaticPaths({ locales }) {
let paths = []
const { products } = await graphCmsClient.request(gql`
{
products {
id
}
}
`)
for (const locale of locales) {
paths = [
...paths,
...products.map((product) => ({ params: { id: product.id }, locale })),
]
}
return {
paths,
fallback: false,
}
}
export async function getStaticProps({ locale, params }) {
const { product } = await graphCmsClient.request(
gql`
query ProductPageQuery($id: ID!, $locale: Locale!) {
product(where: { id: $id }, locales: [$locale]) {
id
description
images {
height
url
width
}
locale
name
price
slug
}
}
`,
{ id: params.id, locale }
)
return {
props: {
product,
},
}
}
export default ProductPage
| ynnoj/2020-11-17-nextjs-internationalized-routing | 3 | 📹 Internationalized routing with Next.js | JavaScript | ynnoj | Jonathan Steele | stripe |
pages/_app.js | JavaScript | import Link from 'next/link'
import { useRouter } from 'next/router'
import '../styles/tailwind.css'
function App({ Component, pageProps }) {
const router = useRouter()
return (
<div>
<ul>
{router.locales.map((locale) => (
<li key={locale}>
<Link href={router.asPath} locale={locale}>
<a>{locale}</a>
</Link>
</li>
))}
</ul>
<Component {...pageProps} />
</div>
)
}
export default App
| ynnoj/2020-11-17-nextjs-internationalized-routing | 3 | 📹 Internationalized routing with Next.js | JavaScript | ynnoj | Jonathan Steele | stripe |
pages/index.js | JavaScript | import Link from 'next/link'
import { useRouter } from 'next/router'
import { gql } from 'graphql-request'
import graphCmsClient from '../lib/graphCmsClient'
function IndexPage({ products }) {
const router = useRouter()
return (
<div>
{products.map((product) => (
<div key={product.id}>
<Link href={product.id} locale={router.locale}>
<a>
<h1>{product.name}</h1>
</a>
</Link>
</div>
))}
</div>
)
}
export async function getStaticProps({ locale }) {
const { products } = await graphCmsClient.request(
gql`
query IndexPageQuery($locale: Locale!) {
products(locales: [$locale]) {
id
locale
name
price
slug
}
}
`,
{ locale }
)
return {
props: {
products,
},
}
}
export default IndexPage
| ynnoj/2020-11-17-nextjs-internationalized-routing | 3 | 📹 Internationalized routing with Next.js | JavaScript | ynnoj | Jonathan Steele | stripe |
postcss.config.js | JavaScript | module.exports = {
plugins: ['tailwindcss', 'postcss-preset-env'],
}
| ynnoj/2020-11-17-nextjs-internationalized-routing | 3 | 📹 Internationalized routing with Next.js | JavaScript | ynnoj | Jonathan Steele | stripe |
styles/tailwind.css | CSS | /* purgecss start ignore */
@tailwind base;
@tailwind components;
/* purgecss end ignore */
@tailwind utilities; | ynnoj/2020-11-17-nextjs-internationalized-routing | 3 | 📹 Internationalized routing with Next.js | JavaScript | ynnoj | Jonathan Steele | stripe |
tailwind.config.js | JavaScript | module.exports = {
future: {
removeDeprecatedGapUtilities: true,
purgeLayersByDefault: true,
},
purge: ['./pages/**/*.js'],
theme: {
extend: {},
},
variants: {},
plugins: [],
}
| ynnoj/2020-11-17-nextjs-internationalized-routing | 3 | 📹 Internationalized routing with Next.js | JavaScript | ynnoj | Jonathan Steele | stripe |
gatsby-node.js | JavaScript | exports.onPreBootstrap = ({ reporter }, pluginOptions) => {
if (!pluginOptions || !pluginOptions.clientId)
return reporter.panic(
'gatsby-plugin-smallchat: You must provide your Smallchat client ID'
)
}
| ynnoj/gatsby-plugin-smallchat | 0 | Plugin to add Smallchat to your Gatsby site | JavaScript | ynnoj | Jonathan Steele | stripe |
gatsby-ssr.js | JavaScript | import React from 'react'
export const onRenderBody = (
{ setPostBodyComponents },
{ async = true, clientId }
) => {
setPostBodyComponents([
<script
key="gatsby-plugin-smallchat"
src={`https://embed.small.chat/${clientId}.js`}
async={async}
/>
])
}
| ynnoj/gatsby-plugin-smallchat | 0 | Plugin to add Smallchat to your Gatsby site | JavaScript | ynnoj | Jonathan Steele | stripe |
index.js | JavaScript | // noop
| ynnoj/gatsby-plugin-smallchat | 0 | Plugin to add Smallchat to your Gatsby site | JavaScript | ynnoj | Jonathan Steele | stripe |
gatsby-node.js | JavaScript | exports.onPreBootstrap = ({ reporter }, pluginOptions) => {
if (!pluginOptions || !pluginOptions.accountId)
return reporter.panic(
'gatsby-plugin-vwo: You must provide your VWO account ID'
)
}
| ynnoj/gatsby-plugin-vwo | 0 | Plugin to add VWO to your Gatsby site | JavaScript | ynnoj | Jonathan Steele | stripe |
gatsby-ssr.js | JavaScript | import React from 'react'
export const onRenderBody = (
{ setHeadComponents },
{ accountId, async = true }
) => {
setHeadComponents([
<script
key="gatsby-plugin-vwo"
async={async}
dangerouslySetInnerHTML={{
__html: `
window._vwo_code = window._vwo_code || (function(){
var account_id=${accountId},
settings_tolerance=2000,
library_tolerance=2500,
use_existing_jquery=false,
is_spa=1,
hide_element='body',
f=false,d=document,code={use_existing_jquery:function(){return use_existing_jquery;},library_tolerance:function(){return library_tolerance;},finish:function(){if(!f){f=true;var a=d.getElementById('_vis_opt_path_hides');if(a)a.parentNode.removeChild(a);}},finished:function(){return f;},load:function(a){var b=d.createElement('script');b.src=a;b.type='text/javascript';b.innerText;b.onerror=function(){_vwo_code.finish();};d.getElementsByTagName('head')[0].appendChild(b);},init:function(){
window.settings_timer=setTimeout('_vwo_code.finish()',settings_tolerance);var a=d.createElement('style'),b=hide_element?hide_element+'{opacity:0 !important;filter:alpha(opacity=0) !important;background:none !important;}':'',h=d.getElementsByTagName('head')[0];a.setAttribute('id','_vis_opt_path_hides');a.setAttribute('type','text/css');if(a.styleSheet)a.styleSheet.cssText=b;else a.appendChild(d.createTextNode(b));h.appendChild(a);this.load('https://dev.visualwebsiteoptimizer.com/j.php?a='+account_id+'&u='+encodeURIComponent(d.URL)+'&f='+(+is_spa)+'&r='+Math.random());return settings_timer; }};window._vwo_settings_timer = code.init(); return code; }());`
}}
/>
])
}
| ynnoj/gatsby-plugin-vwo | 0 | Plugin to add VWO to your Gatsby site | JavaScript | ynnoj | Jonathan Steele | stripe |
index.js | JavaScript | // noop
| ynnoj/gatsby-plugin-vwo | 0 | Plugin to add VWO to your Gatsby site | JavaScript | ynnoj | Jonathan Steele | stripe |
prettier.config.js | JavaScript | module.exports = {
semi: false,
singleQuote: true,
trailingComma: 'none',
}
| ynnoj/gatsby-plugin-vwo | 0 | Plugin to add VWO to your Gatsby site | JavaScript | ynnoj | Jonathan Steele | stripe |
example/gatsby-config.js | JavaScript | require(`dotenv`).config()
module.exports = {
plugins: [
{
resolve: `@moltin/gatsby-theme-moltin`,
options: {
clientId: process.env.MOLTIN_CLIENT_ID,
},
},
],
}
| ynnoj/gatsby-theme-moltin | 9 | 🛍 Gatsby theme for building Moltin powered eCommerce websites | JavaScript | ynnoj | Jonathan Steele | stripe |
demo/gatsby-config.js | JavaScript | require('dotenv').config()
module.exports = {
siteMetadata: {
title: 'JSNE Demo',
description: 'Gatsby demo for JavaScript NE',
},
plugins: [
'gatsby-plugin-react-helmet',
'gatsby-plugin-styled-components',
'gatsby-transformer-remark',
{
resolve: 'gatsby-source-contentful',
options: {
spaceId: process.env.CONTENTFUL_SPACE,
accessToken: process.env.CONTENTFUL_TOKEN,
},
},
],
}
| ynnoj/jsne-talk-gatsby | 1 | 📣 Gatsby talk at JavaScript NE | ynnoj | Jonathan Steele | stripe | |
demo/gatsby-node.js | JavaScript | const path = require('path')
exports.createPages = ({ graphql, actions }) => {
const { createPage } = actions
return new Promise((resolve, reject) => {
graphql(`
{
allContentfulTalk {
edges {
node {
slug
}
}
}
}
`)
.then(result => {
if (result.errors) {
reject(result.errors)
}
const talkTemplate = path.resolve(`src/templates/talk.js`)
result.data.allContentfulTalk.edges.forEach(({ node: talk }) => {
createPage({
path: `/talks/${talk.slug}`,
component: talkTemplate,
context: {
slug: talk.slug,
},
})
})
})
.then(() => {
graphql(`
{
allContentfulEvent {
edges {
node {
slug
}
}
}
}
`).then(result => {
if (result.errors) {
reject(result.errors)
}
const eventTemplate = path.resolve(`src/templates/event.js`)
result.data.allContentfulEvent.edges.forEach(({ node: event }) => {
createPage({
path: `/events/${event.slug}`,
component: eventTemplate,
context: {
slug: event.slug,
},
})
})
})
})
.then(() => {
graphql(`
{
allContentfulSpeaker {
edges {
node {
slug
}
}
}
}
`).then(result => {
if (result.errors) {
reject(result.errors)
}
const speakerTemplate = path.resolve(`src/templates/speaker.js`)
result.data.allContentfulSpeaker.edges.forEach(
({ node: speaker }) => {
createPage({
path: `/speakers/${speaker.slug}`,
component: speakerTemplate,
context: {
slug: speaker.slug,
},
})
}
)
resolve()
})
})
})
}
| ynnoj/jsne-talk-gatsby | 1 | 📣 Gatsby talk at JavaScript NE | ynnoj | Jonathan Steele | stripe | |
demo/src/components/card.js | JavaScript | import React, { Component } from 'react'
import styled from 'styled-components'
const Card = styled.div`
border: 1px solid gray;
margin: 0 0.5rem;
padding: 1rem;
`
const Image = styled.div`
display: flex;
justify-content: center;
`
const Title = styled.h2`
color: #222;
`
export default class CardComponent extends Component {
renderImage() {
const { image, title } = this.props
if (image) {
return (
<Image>
<img src={image} alt={title} title={title} />
</Image>
)
}
}
render() {
const { children, title } = this.props
return (
<Card>
{this.renderImage()}
<Title>{title}</Title>
{children}
</Card>
)
}
}
| ynnoj/jsne-talk-gatsby | 1 | 📣 Gatsby talk at JavaScript NE | ynnoj | Jonathan Steele | stripe | |
demo/src/components/event.js | JavaScript | import React from 'react'
import styled from 'styled-components'
import Card from '../components/card'
const Description = styled.p`
color: silver;
`
export default ({ event: { date, title } }) => (
<Card title={title}>
<Description>{date}</Description>
</Card>
)
| ynnoj/jsne-talk-gatsby | 1 | 📣 Gatsby talk at JavaScript NE | ynnoj | Jonathan Steele | stripe | |
demo/src/components/grid.js | JavaScript | import React from 'react'
import styled from 'styled-components'
const Grid = styled.div`
display: flex;
margin: 0 -0.5rem;
`
export default ({ children }) => <Grid>{children}</Grid>
| ynnoj/jsne-talk-gatsby | 1 | 📣 Gatsby talk at JavaScript NE | ynnoj | Jonathan Steele | stripe | |
demo/src/components/header.js | JavaScript | import React from 'react'
import Link from 'gatsby-link'
import styled from 'styled-components'
const Header = styled.header`
align-items: center;
background-color: rebeccapurple;
display: flex;
flex: auto;
justify-content: space-between;
padding: 1rem;
`
const Title = styled.h1`
color: white;
margin-right: 2rem;
`
const Nav = styled.nav`
margin: 0 -0.5rem;
`
const StyledLink = styled(Link)`
color: white;
padding: 0 0.5rem;
text-decoration: none;
&.active {
text-decoration: underline;
}
`
export default ({ siteTitle }) => (
<Header>
<Title>
<Link
to="/"
style={{
color: 'white',
textDecoration: 'none',
}}
>
{siteTitle}
</Link>
</Title>
<Nav>
<StyledLink to="/talks" activeClassName="active">
Talks
</StyledLink>
<StyledLink to="/speakers" activeClassName="active">
Speakers
</StyledLink>
</Nav>
</Header>
)
| ynnoj/jsne-talk-gatsby | 1 | 📣 Gatsby talk at JavaScript NE | ynnoj | Jonathan Steele | stripe | |
demo/src/components/item.js | JavaScript | import React from 'react'
import styled from 'styled-components'
const Item = styled.li`
list-style: none;
margin-bottom: 1rem;
`
export default ({ children }) => <Item>{children}</Item>
| ynnoj/jsne-talk-gatsby | 1 | 📣 Gatsby talk at JavaScript NE | ynnoj | Jonathan Steele | stripe | |
demo/src/components/layout.js | JavaScript | import React from 'react'
import Helmet from 'react-helmet'
import { graphql, StaticQuery } from 'gatsby'
import styled, { injectGlobal } from 'styled-components'
import Header from './header'
injectGlobal`
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
margin: 0;
}
`
const Wrapper = styled.div`
display: flex;
flex-direction: ${props => (props.horizontal ? 'row' : 'column')};
padding: 1rem;
`
export default ({ horizontal, children, data }) => (
<StaticQuery
query={graphql`
query SiteTitleQuery {
site {
siteMetadata {
title
}
}
}
`}
render={data => (
<>
<Helmet
title={data.site.siteMetadata.title}
meta={[
{
name: 'description',
content: data.site.siteMetadata.description,
},
]}
/>
<Header siteTitle={data.site.siteMetadata.title} />
<Wrapper horizontal={horizontal}>{children}</Wrapper>
</>
)}
/>
)
| ynnoj/jsne-talk-gatsby | 1 | 📣 Gatsby talk at JavaScript NE | ynnoj | Jonathan Steele | stripe | |
demo/src/components/list.js | JavaScript | import React from 'react'
import styled from 'styled-components'
const List = styled.ul`
margin: 0;
padding: 0;
`
export default ({ children }) => <List>{children}</List>
| ynnoj/jsne-talk-gatsby | 1 | 📣 Gatsby talk at JavaScript NE | ynnoj | Jonathan Steele | stripe | |
demo/src/components/speaker.js | JavaScript | import React from 'react'
import styled from 'styled-components'
import Card from '../components/card'
const Description = styled.p`
color: silver;
`
export default ({
speaker: {
avatar: {
sizes: { src: image },
},
description: {
childMarkdownRemark: { html: description },
},
name,
},
}) => (
<Card image={image} title={name}>
<Description dangerouslySetInnerHTML={{ __html: description }} />
</Card>
)
| ynnoj/jsne-talk-gatsby | 1 | 📣 Gatsby talk at JavaScript NE | ynnoj | Jonathan Steele | stripe | |
demo/src/components/talk.js | JavaScript | import React from 'react'
import styled from 'styled-components'
import Card from '../components/card'
const Date = styled.p`
color: silver;
`
const Speaker = styled.p`
color: gray;
`
export default ({ talk: { date, title, speaker } }) => (
<Card title={title}>
<Speaker>{speaker.name}</Speaker>
<Date>{date}</Date>
</Card>
)
| ynnoj/jsne-talk-gatsby | 1 | 📣 Gatsby talk at JavaScript NE | ynnoj | Jonathan Steele | stripe | |
demo/src/components/title.js | JavaScript | import React from 'react'
import styled from 'styled-components'
const Title = styled.h2`
color: #333;
`
export default ({ title }) => <Title>{title}</Title>
| ynnoj/jsne-talk-gatsby | 1 | 📣 Gatsby talk at JavaScript NE | ynnoj | Jonathan Steele | stripe | |
demo/src/pages/index.js | JavaScript | import React from 'react'
import { graphql } from 'gatsby'
import Link from 'gatsby-link'
import styled from 'styled-components'
import Grid from '../components/grid'
import Layout from '../components/layout'
import Event from '../components/event'
import Title from '../components/title'
const StyledLink = styled(Link)`
color: currentColor;
text-decoration: none;
`
export default ({
data: {
allContentfulEvent: { edges: events },
},
}) => (
<Layout>
<Title title="Events" />
<Grid>
{events.map(({ node: event }) => {
return (
<StyledLink to={`/events/${event.slug}`} key={event.id}>
<Event event={event} />
</StyledLink>
)
})}
</Grid>
</Layout>
)
export const query = graphql`
query {
allContentfulEvent {
edges {
node {
date(formatString: "DD/MM/YY")
id
slug
title
}
}
}
}
`
| ynnoj/jsne-talk-gatsby | 1 | 📣 Gatsby talk at JavaScript NE | ynnoj | Jonathan Steele | stripe | |
demo/src/pages/speakers.js | JavaScript | import React from 'react'
import { graphql } from 'gatsby'
import Link from 'gatsby-link'
import styled from 'styled-components'
import Grid from '../components/grid'
import Layout from '../components/layout'
import Speaker from '../components/speaker'
import Title from '../components/title'
const StyledLink = styled(Link)`
color: currentColor;
text-decoration: none;
`
export default ({
data: {
allContentfulSpeaker: { edges: speakers },
},
}) => (
<Layout>
<Title title="Speakers" />
<Grid>
{speakers.map(({ node: speaker }) => {
return (
<StyledLink to={`/speakers/${speaker.slug}`} key={speaker.id}>
<Speaker speaker={speaker} />
</StyledLink>
)
})}
</Grid>
</Layout>
)
export const query = graphql`
query {
allContentfulSpeaker {
edges {
node {
avatar {
sizes(maxWidth: 200, quality: 100) {
src
}
}
description {
childMarkdownRemark {
html
}
}
id
name
slug
}
}
}
}
`
| ynnoj/jsne-talk-gatsby | 1 | 📣 Gatsby talk at JavaScript NE | ynnoj | Jonathan Steele | stripe | |
demo/src/pages/talks.js | JavaScript | import React from 'react'
import { graphql } from 'gatsby'
import Link from 'gatsby-link'
import styled from 'styled-components'
import Grid from '../components/grid'
import Layout from '../components/layout'
import Talk from '../components/talk'
import Title from '../components/title'
const StyledLink = styled(Link)`
color: currentColor;
text-decoration: none;
`
export default ({
data: {
allContentfulTalk: { edges: talks },
},
}) => (
<Layout>
<Title title="Talks" />
<Grid>
{talks.map(({ node: talk }) => {
return (
<StyledLink to={`/talks/${talk.slug}`} key={talk.id}>
<Talk talk={talk} />
</StyledLink>
)
})}
</Grid>
</Layout>
)
export const query = graphql`
query {
allContentfulTalk {
edges {
node {
date(formatString: "DD/MM/YY")
id
slug
speaker {
name
}
title
}
}
}
}
`
| ynnoj/jsne-talk-gatsby | 1 | 📣 Gatsby talk at JavaScript NE | ynnoj | Jonathan Steele | stripe | |
demo/src/templates/event.js | JavaScript | import React from 'react'
import styled from 'styled-components'
import { graphql } from 'gatsby'
import Link from 'gatsby-link'
import Layout from '../components/layout'
import List from '../components/list'
import ListItem from '../components/item'
import Title from '../components/title'
const Event = styled.div`
margin-right: 2rem;
width: 70%;
`
const Talks = styled.div`
width: 30%;
`
export default ({
data: {
contentfulEvent: { date, title, talk },
},
}) => (
<Layout horizontal>
<Event>
<Title title={title} />
<p>{date}</p>
</Event>
<Talks>
<Title title="Talks" />
<List>
{talk.map(talk => {
return (
<ListItem key={talk.id}>
<Link to={`/talks/${talk.slug}`}>{talk.title}</Link>
</ListItem>
)
})}
</List>
</Talks>
</Layout>
)
export const query = graphql`
query eventQuery($slug: String!) {
contentfulEvent(slug: { eq: $slug }) {
date(formatString: "DD/MM/YY")
talk {
id
slug
speaker {
name
}
title
}
title
}
}
`
| ynnoj/jsne-talk-gatsby | 1 | 📣 Gatsby talk at JavaScript NE | ynnoj | Jonathan Steele | stripe | |
demo/src/templates/speaker.js | JavaScript | import React from 'react'
import styled from 'styled-components'
import { graphql } from 'gatsby'
import Link from 'gatsby-link'
import Layout from '../components/layout'
import List from '../components/list'
import ListItem from '../components/item'
import Title from '../components/title'
const Speaker = styled.div`
margin-right: 2rem;
width: 70%;
`
const Talks = styled.div`
width: 30%;
`
export default ({
data: {
contentfulSpeaker: {
avatar: {
sizes: { src: image },
},
description: {
childMarkdownRemark: { html: description },
},
name,
talk,
},
},
}) => (
<Layout horizontal>
<Speaker>
<img src={image} alt={name} title={name} />
<Title title={name} />
<p dangerouslySetInnerHTML={{ __html: description }} />
</Speaker>
<Talks>
<Title title="Talks" />
<List>
{talk.map(talk => {
return (
<ListItem key={talk.id}>
<Link to={`/talks/${talk.slug}`}>{talk.title}</Link>
</ListItem>
)
})}
</List>
</Talks>
</Layout>
)
export const query = graphql`
query speakerQuery($slug: String!) {
contentfulSpeaker(slug: { eq: $slug }) {
avatar {
sizes(maxWidth: 200, quality: 100) {
src
}
}
description {
childMarkdownRemark {
html
}
}
name
talk {
id
slug
title
}
}
}
`
| ynnoj/jsne-talk-gatsby | 1 | 📣 Gatsby talk at JavaScript NE | ynnoj | Jonathan Steele | stripe | |
demo/src/templates/talk.js | JavaScript | import React from 'react'
import styled from 'styled-components'
import { graphql } from 'gatsby'
import Link from 'gatsby-link'
import Layout from '../components/layout'
import Title from '../components/title'
const Talk = styled.div`
margin-right: 2rem;
width: 70%;
`
const Meta = styled.div`
width: 30%;
`
export default ({
data: {
contentfulTalk: {
title,
description: {
childMarkdownRemark: { html: description },
},
event,
speaker: { name, slug },
},
},
}) => (
<Layout horizontal>
<Talk>
<Title title={title} />
<p dangerouslySetInnerHTML={{ __html: description }} />
</Talk>
<Meta>
<Title title="Speaker" />
<Link to={`/speakers/${slug}`}>{name}</Link>
<Title title="Event" />
<Link to={`/events/${event.slug}`}>{event.title}</Link>
</Meta>
</Layout>
)
export const query = graphql`
query talkQuery($slug: String!) {
contentfulTalk(slug: { eq: $slug }) {
description {
childMarkdownRemark {
html
}
}
event {
slug
title
}
title
speaker {
name
slug
}
}
}
`
| ynnoj/jsne-talk-gatsby | 1 | 📣 Gatsby talk at JavaScript NE | ynnoj | Jonathan Steele | stripe | |
client.js | JavaScript | module.exports = require('./dist/client').default
| ynnoj/next-stripe | 564 | Simplified server-side Stripe workflows in Next.js | JavaScript | ynnoj | Jonathan Steele | stripe |
index.js | JavaScript | module.exports = require('./dist/server')
| ynnoj/next-stripe | 564 | Simplified server-side Stripe workflows in Next.js | JavaScript | ynnoj | Jonathan Steele | stripe |
prettier.config.js | JavaScript | module.exports = {
semi: false,
singleQuote: true,
trailingComma: 'none',
}
| ynnoj/next-stripe | 564 | Simplified server-side Stripe workflows in Next.js | JavaScript | ynnoj | Jonathan Steele | stripe |
release.config.js | JavaScript | module.exports = {
branches: ['main', { name: 'beta', prerelease: true }]
}
| ynnoj/next-stripe | 564 | Simplified server-side Stripe workflows in Next.js | JavaScript | ynnoj | Jonathan Steele | stripe |
src/client/index.js | JavaScript | import fetcher from '../lib/fetcher'
async function confirmPaymentIntent(id, body) {
return await fetcher({
body: { id, body },
method: 'POST',
url: `/api/stripe/confirm/payment-intent`
})
}
async function createBillingPortalSession(body) {
return await fetcher({
body,
method: 'POST',
url: `/api/stripe/create/billing-portal-session`
})
}
async function createCheckoutSession(body) {
return await fetcher({
body,
method: 'POST',
url: `/api/stripe/create/checkout-session`
})
}
async function createPaymentIntent(body) {
return await fetcher({
body,
method: 'POST',
url: `/api/stripe/create/payment-intent`
})
}
async function retrievePaymentIntent(id) {
return await fetcher({
body: { id },
method: 'GET',
url: `/api/stripe/retrieve/payment-intent`
})
}
async function updatePaymentIntent(id, body) {
return await fetcher({
body: { id, body },
method: 'POST',
url: `/api/stripe/update/payment-intent`
})
}
export default {
confirmPaymentIntent,
createBillingPortalSession,
createCheckoutSession,
createPaymentIntent,
retrievePaymentIntent,
updatePaymentIntent
}
| ynnoj/next-stripe | 564 | Simplified server-side Stripe workflows in Next.js | JavaScript | ynnoj | Jonathan Steele | stripe |
src/lib/fetcher.js | JavaScript | async function fetcher({ body, method = 'GET', url }) {
const res = await fetch(url, {
method,
headers: new Headers({ 'Content-Type': 'application/json' }),
...(body && { body: JSON.stringify(body) })
})
if (!res.ok) {
const error = new Error('An error occurred while performing this request.')
error.info = await res.json()
error.status = res.status
throw error
}
return res.json()
}
export default fetcher
| ynnoj/next-stripe | 564 | Simplified server-side Stripe workflows in Next.js | JavaScript | ynnoj | Jonathan Steele | stripe |
src/server/index.js | JavaScript | import * as routes from './routes'
async function NextStripeHandler(req, res, options) {
if (!req.query.nextstripe)
return res
.status(500)
.end(`Error: Cannot find [...nextstripe].js in pages/api/stripe`)
const [method, type] = req.query.nextstripe
if (method === 'confirm') {
switch (type) {
case 'payment-intent':
return routes.confirmPaymentIntent(req, res, options)
}
} else if (method === 'create') {
switch (type) {
case 'billing-portal-session':
return routes.createBillingPortalSession(req, res, options)
case 'checkout-session':
return routes.createCheckoutSession(req, res, options)
case 'payment-intent':
return routes.createPaymentIntent(req, res, options)
}
} else if (method === 'retrieve') {
switch (type) {
case 'payment-intent':
return routes.retrievePaymentIntent(req, res, options)
}
} else if (method === 'update') {
switch (type) {
case 'payment-intent':
return routes.updatePaymentIntent(req, res, options)
}
}
}
export default function NextStripe (...args) {
if (args.length === 1) {
return (req, res) => NextStripeHandler(req, res, args[0])
}
return NextStripeHandler(...args)
}
| ynnoj/next-stripe | 564 | Simplified server-side Stripe workflows in Next.js | JavaScript | ynnoj | Jonathan Steele | stripe |
src/server/routes/confirm/payment-intent.js | JavaScript | import Stripe from 'stripe'
export default async function confirmPaymentIntent(req, res, options) {
try {
const stripe = new Stripe(options.stripe_key)
const { id, body } = req.body
const paymentIntent = await stripe.paymentIntents.confirm(id, body)
res.status(201).json(paymentIntent)
} catch ({ statusCode, raw: { message } }) {
res.status(statusCode).json({ message, status: statusCode })
}
}
| ynnoj/next-stripe | 564 | Simplified server-side Stripe workflows in Next.js | JavaScript | ynnoj | Jonathan Steele | stripe |
src/server/routes/create/billing-portal-session.js | JavaScript | import Stripe from 'stripe'
export default async function createBillingPortalSession(req, res, options) {
try {
const stripe = new Stripe(options.stripe_key)
const session = await stripe.billingPortal.sessions.create(req.body)
res.status(201).json(session)
} catch ({ statusCode, raw: { message } }) {
res.status(statusCode).json({ message, status: statusCode })
}
}
| ynnoj/next-stripe | 564 | Simplified server-side Stripe workflows in Next.js | JavaScript | ynnoj | Jonathan Steele | stripe |
src/server/routes/create/checkout-session.js | JavaScript | import Stripe from 'stripe'
export default async function createCheckoutSession(req, res, options) {
try {
const stripe = new Stripe(options.stripe_key)
const session = await stripe.checkout.sessions.create(req.body)
res.status(201).json(session)
} catch ({ statusCode, raw: { message } }) {
res.status(statusCode).json({ message, status: statusCode })
}
}
| ynnoj/next-stripe | 564 | Simplified server-side Stripe workflows in Next.js | JavaScript | ynnoj | Jonathan Steele | stripe |
src/server/routes/create/payment-intent.js | JavaScript | import Stripe from 'stripe'
export default async function createPaymentIntent(req, res, options) {
try {
const stripe = new Stripe(options.stripe_key)
const paymentIntent = await stripe.paymentIntents.create(req.body)
res.status(201).json(paymentIntent)
} catch ({ statusCode, raw: { message } }) {
res.status(statusCode).json({ message, status: statusCode })
}
}
| ynnoj/next-stripe | 564 | Simplified server-side Stripe workflows in Next.js | JavaScript | ynnoj | Jonathan Steele | stripe |
src/server/routes/index.js | JavaScript | // Confirm
export { default as confirmPaymentIntent } from './confirm/payment-intent'
// Create
export { default as createBillingPortalSession } from './create/billing-portal-session'
export { default as createCheckoutSession } from './create/checkout-session'
export { default as createPaymentIntent } from './create/payment-intent'
// Retrieve
export { default as retrievePaymentIntent } from './retrieve/payment-intent'
// Update
export { default as updatePaymentIntent } from './update/payment-intent'
| ynnoj/next-stripe | 564 | Simplified server-side Stripe workflows in Next.js | JavaScript | ynnoj | Jonathan Steele | stripe |
src/server/routes/retrieve/payment-intent.js | JavaScript | import Stripe from 'stripe'
export default async function retrievePaymentIntent(req, res, options) {
try {
const stripe = new Stripe(options.stripe_key)
const paymentIntent = await stripe.paymentIntents.retrieve(req.body.id)
res.status(200).json(paymentIntent)
} catch ({ statusCode, raw: { message } }) {
res.status(statusCode).json({ message, status: statusCode })
}
}
| ynnoj/next-stripe | 564 | Simplified server-side Stripe workflows in Next.js | JavaScript | ynnoj | Jonathan Steele | stripe |
src/server/routes/update/payment-intent.js | JavaScript | import Stripe from 'stripe'
export default async function updatePaymentIntent(req, res, options) {
try {
const stripe = new Stripe(options.stripe_key)
const { id, body } = req.body
const paymentIntent = await stripe.paymentIntents.update(id, body)
res.status(200).json(paymentIntent)
} catch ({ statusCode, raw: { message } }) {
res.status(statusCode).json({ message, status: statusCode })
}
}
| ynnoj/next-stripe | 564 | Simplified server-side Stripe workflows in Next.js | JavaScript | ynnoj | Jonathan Steele | stripe |
Fastfox.js | JavaScript |
/****************************************************************************************
* Fastfox *
* "Non ducor duco" *
* priority: speedy browsing *
* version: 146 *
* url: https://github.com/yokoffing/Betterfox *
***************************************************************************************/
/****************************************************************************
* SECTION: GENERAL *
****************************************************************************/
// PREF: initial paint delay
// How long FF will wait before rendering the page (in ms)
// [NOTE] You may prefer using 250.
// [NOTE] Dark Reader users may want to use 1000 [3].
// [1] https://bugzilla.mozilla.org/show_bug.cgi?id=1283302
// [2] https://docs.google.com/document/d/1BvCoZzk2_rNZx3u9ESPoFjSADRI0zIPeJRXFLwWXx_4/edit#heading=h.28ki6m8dg30z
// [3] https://old.reddit.com/r/firefox/comments/o0xl1q/reducing_cpu_usage_of_dark_reader_extension/
// [4] https://reddit.com/r/browsers/s/wvNB7UVCpx
//user_pref("nglayout.initialpaint.delay", 5); // DEFAULT; formerly 250
//user_pref("nglayout.initialpaint.delay_in_oopif", 5); // DEFAULT
// PREF: Font rendering cache in Skia (32MB)
// Increases font cache size to improve performance on text-heavy websites.
// Especially beneficial for sites with many font faces or complex typography.
// [1] https://bugzilla.mozilla.org/show_bug.cgi?id=1239151#c2
user_pref("gfx.content.skia-font-cache-size", 32); // 32 MB; default=5; Chrome=20
// PREF: page reflow timer
// Rather than wait until a page has completely downloaded to display it to the user,
// web browsers will periodically render what has been received to that point.
// Because reflowing the page every time additional data is received slows down
// total page load time, a timer was added so that the page would not reflow too often.
// This preference specfies whether that timer is active.
// [1] https://kb.mozillazine.org/Content.notify.ontimer
// true = do not reflow pages at an interval any higher than that specified by content.notify.interval (default)
// false = reflow pages whenever new data is received
//user_pref("content.notify.ontimer", true); // DEFAULT
// PREF: content notification delay - notification interval (in microseconds) to avoid layout thrashing
// When Firefox is loading a page, it periodically reformats
// or "reflows" the page as it loads. The page displays new elements
// every 0.12 seconds by default. These redraws increase the total page load time.
// The default value provides good incremental display of content
// without causing an increase in page load time.
// [NOTE] Lowering the interval will increase responsiveness
// but also increase the total load time.
// [WARNING] If this value is set below 1/10 of a second, it starts
// to impact page load performance.
// [EXAMPLE] 100000 = .10s = 100 reflows/second
// [1] https://searchfox.org/mozilla-central/rev/c1180ea13e73eb985a49b15c0d90e977a1aa919c/modules/libpref/init/StaticPrefList.yaml#1824-1834
// [2] https://web.archive.org/web/20240115073722/https://dev.opera.com/articles/efficient-javascript/?page=3#reflow
// [3] https://web.archive.org/web/20240115073722/https://dev.opera.com/articles/efficient-javascript/?page=3#smoothspeed
//user_pref("content.notify.interval", 100000); // (.10s); default=120000 (.12s)
//user_pref("content.max.tokenizing.time", 1000000); // (1.00s); alt=2000000; HIDDEN
//user_pref("content.interrupt.parsing", true); // HIDDEN
// PREF: UI responsiveness threshold
//user_pref("content.switch.threshold", 300000); // HIDDEN; default= 750000; alt=500000
// PREF: split text nodes to a length
// The number of bytes in a text node.
//user_pref("content.maxtextrun", 8191); // DEFAULT; HIDDEN
// PREF: new tab preload
// [WARNING] Disabling this may cause a delay when opening a new tab in Firefox.
// [1] https://wiki.mozilla.org/Tiles/Technical_Documentation#Ping
// [2] https://github.com/arkenfox/user.js/issues/1556
//user_pref("browser.newtab.preload", true); // DEFAULT
// PREF: disable EcoQoS [WINDOWS]
// Background tab processes use efficiency mode on Windows 11 to limit resource use.
// [WARNING] Leave this alone, unless you're on Desktop and you rely on
// background tabs to have maximum performance.
// [1] https://devblogs.microsoft.com/performance-diagnostics/introducing-ecoqos/
// [2] https://bugzilla.mozilla.org/show_bug.cgi?id=1796525
// [3] https://bugzilla.mozilla.org/show_bug.cgi?id=1800412
// [4] https://reddit.com/r/firefox/comments/107fj69/how_can_i_disable_the_efficiency_mode_on_firefox/
//user_pref("dom.ipc.processPriorityManager.backgroundUsesEcoQoS", false);
// PREF: control how tabs are loaded when a session is restored
// true=Tabs are not loaded until they are selected (default)
// false=Tabs begin to load immediately.
//user_pref("browser.sessionstore.restore_on_demand", true); // DEFAULT
//user_pref("browser.sessionstore.restore_pinned_tabs_on_demand", true);
//user_pref("browser.sessionstore.restore_tabs_lazily", true); // DEFAULT
// PREF: disable preSkeletonUI on startup [WINDOWS]
//user_pref("browser.startup.preXulSkeletonUI", false);
// PREF: lazy load iframes
//user_pref("dom.iframe_lazy_loading.enabled", true); // DEFAULT [FF121+]
// PREF: Prioritized Task Scheduling API
// [1] https://github.com/yokoffing/Betterfox/issues/355
// [2] https://blog.mozilla.org/performance/2022/06/02/prioritized-task-scheduling-api-is-prototyped-in-nightly/
// [3] https://medium.com/airbnb-engineering/building-a-faster-web-experience-with-the-posttask-scheduler-276b83454e91
// [4] https://github.com/WICG/scheduling-apis/blob/main/explainers/prioritized-post-task.md
// [5] https://wicg.github.io/scheduling-apis/
// [6] https://caniuse.com/mdn-api_taskcontroller
//user_pref("dom.enable_web_task_scheduling", true); // DEFAULT [FF142+]
/****************************************************************************
* SECTION: GFX RENDERING TWEAKS *
****************************************************************************/
// PREF: Webrender tweaks
// [1] https://searchfox.org/mozilla-central/rev/6e6332bbd3dd6926acce3ce6d32664eab4f837e5/modules/libpref/init/StaticPrefList.yaml#6202-6219
// [2] https://hacks.mozilla.org/2017/10/the-whole-web-at-maximum-fps-how-webrender-gets-rid-of-jank/
// [3] https://www.reddit.com/r/firefox/comments/tbphok/is_setting_gfxwebrenderprecacheshaders_to_true/i0bxs2r/
// [4] https://www.reddit.com/r/firefox/comments/z5auzi/comment/ixw65gb?context=3
// [5] https://gist.github.com/RubenKelevra/fd66c2f856d703260ecdf0379c4f59db?permalink_comment_id=4532937#gistcomment-4532937
//user_pref("gfx.webrender.all", true); // enables WR + additional features
//user_pref("gfx.webrender.precache-shaders", true); // longer initial startup time
//user_pref("gfx.webrender.compositor", true); // DEFAULT WINDOWS macOS
//user_pref("gfx.webrender.compositor.force-enabled", true); // enforce
// PREF: Webrender layer compositor
// [1] https://bugzilla.mozilla.org/show_bug.cgi?id=1945683
// [2] https://www.reddit.com/r/firefox/comments/1p58qre/firefox_is_getting_ready_to_make_youtube_fast/
// [3] https://www.ghacks.net/2025/11/24/these-two-tweaks-should-improve-firefoxs-performance-on-youtube-significantly/
user_pref("gfx.webrender.layer-compositor", true);
// If your PC uses an AMD GPU, you might want to make a second change.
// This one improves CPU usage on AMD systems.
//user_pref("media.wmf.zero-copy-nv12-textures-force-enabled", true);
// PREF: if your hardware doesn't support Webrender, you can fallback to Webrender's software renderer
// [1] https://www.ghacks.net/2020/12/14/how-to-find-out-if-webrender-is-enabled-in-firefox-and-how-to-enable-it-if-it-is-not/
//user_pref("gfx.webrender.software", true); // Software Webrender uses CPU instead of GPU
//user_pref("gfx.webrender.software.opengl", true); // LINUX
// PREF: GPU-accelerated Canvas2D
// Uses Accelerated Canvas2D for hardware acceleration of Canvas2D.
// This provides a consistent acceleration architecture across all platforms
// by utilizing WebGL instead of relying upon Direct2D.
// [WARNING] May cause issues on some Windows machines using integrated GPUs [2] [3]
// Add to your overrides if you have a dedicated GPU.
// [NOTE] Higher values will use more memory.
// [1] https://bugzilla.mozilla.org/show_bug.cgi?id=1741501
// [2] https://github.com/yokoffing/Betterfox/issues/153
// [3] https://github.com/yokoffing/Betterfox/issues/198
//user_pref("gfx.canvas.accelerated", true); // [DEFAULT FF133+]
user_pref("gfx.canvas.accelerated.cache-items", 32768); // [default=8192 FF135+]; Chrome=4096
user_pref("gfx.canvas.accelerated.cache-size", 4096); // default=256; Chrome=512
//user_pref("gfx.canvas.max-size", 32767); // DEFAULT=32767
// PREF: WebGL
user_pref("webgl.max-size", 16384); // default=1024
//user_pref("webgl.force-enabled", true);
// PREF: prefer GPU over CPU
// At best, the prefs do nothing on Linux/macOS.
// At worst, it'll result in crashes if the sandboxing is a WIP.
// [1] https://firefox-source-docs.mozilla.org/dom/ipc/process_model.html#gpu-process
//user_pref("layers.gpu-process.enabled", true); // DEFAULT WINDOWS
//user_pref("layers.gpu-process.force-enabled", true); // enforce
//user_pref("layers.mlgpu.enabled", true); // LINUX
//user_pref("media.hardware-video-decoding.enabled", true); // DEFAULT WINDOWS macOS
//user_pref("media.hardware-video-decoding.force-enabled", true); // enforce
//user_pref("media.gpu-process-decoder", true); // DEFAULT WINDOWS
//user_pref("media.ffmpeg.vaapi.enabled", true); // LINUX
// PREF: hardware and software decoded video overlay [FF116+]
// [1] https://bugzilla.mozilla.org/show_bug.cgi?id=1829063
// [2] https://phabricator.services.mozilla.com/D175993
//user_pref("gfx.webrender.dcomp-video-hw-overlay-win", true); // DEFAULT
//user_pref("gfx.webrender.dcomp-video-hw-overlay-win-force-enabled", true); // enforce
//user_pref("gfx.webrender.dcomp-video-sw-overlay-win", true); // DEFAULT
//user_pref("gfx.webrender.dcomp-video-sw-overlay-win-force-enabled", true); // enforce
/****************************************************************************
* SECTION: DISK CACHE *
****************************************************************************/
// PREF: disk cache
// [NOTE] If you think it helps performance, then feel free to override this.
// [SETTINGS] See about:cache
// More efficient to keep the browser cache instead of having to
// re-download objects for the websites you visit frequently.
// [1] https://www.janbambas.cz/new-firefox-http-cache-enabled/
user_pref("browser.cache.disk.enable", false);
// PREF: disk cache size
// [1] https://bugzilla.mozilla.org/buglist.cgi?bug_id=913808,968106,968101
// [2] https://rockridge.hatenablog.com/entry/2014/09/15/165501
// [3] https://www.reddit.com/r/firefox/comments/17oqhw3/firefox_and_ssd_disk_consumption/
//user_pref("browser.cache.disk.smart_size.enabled", false); // force a fixed max cache size on disk
//user_pref("browser.cache.disk.capacity", 512000); // default=256000; size of disk cache; 1024000=1GB, 2048000=2GB
//user_pref("browser.cache.disk.max_entry_size", 51200); // DEFAULT (50 MB); maximum size of an object in disk cache
// PREF: Race Cache With Network (RCWN) [FF59+]
// [ABOUT] about:networking#rcwn
// Firefox concurrently sends requests for cached resources to both the
// local disk cache and the network server. The browser uses whichever
// result arrives first and cancels the other request. This approach sometimes
// loads pages faster because the network can be quicker than accessing the cache
// on a hard drive. When RCWN is enabled, the request might be served from
// the server even if you have valid entry in the cache. Set to false if your
// intention is to increase cache usage and reduce network usage.
// [1] https://slides.com/valentingosu/race-cache-with-network-2017
// [2] https://simonhearne.com/2020/network-faster-than-cache/
// [3] https://support.mozilla.org/en-US/questions/1267945
// [4] https://askubuntu.com/questions/1214862/36-syns-in-a-row-how-to-limit-firefox-connections-to-one-website
// [5] https://bugzilla.mozilla.org/show_bug.cgi?id=1622859
// [6] https://soylentnews.org/comments.pl?noupdate=1&sid=40195&page=1&cid=1067867#commentwrap
//user_pref("network.http.rcwn.enabled", false);
// PREF: attempt to RCWN only if a resource is smaller than this size
//user_pref("network.http.rcwn.small_resource_size_kb", 256); // DEFAULT
// PREF: cache memory pool
// Cache v2 provides a memory pool that stores metadata (such as response headers)
// for recently read cache entries [1]. It is managed by a cache thread, and caches with
// metadata in the pool appear to be reused immediately.
// [1] https://bugzilla.mozilla.org/buglist.cgi?bug_id=986179
//user_pref("browser.cache.disk.metadata_memory_limit", 16384); // default=250 (0.25 MB); limit of recent metadata we keep in memory for faster access
// PREF: number of chunks we preload ahead of read
// Large content such as images will load faster.
// [1] https://bugzilla.mozilla.org/buglist.cgi?bug_id=913819,988318
// [2] http://www.janbambas.cz/new-firefox-http-cache-enabled/
//user_pref("browser.cache.disk.preload_chunk_count", 4); // DEFAULT
// PREF: the time period used to re-compute the frecency value of cache entries
// The frequency algorithm is used to select entries, and entries that are recently
// saved or frequently reused are retained. The frecency value determines how
// frequently a page has been accessed and is used by Firefox's cache algorithm.
// The frequency algorithm is used to select entries, and entries that are recently
// saved or frequently reused are retained. The frecency value determines how
// often a page has been accessed and is used by Firefox's cache algorithm.
// When the memory pool becomes full, the oldest data is purged. By default,
// data older than 6 hours is treated as old.
// [1] https://bugzilla.mozilla.org/buglist.cgi?bug_id=942835,1012327
// [2] https://bugzilla.mozilla.org/buglist.cgi?bug_id=913808,968101
//user_pref("browser.cache.frecency_half_life_hours", 6); // DEFAULT
// PREF: memory limit (in kB) for new cache data not yet written to disk
// Writes to the cache are buffered and written to disk on background with low priority.
// With a slow persistent storage, these buffers may grow when data is coming
// fast from the network. When the amount of unwritten data is exceeded, new
// writes will simply fail. We have two buckets, one for important data
// (priority) like html, css, fonts and js, and one for other data like images, video, etc.
//user_pref("browser.cache.disk.max_chunks_memory_usage", 40960); // DEFAULT (40 MB)
//user_pref("browser.cache.disk.max_priority_chunks_memory_usage", 40960); // DEFAULT (40 MB)
// PREF: how often to validate document in cache
// 0 = once-per-session
// 1 = each-time
// 2 = never
// 3 = when-appropriate/automatically (default)
//user_pref("browser.cache.check_doc_frequency", 3); // DEFAULT
// PREF: enforce free space checks
// When smartsizing is disabled, we could potentially fill all disk space by
// cache data when the disk capacity is not set correctly. To avoid that, we
// check the free space every time we write some data to the cache. The free
// space is checked against two limits. Once the soft limit is reached we start
// evicting the least useful entries, when we reach the hard limit writing to
// the entry fails.
//user_pref("browser.cache.disk.free_space_soft_limit", 10240); // default=5120 (5 MB)
//user_pref("browser.cache.disk.free_space_hard_limit", 2048); // default=1024 (1 MB)
// PREF: compression level for cached JavaScript bytecode [FF102+]
// [1] https://github.com/yokoffing/Betterfox/issues/247
// 0 = do not compress (default)
// 1 = minimal compression
// 9 = maximal compression
//user_pref("browser.cache.jsbc_compression_level", 3);
// PREF: strategy to use for when the bytecode should be encoded and saved [TESTING ONLY]
// -1 makes page load times marginally longer when a page is being loaded for the first time, while
// subsequent reload of websites will be much much faster.
// 0 means that the bytecode is created every 4 page loads [3].
// [1] https://searchfox.org/mozilla-release/source/modules/libpref/init/StaticPrefList.yaml#3461-3488
// [2] https://www.reddit.com/r/firefox/comments/12786yv/improving_performance_in_firefox_android_part_ii/
// [3] https://github.com/zen-browser/desktop/issues/217
// -1 = saved as soon as the script is seen for the first time, independently of the size or last access time
// 0 = saved in order to minimize the page-load time (default)
//user_pref("dom.script_loader.bytecode_cache.enabled", true); // DEFAULT
//user_pref("dom.script_loader.bytecode_cache.strategy", 0); // DEFAULT
/****************************************************************************
* SECTION: MEMORY CACHE *
****************************************************************************/
// PREF: memory cache
// The "automatic" size selection (default) is based on a decade-old table
// that only contains settings for systems at or below 8GB of system memory [1].
// Waterfox G6 allows it to go above 8GB machines [3].
// Value can be up to the max size of an unsigned 64-bit integer.
// -1 = Automatically decide the maximum memory to use to cache decoded images,
// messages, and chrome based on the total amount of RAM
// For machines with 8GB+ RAM, that equals 32768 kb = 32 MB
// [1] https://kb.mozillazine.org/Browser.cache.memory.capacity#-1
// [2] https://searchfox.org/mozilla-central/source/netwerk/cache2/CacheObserver.cpp#94-125
// [3] https://github.com/WaterfoxCo/Waterfox/commit/3fed16932c80a2f6b37d126fe10aed66c7f1c214
user_pref("browser.cache.memory.capacity", 131072); // 128 MB RAM cache; alt=65536 (65 MB RAM cache); default=32768
user_pref("browser.cache.memory.max_entry_size", 20480); // 20 MB max entry; default=5120 (5 MB)
// PREF: amount of Back/Forward cached pages stored in memory for each tab
// Pages that were recently visited are stored in memory in such a way
// that they don't have to be re-parsed. This improves performance
// when pressing Back and Forward. This pref limits the maximum
// number of pages stored in memory. If you are not using the Back
// and Forward buttons that much, but rather using tabs, then there
// is no reason for Firefox to keep memory for this.
// -1=determine automatically (8 pages)
// [1] https://kb.mozillazine.org/Browser.sessionhistory.max_total_viewers#Possible_values_and_their_effects
user_pref("browser.sessionhistory.max_total_viewers", 4); // default=8
user_pref("browser.sessionstore.max_tabs_undo", 10); // default=25
//user_pref("browser.sessionstore.max_entries", 10); // [HIDDEN OR REMOVED]
//user_pref("dom.storage.default_quota", 20480); // 20MB; default=5120
//user_pref("dom.storage.shadow_writes", true);
// PREF: tell garbage collector to start running when javascript is using xx MB of memory
// Garbage collection releases memory back to the system.
//user_pref("javascript.options.mem.high_water_mark", 128); // DEFAULT [HIDDEN OR REMOVED]
/****************************************************************************
* SECTION: MEDIA CACHE *
****************************************************************************/
// PREF: media disk cache
//user_pref("media.cache_size", 512000); // DEFAULT
// PREF: media memory cache
// [1] https://hg.mozilla.org/mozilla-central/file/tip/modules/libpref/init/StaticPrefList.yaml#l9652
// [2] https://github.com/arkenfox/user.js/pull/941#issuecomment-668278121
user_pref("media.memory_cache_max_size", 262144); // 256 MB; default=8192; AF=65536
// PREF: media cache combine sizes
user_pref("media.memory_caches_combined_limit_kb", 1048576); // 1GB; default=524288
//user_pref("media.memory_caches_combined_limit_pc_sysmem", 5); // DEFAULT; alt=10; the percentage of system memory that Firefox can use for media caches
// PREF: Media Source Extensions (MSE) web standard
// Disabling MSE allows videos to fully buffer, but you're limited to 720p.
// [WARNING] Disabling MSE may break certain videos.
// false=Firefox plays the old WebM format
// true=Firefox plays the new WebM format (default)
// [1] https://support.mozilla.org/en-US/questions/1008271
//user_pref("media.mediasource.enabled", true); // DEFAULT
// PREF: adjust video buffering periods when not using MSE (in seconds)
// [NOTE] Does not affect videos over 720p since they use DASH playback [1]
// [1] https://lifehacker.com/preload-entire-youtube-videos-by-disabling-dash-playbac-1186454034
user_pref("media.cache_readahead_limit", 600); // 10 min; default=60; stop reading ahead when our buffered data is this many seconds ahead of the current playback
user_pref("media.cache_resume_threshold", 300); // 5 min; default=30; when a network connection is suspended, don't resume it until the amount of buffered data falls below this threshold
/****************************************************************************
* SECTION: IMAGE CACHE *
****************************************************************************/
// PREF: image cache
user_pref("image.cache.size", 10485760); // (cache images up to 10MiB in size) [DEFAULT 5242880]
user_pref("image.mem.decode_bytes_at_a_time", 65536); // default=16384; alt=32768; chunk size for calls to the image decoders
//user_pref("image.mem.max_decoded_image_kb", 512000); // 500MB [HIDDEN OR REMOVED?]
// PREF: set minimum timeout to unmap shared surfaces since they have been last used
// [NOTE] This is only used on 32-bit builds of Firefox where there is meaningful
// virtual address space pressure.
// [1] https://phabricator.services.mozilla.com/D109440
// [2] https://bugzilla.mozilla.org/show_bug.cgi?id=1699224
//user_pref("image.mem.shared.unmap.min_expiration_ms", 120000); // default=60000; minimum timeout to unmap shared surfaces since they have been last used
/****************************************************************************
* SECTION: NETWORK *
****************************************************************************/
// PREF: use bigger packets
// [WARNING] Cannot open HTML files bigger than 4MB if value is too large [2].
// Reduce Firefox's CPU usage by requiring fewer application-to-driver data transfers.
// However, it does not affect the actual packet sizes transmitted over the network.
// [1] https://www.mail-archive.com/support-seamonkey@lists.mozilla.org/msg74561.html
// [2] https://github.com/yokoffing/Betterfox/issues/279
// [3] https://ra1ahq.blog/en/optimizaciya-proizvoditelnosti-mozilla-firefox
//user_pref("network.buffer.cache.size", 65535); // default=32768 (32 kb); 262144 too large
//user_pref("network.buffer.cache.count", 48); // default=24; 128 too large
// PREF: increase the absolute number of HTTP connections
// [1] https://kb.mozillazine.org/Network.http.max-connections
// [2] https://kb.mozillazine.org/Network.http.max-persistent-connections-per-server
// [3] https://www.reddit.com/r/firefox/comments/11m2yuh/how_do_i_make_firefox_use_more_of_my_900_megabit/jbfmru6/
user_pref("network.http.max-connections", 1800); // default=900
user_pref("network.http.max-persistent-connections-per-server", 10); // default=6; download connections; anything above 10 is excessive
user_pref("network.http.max-urgent-start-excessive-connections-per-host", 5); // default=3
//user_pref("network.http.max-persistent-connections-per-proxy", 48); // default=32
user_pref("network.http.request.max-start-delay", 5); // default=10
//user_pref("network.websocket.max-connections", 200); // DEFAULT
// PREF: pacing requests [FF23+]
// Controls how many HTTP requests are sent at a time.
// Pacing HTTP requests can have some benefits, such as reducing network congestion,
// improving web page loading speed, and avoiding server overload.
// Pacing requests adds a slight delay between requests to throttle them.
// If you have a fast machine and internet connection, disabling pacing
// may provide a small speed boost when loading pages with lots of requests.
// false = Firefox will send as many requests as possible without pacing
// true = Firefox will pace requests (default)
user_pref("network.http.pacing.requests.enabled", false);
//user_pref("network.http.pacing.requests.min-parallelism", 10); // default=6
//user_pref("network.http.pacing.requests.burst", 32); // default=10
// PREF: increase DNS cache
// [1] https://developer.mozilla.org/en-US/docs/Web/Performance/Understanding_latency
user_pref("network.dnsCacheEntries", 10000); // default=800
// PREF: adjust DNS expiration time
// [ABOUT] about:networking#dns
// [NOTE] These prefs will be ignored by DNS resolver if using DoH/TRR.
user_pref("network.dnsCacheExpiration", 3600); // keep entries for 1 hour; default=60
//user_pref("network.dnsCacheExpirationGracePeriod", 120); // default=60; cache DNS entries for 2 minutes after they expire
// PREF: the number of threads for DNS
//user_pref("network.dns.max_high_priority_threads", 40); // DEFAULT [FF 123?]
//user_pref("network.dns.max_any_priority_threads", 24); // DEFAULT [FF 123?]
// PREF: increase TLS token caching
user_pref("network.ssl_tokens_cache_capacity", 10240); // default=2048; more TLS token caching (fast reconnects)
/****************************************************************************
* SECTION: SPECULATIVE LOADING *
****************************************************************************/
// These are connections that are not explicitly asked for (e.g., clicked on).
// [1] https://developer.mozilla.org/en-US/docs/Web/Performance/Speculative_loading
// [NOTE] FF85+ partitions (isolates) pooled connections, prefetch connections,
// pre-connect connections, speculative connections, TLS session identifiers,
// and other connections. We can take advantage of the speed of pre-connections
// while preserving privacy. Users may relax hardening to maximize their preference.
// For more information, see SecureFox: "PREF: State Paritioning" and "PREF: Network Partitioning".
// [NOTE] To activate and increase network predictions, go to settings in uBlock Origin and uncheck:
// - "Disable pre-fetching (to prevent any connection for blocked network requests)"
// [NOTE] Add prefs to "MY OVERRIDES" section and uncomment to enable them in your user.js.
// PREF: link-mouseover opening connection to linked server
// When accessing content online, devices use sockets as endpoints.
// The global limit on half-open sockets controls how many speculative
// connection attempts can occur at once when starting new connections [3].
// If the user follows through, pages can load faster since some
// work was done in advance. Firefox opens predictive connections
// to sites when hovering over New Tab thumbnails or starting a
// URL Bar search [1] and hyperlinks within a page [2].
// [NOTE] DNS (if enabled), TCP, and SSL handshakes are set up in advance,
// but page contents are not downloaded until a click on the link is registered.
// [1] https://support.mozilla.org/en-US/kb/how-stop-firefox-making-automatic-connections?redirectslug=how-stop-firefox-automatically-making-connections&redirectlocale=en-US#:~:text=Speculative%20pre%2Dconnections
// [2] https://news.slashdot.org/story/15/08/14/2321202/how-to-quash-firefoxs-silent-requests
// [3] https://searchfox.org/mozilla-central/rev/028c68d5f32df54bca4cf96376f79e48dfafdf08/modules/libpref/init/all.js#1280-1282
// [4] https://www.keycdn.com/blog/resource-hints#prefetch
// [5] https://3perf.com/blog/link-rels/#prefetch
user_pref("network.http.speculative-parallel-limit", 0);
// PREF: DNS prefetching for HTMLLinkElement <link rel="dns-prefetch">
// Used for cross-origin connections to provide small performance improvements.
// You can enable rel=dns-prefetch for the HTTPS document without prefetching
// DNS for anchors, whereas the latter makes more specualtive requests [5].
// [1] https://bitsup.blogspot.com/2008/11/dns-prefetching-for-firefox.html
// [2] https://css-tricks.com/prefetching-preloading-prebrowsing/#dns-prefetching
// [3] https://www.keycdn.com/blog/resource-hints#2-dns-prefetching
// [4] http://www.mecs-press.org/ijieeb/ijieeb-v7-n5/IJIEEB-V7-N5-2.pdf
// [5] https://bugzilla.mozilla.org/show_bug.cgi?id=1596935#c28
user_pref("network.dns.disablePrefetch", true);
user_pref("network.dns.disablePrefetchFromHTTPS", true); // [FF127+ false]
// PREF: DNS prefetch for HTMLAnchorElement (speculative DNS)
// Disable speculative DNS calls to prevent Firefox from resolving
// hostnames for other domains linked on a page. This may eliminate
// unnecessary DNS lookups, but can increase latency when following external links.
// [1] https://bugzilla.mozilla.org/show_bug.cgi?id=1596935#c28
// [2] https://github.com/arkenfox/user.js/issues/1870#issuecomment-2220773972
//user_pref("dom.prefetch_dns_for_anchor_http_document", false); // [FF128+]
//user_pref("dom.prefetch_dns_for_anchor_https_document", false); // DEFAULT [FF128+]
// PREF: enable <link rel="preconnect"> tag and Link: rel=preconnect response header handling
//user_pref("network.preconnect", true); // DEFAULT
// PREF: preconnect to the autocomplete URL in the address bar
// Whether to warm up network connections for autofill or search results.
// Firefox preloads URLs that autocomplete when a user types into the address bar.
// Connects to destination server ahead of time, to avoid TCP handshake latency.
// [NOTE] Firefox will perform DNS lookup (if enabled) and TCP and TLS handshake,
// but will not start sending or receiving HTTP data.
// [1] https://www.ghacks.net/2017/07/24/disable-preloading-firefox-autocomplete-urls/
user_pref("browser.urlbar.speculativeConnect.enabled", false);
// PREF: mousedown speculative connections on bookmarks and history [FF98+]
// Whether to warm up network connections for places:menus and places:toolbar.
user_pref("browser.places.speculativeConnect.enabled", false);
// PREF: network module preload <link rel="modulepreload"> [FF115+]
// High-priority loading of current page JavaScript modules.
// Used to preload high-priority JavaScript modules for strategic performance improvements.
// Module preloading allows developers to fetch JavaScript modules and dependencies
// earlier to accelerate page loads. The browser downloads, parses, and compiles modules
// referenced by links with this attribute in parallel with other resources, rather
// than sequentially waiting to process each. Preloading reduces overall download times.
// Browsers may also automatically preload dependencies without firing extra events.
// Unlike other pre-connection tags (except rel=preload), this tag is mandatory for the browser.
// [1] https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/rel/modulepreload
//user_pref("network.modulepreload", true); // DEFAULT
// PREF: link prefetching <link rel="prefetch">
// Pre-populates the HTTP cache by prefetching same-site future navigation
// resources or subresources used on those pages.
// Enabling link prefetching allows Firefox to preload pages tagged as important.
// The browser prefetches links with the prefetch-link tag, fetching resources
// likely needed for the next navigation at low priority. When clicking a link
// or loading a new page, prefetching stops and discards hints. Prefetching
// downloads resources without executing them.
// [NOTE] Since link prefetch uses the HTTP cache, it has a number of issues
// with document prefetches, such as being potentially blocked by Cache-Control headers
// (e.g. cache partitioning).
// [1] https://developer.mozilla.org/en-US/docs/Glossary/Prefetch
// [2] http://www.mecs-press.org/ijieeb/ijieeb-v7-n5/IJIEEB-V7-N5-2.pdf
// [3] https://timkadlec.com/remembers/2020-06-17-prefetching-at-this-age/
// [4] https://3perf.com/blog/link-rels/#prefetch
// [5] https://developer.mozilla.org/docs/Web/HTTP/Link_prefetching_FAQ
user_pref("network.prefetch-next", false);
// PREF: Fetch Priority API [FF119+]
// Indicates whether the `fetchpriority` attribute for elements which support it.
// [1] https://web.dev/articles/fetch-priority
// [2] https://nitropack.io/blog/post/priority-hints
// [2] https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/fetchPriority
// [3] https://developer.mozilla.org/en-US/docs/Web/API/HTMLLinkElement/fetchPriority
//user_pref("network.fetchpriority.enabled", true);
// PREF: early hints [FF120+]
// [1] https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/103
// [2] https://developer.chrome.com/blog/early-hints/
// [3] https://blog.cloudflare.com/early-hints/
// [4] https://blog.cloudflare.com/early-hints-performance/
//user_pref("network.early-hints.enabled", true);
// PREF: `Link: rel=preconnect` in 103 Early Hint response [FF120+]
// Used to warm most critical cross-origin connections to provide
// performance improvements when connecting to them.
// [NOTE] When 0, this is limited by "network.http.speculative-parallel-limit".
//user_pref("network.early-hints.preconnect.enabled", true);
//user_pref("network.early-hints.preconnect.max_connections", 10); // DEFAULT
// PREF: Network Predictor (NP)
// When enabled, it trains and uses Firefox's algorithm to preload page resource
// by tracking past page resources. It uses a local file (history) of needed images,
// scripts, etc. to request them preemptively when navigating.
// [NOTE] By default, it only preconnects DNS, TCP, and SSL handshakes.
// No data sends until clicking. With "network.predictor.enable-prefetch" enabled,
// it also performs prefetches.
// [1] https://wiki.mozilla.org/Privacy/Reviews/Necko
// [2] https://www.ghacks.net/2014/05/11/seer-disable-firefox/
// [3] https://github.com/dillbyrne/random-agent-spoofer/issues/238#issuecomment-110214518
// [4] https://www.igvita.com/posa/high-performance-networking-in-google-chrome/#predictor
//user_pref("network.predictor.enabled", false); // [DEFAULT: false FF144+]
// PREF: Network Predictor fetch for resources ahead of time
// Prefetch page resources based on past user behavior.
//user_pref("network.predictor.enable-prefetch", false); // [FF48+] [DEFAULT: false]
// PREF: make Network Predictor active when hovering over links
// When hovering over links, Network Predictor uses past resource history to
// preemptively request what will likely be needed instead of waiting for the document.
// Predictive connections automatically open when hovering over links to speed up
// loading, starting some work in advance.
//user_pref("network.predictor.enable-hover-on-ssl", false); // DEFAULT
// PREF: assign Network Predictor confidence levels
// [NOTE] Keep in mind that Network Predictor must LEARN your browsing habits.
// Editing these lower will cause more speculative connections to occur,
// which reduces accuracy over time and has privacy implications.
//user_pref("network.predictor.preresolve-min-confidence", 60); // DEFAULT
//user_pref("network.predictor.preconnect-min-confidence", 90); // DEFAULT
//user_pref("network.predictor.prefetch-min-confidence", 100); // DEFAULT
// PREF: other Network Predictor values
// [NOTE] Keep in mind that Network Predictor must LEARN your browsing habits.
//user_pref("network.predictor.prefetch-force-valid-for", 10); // DEFAULT; how long prefetched resources are considered valid and usable (in seconds) for the prediction modeling
//user_pref("network.predictor.prefetch-rolling-load-count", 10); // DEFAULT; the maximum number of resources that Firefox will prefetch in memory at one time based on prediction modeling
//user_pref("network.predictor.max-resources-per-entry", 250); // default=100
//user_pref("network.predictor.max-uri-length", 1000); // default=500
/****************************************************************************
* SECTION: EXPERIMENTAL *
****************************************************************************/
// PREF: CSS Masonry Layout [NIGHTLY]
// [1] https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout/Masonry_Layout
// [2] https://www.smashingmagazine.com/native-css-masonry-layout-css-grid/
//user_pref("layout.css.grid-template-masonry-value.enabled", true);
/****************************************************************************
* SECTION: TAB UNLOAD *
****************************************************************************/
// PREF: unload tabs on low memory
// [ABOUT] about:unloads
// Firefox will detect if your computer’s memory is running low (less than 200MB)
// and suspend tabs that you have not used in awhile.
// [1] https://support.mozilla.org/en-US/kb/unload-inactive-tabs-save-system-memory-firefox
// [2] https://hacks.mozilla.org/2021/10/tab-unloading-in-firefox-93/
//user_pref("browser.tabs.unloadOnLowMemory", true); // DEFAULT
// PREF: determine when tabs unload [WINDOWS] [LINUX]
// Notify TabUnloader or send the memory pressure if the memory resource
// notification is signaled AND the available commit space is lower than
// this value (in MiB).
// Set this to some value, e.g. 4/5 of total memory available on your system:
// 4GB=3276, 8GB=6553, 16GB=13107, 32GB=25698, 64GB=52429
// [1] https://dev.to/msugakov/taking-firefox-memory-usage-under-control-on-linux-4b02
//user_pref("browser.low_commit_space_threshold_mb", 3276); // default=200; WINDOWS LINUX
// PREF: determine when tabs unload [LINUX]
// On Linux, Firefox checks available memory in comparison to total memory,
// and use this percent value (out of 100) to determine if Firefox is in a
// low memory scenario.
// [1] https://dev.to/msugakov/taking-firefox-memory-usage-under-control-on-linux-4b02
//user_pref("browser.low_commit_space_threshold_percent", 20); // default=5; LINUX
// PREF: determine how long (in ms) tabs are inactive before they unload
// 60000=1min; 300000=5min; 600000=10min (default)
//user_pref("browser.tabs.min_inactive_duration_before_unload", 300000); // 5min; default=600000
/****************************************************************************
* SECTION: PROCESS COUNT *
****************************************************************************/
// PREF: process count
// [ABOUT] View in about:processes.
// With Firefox Quantum (2017), CPU cores = processCount. However, since the
// introduction of Fission [2], the number of website processes is controlled
// by processCount.webIsolated. Disabling fission.autostart or changing
// fission.webContentIsolationStrategy reverts control back to processCount.
// [1] https://www.reddit.com/r/firefox/comments/r69j52/firefox_content_process_limit_is_gone/
// [2] https://firefox-source-docs.mozilla.org/dom/ipc/process_model.html#web-content-processes
//user_pref("dom.ipc.processCount", 8); // DEFAULT; Shared Web Content
//user_pref("dom.ipc.processCount.webIsolated", 1); // default=4; Isolated Web Content
//user_pref("dom.ipc.keepProcessesAlive.web", 4); // default=1 [HIDDEN OR REMOVED]
// PREF: use one process for process preallocation cache
//user_pref("dom.ipc.processPrelaunch.fission.number", 1); // default=3; Process Preallocation Cache
// PREF: configure process isolation
// [1] https://hg.mozilla.org/mozilla-central/file/tip/dom/ipc/ProcessIsolation.cpp#l53
// [2] https://www.reddit.com/r/firefox/comments/r69j52/firefox_content_process_limit_is_gone/
// OPTION 1: isolate all websites
// Web content is always isolated into its own `webIsolated` content process
// based on site-origin, and will only load in a shared `web` content process
// if site-origin could not be determined.
//user_pref("fission.webContentIsolationStrategy", 1); // DEFAULT
//user_pref("browser.preferences.defaultPerformanceSettings.enabled", true); // DEFAULT
//user_pref("dom.ipc.processCount.webIsolated", 1); // one process per site origin
// OPTION 2: isolate only "high value" websites
// Only isolates web content loaded by sites which are considered "high
// value". A site is considered high value if it has been granted a
// `highValue*` permission by the permission manager, which is done in
// response to certain actions.
//user_pref("fission.webContentIsolationStrategy", 2);
//user_pref("browser.preferences.defaultPerformanceSettings.enabled", false);
//user_pref("dom.ipc.processCount.webIsolated", 1); // one process per site origin (high value)
//user_pref("dom.ipc.processCount", 8); // determine by number of CPU cores/processors
// OPTION 3: do not isolate websites
// All web content is loaded into a shared `web` content process. This is
// similar to the non-Fission behavior; however, remote subframes may still
// be used for sites with special isolation behavior, such as extension or
// mozillaweb content processes.
//user_pref("fission.webContentIsolationStrategy", 0);
//user_pref("browser.preferences.defaultPerformanceSettings.enabled", false);
//user_pref("dom.ipc.processCount", 8); // determine by number of CPU cores/processors
| yokoffing/Betterfox | 10,046 | Firefox user.js for optimal privacy and security. Your favorite browser, but better. | JavaScript | yokoffing | ||
Peskyfox.js | JavaScript |
/****************************************************************************
* Peskyfox *
* "Aquila non capit muscas" *
* priority: remove annoyances *
* version: 146 *
* url: https://github.com/yokoffing/Betterfox *
* credit: Some prefs are reproduced and adapted from the arkenfox project *
* credit urL: https://github.com/arkenfox/user.js *
***************************************************************************/
/****************************************************************************
* SECTION: MOZILLA UI *
****************************************************************************/
// PREF: disable about:addons' Recommendations pane (uses Google Analytics)
user_pref("extensions.getAddons.showPane", false); // HIDDEN
// PREF: disable recommendations in about:addons' Extensions and Themes panes
user_pref("extensions.htmlaboutaddons.recommendations.enabled", false);
// PREF: Personalized Extension Recommendations in about:addons and AMO
// [NOTE] This pref has no effect when Health Reports are disabled.
// [SETTING] Privacy & Security>Firefox Data Collection & Use>Allow Firefox to make personalized extension recommendations
user_pref("browser.discovery.enabled", false);
// PREF: disable Firefox from asking to set as the default browser
// [1] https://github.com/yokoffing/Betterfox/issues/166
user_pref("browser.shell.checkDefaultBrowser", false);
// PREF: disable Extension Recommendations (CFR: "Contextual Feature Recommender")
// [1] https://support.mozilla.org/en-US/kb/extension-recommendations
user_pref("browser.newtabpage.activity-stream.asrouter.userprefs.cfr.addons", false);
user_pref("browser.newtabpage.activity-stream.asrouter.userprefs.cfr.features", false);
// PREF: hide "More from Mozilla" in Settings
user_pref("browser.preferences.moreFromMozilla", false);
// PREF: tab and about:config warnings
//user_pref("browser.tabs.warnOnClose", false); // DEFAULT [FF94+]
//user_pref("browser.tabs.warnOnCloseOtherTabs", true); // DEFAULT
//user_pref("browser.tabs.warnOnOpen", true); // DEFAULT
user_pref("browser.aboutConfig.showWarning", false);
// PREF: disable welcome notices
user_pref("browser.startup.homepage_override.mstone", "ignore");
user_pref("browser.aboutwelcome.enabled", false); // disable Intro screens
//user_pref("startup.homepage_welcome_url", "");
//user_pref("startup.homepage_welcome_url.additional", "");
//user_pref("startup.homepage_override_url", ""); // What's New page after updates
// PREF: disable "What's New" toolbar icon [FF69+]
//user_pref("browser.messaging-system.whatsNewPanel.enabled", false);
// PREF: new profile switcher
user_pref("browser.profiles.enabled", true);
// PREF: use native title bar buttons [LINUX]
// [1] https://github.com/yokoffing/Betterfox/issues/320
//user_pref("widget.gtk.non-native-titlebar-buttons.enabled", true);
// PREF: disable search engine switcher in the URL bar [FF136+]
//user_pref("browser.urlbar.scotchBonnet.enableOverride", false);
/****************************************************************************
* SECTION: THEME ADJUSTMENTS *
****************************************************************************/
// PREF: enable Firefox to use userChome, userContent, etc.
user_pref("toolkit.legacyUserProfileCustomizations.stylesheets", true);
// PREF: add compact mode back to options
user_pref("browser.compactmode.show", true);
// PREF: preferred color scheme for websites
// [SETTING] General>Language and Appearance>Website appearance
// By default, color scheme matches the theme of your browser toolbar (3).
// Set this pref to choose Dark on sites that support it (0) or Light (1).
// Before FF95, the pref was 2, which determined site color based on OS theme.
// Dark (0), Light (1), System (2), Browser (3) [DEFAULT FF95+]
// [1] https://www.reddit.com/r/firefox/comments/rfj6yc/how_to_stop_firefoxs_dark_theme_from_overriding/hoe82i5/?context=3
user_pref("layout.css.prefers-color-scheme.content-override", 2);
// PREF: disable always using dark theme for private browsing windows [FF106+]
//user_pref("browser.theme.dark-private-windows", false);
// PREF: prevent private windows being separate from normal windows in taskbar [WINDOWS] [FF106+]
user_pref("browser.privateWindowSeparation.enabled", false);
// PREF: show search bar [FF122+]
// Mozilla has removed the search bar option from the settings window.
//user_pref("browser.search.widget.inNavBar", true);
// PREF: new tab page wallpapers
//user_pref("browser.newtabpage.activity-stream.newtabWallpapers.v2.enabled", true); // [DEFAULT FF132+]
/****************************************************************************
* SECTION: AI *
****************************************************************************/
// PREF: AI master switch
// [1] https://github.com/yokoffing/Betterfox/issues/416
user_pref("browser.ml.enable", false);
// PREF: AI chat
user_pref("browser.ml.chat.enabled", false);
// PREF: AI chatbot option in right click menu
user_pref("browser.ml.chat.menu", false);
// PREF: AI-enhanced tab groups
// [1] https://support.mozilla.org/kb/how-use-ai-enhanced-tab-groups
user_pref("browser.tabs.groups.smart.enabled", false);
// PREF: link previews
user_pref("browser.ml.linkPreview.enabled", false);
/****************************************************************************
* SECTION: COOKIE BANNER HANDLING *
****************************************************************************/
// PREF: Cookie Banner handling
// [DEPRECIATED] Future of the project is unclear. See [5] and [6].
// [NOTE] Feature still enforces Total Cookie Protection to limit 3rd-party cookie tracking [1]
// [1] https://github.com/mozilla/cookie-banner-rules-list/issues/33#issuecomment-1318460084
// [2] https://phabricator.services.mozilla.com/D153642
// [3] https://winaero.com/make-firefox-automatically-click-on-reject-all-in-cookie-banner-consent/
// [4] https://docs.google.com/spreadsheets/d/1Nb4gVlGadyxix4i4FBDnOeT_eJp2Zcv69o-KfHtK-aA/edit#gid=0
// [5] https://bugzilla.mozilla.org/show_bug.cgi?id=1940418
// [6] https://github.com/mozilla/cookie-banner-rules-list/issues/544
// 2: reject banners if it is a one-click option; otherwise, fall back to the accept button to remove banner
// 1: reject banners if it is a one-click option; otherwise, keep banners on screen
// 0: disable all cookie banner handling
//user_pref("cookiebanners.service.mode", 1);
//user_pref("cookiebanners.service.mode.privateBrowsing", 1);
// PREF: Cookie Banner global rules
// Global rules that can handle a list of cookie banner libraries and providers on any site.
// This is used for click rules that can handle common Consent Management Providers (CMP).
//user_pref("cookiebanners.service.enableGlobalRules", true); // DEFAULT [FF121+]
//user_pref("cookiebanners.service.enableGlobalRules.subFrames", true); // DEFAULT [FF121+]
/****************************************************************************
* SECTION: TRANSLATIONS *
****************************************************************************/
// PREF: Firefox Translations [FF118+]
// Automated translation of web content is done locally in Firefox, so that
// the text being translated does not leave your machine.
// [ABOUT] Visit about:translations to translate your own text as well.
// [1] https://blog.mozilla.org/en/mozilla/local-translation-add-on-project-bergamot/
// [2] https://blog.nightly.mozilla.org/2023/06/01/firefox-translations-and-other-innovations-these-weeks-in-firefox-issue-139/
// [3] https://www.ghacks.net/2023/08/02/mozilla-firefox-117-beta-brings-an-automatic-language-translator-for-websites-and-it-works-offline/
//user_pref("browser.translations.enable", true); // DEFAULT
//user_pref("browser.translations.autoTranslate", true);
/****************************************************************************
* SECTION: FULLSCREEN NOTICE *
****************************************************************************/
// PREF: remove fullscreen delay
user_pref("full-screen-api.transition-duration.enter", "0 0"); // default=200 200
user_pref("full-screen-api.transition-duration.leave", "0 0"); // default=200 200
// PREF: disable fullscreen notice
// [NOTE] Adjust to a sensible value, like 1250, if you have security concerns.
//user_pref("full-screen-api.warning.timeout", 0); // default=3000; alt=1250
//user_pref("full-screen-api.warning.delay", -1); // default=500
/****************************************************************************
* SECTION: FONT APPEARANCE *
****************************************************************************/
// PREF: smoother font
// [1] https://reddit.com/r/firefox/comments/wvs04y/windows_11_firefox_v104_font_rendering_different/?context=3
//user_pref("gfx.webrender.quality.force-subpixel-aa-where-possible", true);
// PREF: use DirectWrite everywhere like Chrome [WINDOWS]
// [1] https://kb.mozillazine.org/Thunderbird_6.0,_etc.#Font_rendering_and_performance_issues
// [2] https://reddit.com/r/firefox/comments/wvs04y/comment/ilklzy1/?context=3
//user_pref("gfx.font_rendering.cleartype_params.rendering_mode", 5);
//user_pref("gfx.font_rendering.cleartype_params.cleartype_level", 100);
//user_pref("gfx.font_rendering.cleartype_params.force_gdi_classic_for_families", ""); // DEFAULT FF135+
//user_pref("gfx.font_rendering.directwrite.use_gdi_table_loading", false);
// Some users find these helpful:
//user_pref("gfx.font_rendering.cleartype_params.gamma", 1750);
//user_pref("gfx.font_rendering.cleartype_params.enhanced_contrast", 100);
//user_pref("gfx.font_rendering.cleartype_params.pixel_structure", 1);
// PREF: use macOS Appearance Panel text smoothing setting when rendering text [macOS]
//user_pref("gfx.use_text_smoothing_setting", true);
/****************************************************************************
* SECTION: URL BAR *
****************************************************************************/
// PREF: minimize URL bar suggestions (bookmarks, history, open tabs)
// Dropdown options in the URL bar:
//user_pref("browser.urlbar.suggest.history", false);
//user_pref("browser.urlbar.suggest.bookmark", true); // DEFAULT
//user_pref("browser.urlbar.suggest.clipboard", false);
//user_pref("browser.urlbar.suggest.openpage", false);
user_pref("browser.urlbar.suggest.engines", false);
//user_pref("browser.urlbar.suggest.searches", false);
//user_pref("browser.urlbar.quickactions.enabled", false);
//user_pref("browser.urlbar.suggest.weather", true); // DEFAULT [FF108]
//user_pref("browser.urlbar.weather.ignoreVPN", false); // DEFAULT
//user_pref("browser.urlbar.suggest.calculator", true); // [DEFAULT FF137+]
//user_pref("browser.urlbar.unitConversion.enabled", true); // [DEFAULT FF141+]
// PREF: disable dropdown suggestions with empty query
//user_pref("browser.urlbar.suggest.topsites", false);
// PREF: disable urlbar trending search suggestions [FF118+]
// [SETTING] Search>Search Suggestions>Show trending search suggestions (FF119)
user_pref("browser.urlbar.trending.featureGate", false);
//user_pref("browser.urlbar.suggest.trending", false);
// PREF: disable urlbar suggestions
//user_pref("browser.urlbar.addons.featureGate", false); // [FF115+]
//user_pref("browser.urlbar.amp.featureGate", false); // [FF141+] adMarketplace
//user_pref("browser.urlbar.fakespot.featureGate", false); // [FF130+] [DEFAULT: false]
//user_pref("browser.urlbar.mdn.featureGate", false); // [FF117+] [HIDDEN PREF]
//user_pref("browser.urlbar.weather.featureGate", false); // [FF108+] [DEFAULT: false]
//user_pref("browser.urlbar.wikipedia.featureGate", false); // [FF141+]
//user_pref("browser.urlbar.clipboard.featureGate", false); // [FF118+] [DEFAULT: true FF125+]
//user_pref("browser.urlbar.yelp.featureGate", false); // [FF124+] [DEFAULT: false]
// PREF: disable recent searches [FF120+]
// [NOTE] Recent searches are cleared with history.
// [1] https://support.mozilla.org/kb/search-suggestions-firefox
//user_pref("browser.urlbar.recentsearches.featureGate", false);
// PREF: disable tab-to-search [FF85+]
// Alternatively, you can exclude on a per-engine basis by unchecking them in Options>Search
// [SETTING] Privacy & Security>Address Bar>When using the address bar, suggest>Search engines
//user_pref("browser.urlbar.suggest.engines", false);
// PREF: Adaptive History Autofill
// [1] https://docs.google.com/document/u/1/d/e/2PACX-1vRBLr_2dxus-aYhZRUkW9Q3B1K0uC-a0qQyE3kQDTU3pcNpDHb36-Pfo9fbETk89e7Jz4nkrqwRhi4j/pub
//user_pref("browser.urlbar.autoFill", true); // [DEFAULT]
//user_pref("browser.urlbar.autoFill.adaptiveHistory.enabled", false);
// PREF: adjust the amount of Address bar / URL bar dropdown results
// This value controls the total number of entries to appear in the location bar dropdown.
// [NOTE] Items (bookmarks/history/openpages) with a high "frequency"/"bonus" will always
// be displayed (no we do not know how these are calculated or what the threshold is),
// and this does not affect the search by search engine suggestion.
// disable=0
//user_pref("browser.urlbar.maxRichResults", 5); // default=10
// PREF: text fragments
// [WARNING] Enabling can cause tab crashes [4]
// [1] https://bugzilla.mozilla.org/show_bug.cgi?id=1753933#c6
// [2] https://developer.mozilla.org/en-US/docs/Web/Text_fragments
// [3] https://web.dev/articles/text-fragments
// [4] https://github.com/yokoffing/Betterfox/issues/397
//user_pref("dom.text_fragments.enabled", true); // [DEFAULT]
//user_pref("dom.text_fragments.create_text_fragment.enabled", true);
/****************************************************************************
* SECTION: AUTOPLAY *
****************************************************************************/
// PREF: do not autoplay media audio
// [NOTE] You can set exceptions under site permissions
// [SETTING] Privacy & Security>Permissions>Autoplay>Settings>Default for all websites
// 0=Allow all, 1=Block non-muted media (default), 5=Block all
//user_pref("media.autoplay.default", 1); // DEFAULT
//user_pref("media.block-autoplay-until-in-foreground", true); // DEFAULT
// PREF: disable autoplay of HTML5 media if you interacted with the site [FF78+]
// 0=sticky (default), 1=transient, 2=user
// Firefox's Autoplay Policy Documentation (PDF) is linked below via SUMO
// [NOTE] If you have trouble with some video sites (e.g. YouTube), then add an exception (see previous PREF)
// [1] https://support.mozilla.org/questions/1293231
//user_pref("media.autoplay.blocking_policy", 2);
/****************************************************************************
* SECTION: NEW TAB PAGE *
****************************************************************************/
// PREF: startup / new tab page
// 0=blank, 1=home, 2=last visited page, 3=resume previous session
// [NOTE] Session Restore is cleared with history and not used in Private Browsing mode
// [SETTING] General>Startup>Open previous windows and tabs
//user_pref("browser.startup.page", 3);
// PREF: set HOME+NEW WINDOW page to blank tab
// about:home=Activity Stream, custom URL, about:blank
// [SETTING] Home>New Windows and Tabs>Homepage and new windows
// [Custom URLs] Set two or more websites in Home Page Field – delimited by |
// [1] https://support.mozilla.org/en-US/questions/1271888#answer-1262899
//user_pref("browser.startup.homepage", "about:blank");
// PREF: set NEWTAB page to blank tab
// true=Firefox Home, false=blank page
// [SETTING] Home>New Windows and Tabs>New tabs
//user_pref("browser.newtabpage.enabled", false);
// PREF: Pinned Shortcuts on New Tab
// [SETTINGS] Home>Firefox Home Content
// [1] https://github.com/arkenfox/user.js/issues/1556
//user_pref("browser.newtabpage.activity-stream.discoverystream.enabled", false);
//user_pref("browser.newtabpage.activity-stream.showSearch", true); // NTP Web Search [DEFAULT]
//user_pref("browser.newtabpage.activity-stream.feeds.topsites", false); // Shortcuts
user_pref("browser.newtabpage.activity-stream.showSponsoredTopSites", false); // Sponsored shortcuts [FF83+]
//user_pref("browser.newtabpage.activity-stream.showWeather", false); // Weather [FF130+]
//user_pref("browser.newtabpage.activity-stream.system.showWeather", false); // hides Weather as an UI option
user_pref("browser.newtabpage.activity-stream.feeds.section.topstories", false); // Recommended by Pocket
user_pref("browser.newtabpage.activity-stream.showSponsored", false); // Sponsored stories [FF58+]
user_pref("browser.newtabpage.activity-stream.showSponsoredCheckboxes", false); // [FF140+] Support Firefox
//user_pref("browser.newtabpage.activity-stream.feeds.section.highlights", false); // Recent Activity [DEFAULT]
//user_pref("browser.newtabpage.activity-stream.section.highlights.includeBookmarks", false);
//user_pref("browser.newtabpage.activity-stream.section.highlights.includeDownloads", false);
//user_pref("browser.newtabpage.activity-stream.section.highlights.includeVisited", false);
//user_pref("browser.newtabpage.activity-stream.feeds.snippets", false); // [DEFAULT]
// PREF: wallpapers on New Tab [FF128+ NIGHTLY]
//user_pref("browser.newtabpage.activity-stream.newtabWallpapers.enabled", false); // Wallpapers
// PREF: clear default topsites
// [NOTE] This does not block you from adding your own.
user_pref("browser.newtabpage.activity-stream.default.sites", "");
// PREF: keep search in the search box; prevent from jumping to address bar
// [1] https://www.reddit.com/r/firefox/comments/oxwvbo/firefox_start_page_search_options/
//user_pref("browser.newtabpage.activity-stream.improvesearch.handoffToAwesomebar", false);
// PREF: Firefox logo to always show
//user_pref("browser.newtabpage.activity-stream.logowordmark.alwaysVisible", true); // DEFAULT
// PREF: Bookmarks Toolbar visibility
// always, never, or newtab
//user_pref("browser.toolbars.bookmarks.visibility", "newtab"); // DEFAULT
/******************************************************************************
* SECTION: POCKET *
******************************************************************************/
// PREF: disable built-in Pocket extension
// [1] https://support.mozilla.org/kb/future-of-pocket
//user_pref("extensions.pocket.enabled", false); // DEFAULT
//user_pref("extensions.pocket.api"," ");
//user_pref("extensions.pocket.oAuthConsumerKey", " ");
//user_pref("extensions.pocket.site", " ");
//user_pref("extensions.pocket.showHome", false);
/******************************************************************************
* SECTION: DOWNLOADS *
******************************************************************************/
// PREF: choose download location
// [SETTING] To set your default "downloads": General>Downloads>Save files to...
// 0=desktop, 1=downloads (default), 2=last used
//user_pref("browser.download.folderList", 1); // DEFAULT
// PREF: always ask how to handle new mimetypes [FF101+]
// Enforce user interaction for greater security.
// [SETTING] General>Files and Applications>Applications>What should Firefox do with other files?
// false=Save files
// true=Ask whether to open or save files
//user_pref("browser.download.always_ask_before_handling_new_types", true);
// PREF: always ask where to download
// [OPTIONAL HARDENING] Enforce user interaction for greater security.
// [SETTING] General>Files and Applications>Downloads>Always ask you where to save files
// [DIALOGUE] "Ask whether to open or save files"
// true=direct download (default)
// false=the user is asked what to do
// [1] https://github.com/yokoffing/Betterfox/issues/267
//user_pref("browser.download.useDownloadDir", false);
//user_pref("browser.download.dir", "C:\Users\<YOUR_USERNAME>\AppData\Local\Temp"); // [WINDOWS]
// PREF: autohide the downloads button
//user_pref("browser.download.autohideButton", true); // DEFAULT
// PREF: disable download panel opening on every download [non-functional?]
// Controls whether to open the download panel every time a download begins.
// [NOTE] The first download ever ran in a new profile will still open the panel.
//user_pref("browser.download.alwaysOpenPanel", false);
// PREF: disable adding downloads to the system's "recent documents" list
user_pref("browser.download.manager.addToRecentDocs", false);
/****************************************************************************
* SECTION: PDF *
****************************************************************************/
// PREF: enforce Firefox's built-in PDF reader
// This setting controls if the option "Display in Firefox" is available in the setting below
// and by effect controls whether PDFs are handled in-browser or externally ("Ask" or "Open With").
// [1] https://mozilla.github.io/pdf.js/
//user_pref("pdfjs.disabled", false); // DEFAULT
// PREF: allow viewing of PDFs even if the response HTTP headers
// include Content-Disposition:attachment.
//user_pref("browser.helperApps.showOpenOptionForPdfJS", true); // DEFAULT
// PREF: open PDFs inline (FF103+)
user_pref("browser.download.open_pdf_attachments_inline", true);
// PREF: PDF sidebar on load
// 2=table of contents (if not available, will default to 1)
// 1=view pages
// 0=disabled
// -1=remember previous state (default)
//user_pref("pdfjs.sidebarViewOnLoad", 2);
// PREF: default zoom for PDFs [HIDDEN]
// [NOTE] "page-width" not needed if using sidebar on load
//user_pref("pdfjs.defaultZoomValue", page-width);
/****************************************************************************
* SECTION: TAB BEHAVIOR *
****************************************************************************/
// PREF: search query opens in a new tab (instead of the current tab)
//user_pref("browser.search.openintab", true); // SEARCH BOX
//user_pref("browser.urlbar.openintab", true); // URL BAR
// PREF: control behavior of links that would normally open in a new window
// [NOTE] You can still right-click a link and open in a new window
// 3 (default) = in a new tab; pop-up windows are treated like regular tabs
// 2 = in a new window
// 1 = in the current tab
//user_pref("browser.link.open_newwindow", 3); // DEFAULT
// PREF: determine the behavior of pages opened by JavaScript (like popups)
// 2 (default) = catch new windows opened by JavaScript that do not have
// specific values set (how large the window should be, whether it
// should have a status bar, etc.)
// 1 = let all windows opened by JavaScript open in new windows
// 0 = force all new windows opened by JavaScript into tabs
// [NOTE] Most advertising popups also open in new windows with values set
// [1] https://kb.mozillazine.org/About:config_entries
//user_pref("browser.link.open_newwindow.restriction", 0);
// PREF: override <browser.link.open_newwindow> for external links
// Set if a different destination for external links is needed
// 3=Open in a new tab in the current window
// 2=Open in a new window
// 1=Open in the current tab/window
// -1=no overrides (default)
//user_pref("browser.link.open_newwindow.override.external", -1); // DEFAULT
// PREF: focus behavior for new tabs from links
// Determine whether a link opens in the foreground or background on left-click
// [SETTINGS] Settings>General>Tabs>"When you open a link, image or media in a new tab, switch to it immediately"
// true(default) = opens new tabs by left-click in the background, leaving focus on the current tab
// false = opens new tabs by left-click in the foreground, putting focus on the new tab
// [NOTE] CTRL+SHIFT+CLICK will open new tabs in foreground (default); switching PREF to false will reverse this behavior
// [1] https://kb.mozillazine.org/About:config_entries
//user_pref("browser.tabs.loadInBackground", true); // DEFAULT
// PREF: determines whether pages normally meant to open in a new window (such as
// target="_blank" or from an external program), but that have instead been loaded in a new tab
// This pref takes effect when Firefox has diverted a new window to a new tab instead, then:
// true = loads the new tab in the background, leaving focus on the current tab
// false(default) = loads the new tab in the foreground, taking the focus from the current tab
// [NOTE] Setting this preference to true will still bring the browser to the front when opening links from outside the browser
// [1] https://kb.mozillazine.org/About:config_entries
//user_pref("browser.tabs.loadDivertedInBackground", false); // DEFAULT
// PREF: force bookmarks to open in a new tab, not the current tab
//user_pref("browser.tabs.loadBookmarksInTabs", true);
//user_pref("browser.tabs.loadBookmarksInBackground", true); // load bookmarks in background
// PREF: leave Bookmarks Menu open when selecting a site
user_pref("browser.bookmarks.openInTabClosesMenu", false);
// PREF: restore "View image info" on right-click
user_pref("browser.menu.showViewImageInfo", true);
// PREF: show all matches in Findbar
user_pref("findbar.highlightAll", true);
// PREF: force disable finding text on page without prompting
// [NOTE] Not as powerful as using Ctrl+F.
// [SETTINGS] General>Browsing>"Search for text when you start typing"
// [1] https://github.com/yokoffing/Betterfox/issues/212
//user_pref("accessibility.typeaheadfind", false); // enforce DEFAULT
// PREF: disable middle mouse click opening links from clipboard
// It's been default in Linux since at least FF102.
// [1] https://gitlab.torproject.org/tpo/applications/tor-browser/-/issues/10089
//user_pref("middlemouse.contentLoadURL", false);
// PREF: Prevent scripts from moving and resizing open windows
//user_pref("dom.disable_window_move_resize", true);
// PREF: insert new tabs after groups like it
// true(default) = open new tabs to the right of the parent tab
// false = new tabs are opened at the far right of the tab bar
//user_pref("browser.tabs.insertRelatedAfterCurrent", true); // DEFAULT
// PREF: insert new tabs immediately after the current tab
//user_pref("browser.tabs.insertAfterCurrent", true);
// PREF: leave the browser window open even after you close the last tab
//user_pref("browser.tabs.closeWindowWithLastTab", false);
// PREF: stop websites from reloading pages automatically
// [WARNING] Breaks some sites.
// [1] https://www.ghacks.net/2018/08/19/stop-websites-from-reloading-pages-automatically/
//user_pref("accessibility.blockautorefresh", true);
//user_pref("browser.meta_refresh_when_inactive.disabled", true);
// PREF: do not select the space next to a word when selecting a word
user_pref("layout.word_select.eat_space_to_next_word", false);
// PREF: controls if a double-click word selection also deletes one adjacent whitespace
// This mimics native behavior on macOS.
//user_pref("editor.word_select.delete_space_after_doubleclick_selection", true);
// PREF: do not hide the pointer while typing [LINUX]
//user_pref("widget.gtk.hide-pointer-while-typing.enabled", false);
// PREF: limit events that can cause a pop-up
// Firefox provides an option to provide exceptions for sites, remembered in your Site Settings.
// (default) "change click dblclick auxclick mouseup pointerup notificationclick reset submit touchend contextmenu"
// (alternate) user_pref("dom.popup_allowed_events", "click dblclick mousedown pointerdown");
//user_pref("dom.popup_allowed_events", "click dblclick");
//user_pref("dom.disable_open_during_load", true); // DEFAULT
//user_pref("privacy.popups.showBrowserMessage", true); // DEFAULT
// PREF: enable Tab Previews [FF122+, FF128+]
// [1] https://github.com/yokoffing/Betterfox/issues/309
//user_pref("browser.tabs.hoverPreview.enabled", true);
//user_pref("browser.tabs.hoverPreview.showThumbnails", true); // DEFAULT
/****************************************************************************
* SECTION: KEYBOARD AND SHORTCUTS *
****************************************************************************/
// PREF: disable backspace action
// 0=previous page, 1=scroll up, 2=do nothing
//user_pref("browser.backspace_action", 2); // DEFAULT
// PREF: disable ALT key toggling the menu bar
//user_pref("ui.key.menuAccessKeyFocuses", false);
//user_pref("ui.key.menuAccessKey", 18); // DEFAULT
// PREF: cycle through tabs in recently used order
// [SETTING] Ctrl+Tab cycles through tabs in recently used order
//user_pref("browser.ctrlTab.sortByRecentlyUsed", true);
// PREF: disable websites overriding Firefox's keyboard shortcuts [FF58+]
// 0=ask (default), 1=allow, 2=block
// [SETTING] to add site exceptions: Ctrl+I>Permissions>Override Keyboard Shortcuts ***/
//user_pref("permissions.default.shortcuts", 2);
// PREF: hide frequent sites on right-click of taskbar icon [WINDOWS?]
//user_pref("browser.taskbar.lists.frequent.enabled", false);
/****************************************************************************
* SECTION: ACCESSIBILITY AND USABILITY *
****************************************************************************/
// PREF: disable Reader mode parse on load
// Reader supposedly costs extra CPU after page load.
// [TIP] Use about:reader?url=%s as a keyword to open links automatically in reader mode [1].
// Firefox will not have to parse webpage for Reader when navigating.
// Extremely minimal performance impact, if you disable.
// [1] https://www.reddit.com/r/firefox/comments/621sr2/i_found_out_how_to_automatically_open_a_url_in/
//user_pref("reader.parse-on-load.enabled", false);
// PREF: Spell-check
// 0=none, 1-multi-line, 2=multi-line & single-line
//user_pref("layout.spellcheckDefault", 1); // DEFAULT
// PREF: Spell Checker underline styles [HIDDEN]
// [1] https://kb.mozillazine.org/Ui.SpellCheckerUnderlineStyle#Possible_values_and_their_effects
//user_pref("ui.SpellCheckerUnderlineStyle", 1);
// PREF: remove underlined characters from various settings
//user_pref("ui.key.menuAccessKey", 0);
// PREF: enable CSS moz document rules
// Still needed for Stylus?
// [1] https://reddit.com/r/FirefoxCSS/comments/8x2q97/reenabling_mozdocument_rules_in_firefox_61/
//user_pref("layout.css.moz-document.content.enabled", true);
/****************************************************************************
* SECTION: BOOKMARK MANAGEMENT *
****************************************************************************/
// PREF: limit the number of bookmark backups Firefox keeps
//user_pref("browser.bookmarks.max_backups", 1); // default=15
/****************************************************************************
* SECTION: ZOOM AND DISPLAY SETTINGS *
****************************************************************************/
// PREF: zoom only text on webpage, not other elements
//user_pref("browser.zoom.full", false);
// PREF: allow for more granular control of zoom levels
// Especially useful if you want to set your default zoom to a custom level.
//user_pref("toolkit.zoomManager.zoomValues", ".3,.5,.67,.8,.9,.95,1,1.1,1.2,1.3,1.4,1.5,1.6,1.7,2,2.4,3");
// PREF: restore zooming behavior [macOS] [FF109+]
// On macOS, Ctrl or Cmd + trackpad or mouse wheel now scrolls the page instead of zooming.
// This avoids accidental zooming and matches Safari's and Chrome's behavior.
// The prefs below restores the previous zooming behavior
//user_pref("mousewheel.with_control.action", 3);
//user_pref("mousewheel.with_meta.action", 3);
// PREF: adjust the minimum tab width
// Can be overridden by userChrome.css
//user_pref("browser.tabs.tabMinWidth", 120); // default=76
// PREF: always underline links [FF120+]
//user_pref("layout.css.always_underline_links", false); // DEFAULT
/****************************************************************************
* SECTION: DEVELOPER TOOLS *
****************************************************************************/
// PREF: wrap long lines of text when using source / debugger
//user_pref("view_source.wrap_long_lines", true);
//user_pref("devtools.debugger.ui.editor-wrapping", true);
// PREF: enable ASRouter Devtools at about:newtab#devtools
// This is useful if you're making your own CSS theme.
// [1] https://firefox-source-docs.mozilla.org/browser/components/newtab/content-src/asrouter/docs/debugging-docs.html
//user_pref("browser.newtabpage.activity-stream.asrouter.devtoolsEnabled", true);
// show user agent styles in the inspector
//user_pref("devtools.inspector.showUserAgentStyles", true);
// show native anonymous content (like scrollbars or tooltips) and user
// agent shadow roots (like the components of an <input> element) in the inspector
//user_pref("devtools.inspector.showAllAnonymousContent", true);
/****************************************************************************
* SECTION: IMAGE AND MEDIA HANDLING *
****************************************************************************/
// PREF: JPEG XL image format [NIGHTLY]
// May not affect anything on ESR/Stable channel [2].
// [TEST] https://www.jpegxl.io/firefox#firefox-jpegxl-tutorial
// [1] https://cloudinary.com/blog/the-case-for-jpeg-xl
// [2] https://bugzilla.mozilla.org/show_bug.cgi?id=1539075#c51
//user_pref("image.jxl.enabled", true);
| yokoffing/Betterfox | 10,046 | Firefox user.js for optimal privacy and security. Your favorite browser, but better. | JavaScript | yokoffing | ||
Securefox.js | JavaScript |
/****************************************************************************
* Securefox *
* "Natura non contristatur" *
* priority: provide sensible security and privacy *
* version: 146 *
* url: https://github.com/yokoffing/Betterfox *
* credit: Most prefs are reproduced and adapted from the arkenfox project *
* credit urL: https://github.com/arkenfox/user.js *
****************************************************************************/
/****************************************************************************
* SECTION: TRACKING PROTECTION *
****************************************************************************/
// PREF: enable ETP Strict Mode [FF86+]
// ETP Strict Mode enables Total Cookie Protection (TCP)
// [NOTE] Adding site exceptions disables all ETP protections for that site and increases the risk of
// cross-site state tracking e.g. exceptions for SiteA and SiteB means PartyC on both sites is shared
// [1] https://blog.mozilla.org/security/2021/02/23/total-cookie-protection/
// [2] https://support.mozilla.org/en-US/kb/enhanced-tracking-protection-firefox-desktop
// [3] https://www.reddit.com/r/firefox/comments/l7xetb/network_priority_for_firefoxs_enhanced_tracking/gle2mqn/?web2x&context=3
// [SETTING] to add site exceptions: Urlbar>ETP Shield
// [SETTING] to manage site exceptions: Options>Privacy & Security>Enhanced Tracking Protection>Manage Exceptions
user_pref("browser.contentblocking.category", "strict"); // [HIDDEN PREF]
//user_pref("privacy.trackingprotection.enabled", true); // enabled with "Strict"
//user_pref("privacy.trackingprotection.pbmode.enabled", true); // DEFAULT
//user_pref("browser.contentblocking.customBlockList.preferences.ui.enabled", false); // DEFAULT
//user_pref("privacy.trackingprotection.socialtracking.enabled", true); // enabled with "Strict"
//user_pref("privacy.socialtracking.block_cookies.enabled", true); // DEFAULT
//user_pref("privacy.trackingprotection.cryptomining.enabled", true); // DEFAULT
//user_pref("privacy.trackingprotection.fingerprinting.enabled", true); // DEFAULT
//user_pref("privacy.trackingprotection.emailtracking.enabled", true); // enabled with "Strict"
//user_pref("network.http.referer.disallowCrossSiteRelaxingDefault", true); // DEFAULT
//user_pref("network.http.referer.disallowCrossSiteRelaxingDefault.pbmode", true); // DEFAULT
//user_pref("network.http.referer.disallowCrossSiteRelaxingDefault.pbmode.top_navigation", true); // DEFAULT
//user_pref("network.http.referer.disallowCrossSiteRelaxingDefault.top_navigation", true); // enabled with "Strict"
//user_pref("privacy.annotate_channels.strict_list.enabled", true); // enabled with "Strict"
//user_pref("privacy.annotate_channels.strict_list.pbmode.enabled", true); // DEFAULT
//user_pref("privacy.fingerprintingProtection", true); // [FF114+] [ETP FF119+] enabled with "Strict"
//user_pref("privacy.fingerprintingProtection.pbmode", true); // DEFAULT
//user_pref("privacy.bounceTrackingProtection.mode", 1); // [FF131+] [ETP FF133+]
// [1] https://searchfox.org/mozilla-central/source/toolkit/components/antitracking/bouncetrackingprotection/nsIBounceTrackingProtection.idl#11-23
// PREF: disable ETP web compat features (about:compat) [FF93+]
// [SETUP-HARDEN] Includes skip lists, heuristics (SmartBlock) and automatic grants
// Opener and redirect heuristics are granted for 30 days, see [3]
// [1] https://blog.mozilla.org/security/2021/07/13/smartblock-v2/
// [2] https://hg.mozilla.org/mozilla-central/rev/e5483fd469ab#l4.12
// [3] https://developer.mozilla.org/docs/Web/Privacy/State_Partitioning#storage_access_heuristics
// user_pref("privacy.antitracking.enableWebcompat", false);
// PREF: set ETP Strict/Custom exception lists (FF141+)
// [SETTING] Options>Privacy & Security>Enhanced Tracking Protection>Strict/Custom>Fix major [baseline] | minor [convenience]
// [1] https://support.mozilla.org/en-US/kb/manage-enhanced-tracking-protection-exceptions
// [2] https://etp-exceptions.mozilla.org/
// user_pref("privacy.trackingprotection.allow_list.baseline.enabled", true); // [DEFAULT: true]
// user_pref("privacy.trackingprotection.allow_list.convenience.enabled", true); // [DEFAULT: true]
// PREF: query stripping
// Currently uses a small list [1]
// We set the same query stripping list that Brave and LibreWolf uses [2]
// If using uBlock Origin or AdGuard, use filter lists as well [3]
// Query parameters stripped [5]
// [1] https://www.eyerys.com/articles/news/how-mozilla-firefox-improves-privacy-using-query-parameter-stripping-feature
// [2] https://github.com/brave/brave-core/blob/f337a47cf84211807035581a9f609853752a32fb/browser/net/brave_site_hacks_network_delegate_helper.cc
// [3] https://github.com/yokoffing/filterlists#url-tracking-parameters
// [4] https://bugzilla.mozilla.org/show_bug.cgi?id=1706607
// [5] https://firefox.settings.services.mozilla.com/v1/buckets/main/collections/query-stripping/records
//user_pref("privacy.query_stripping.enabled", true); // enabled with "Strict"
//user_pref("privacy.query_stripping.enabled.pbmode", true); // enabled with "Strict"
//user_pref("privacy.query_stripping.strip_list", ""); // DEFAULT
//user_pref("privacy.query_stripping.strip_on_share.enabled", true);
// PREF: Smartblock
// [1] https://support.mozilla.org/en-US/kb/smartblock-enhanced-tracking-protection
// [2] https://www.youtube.com/watch?v=VE8SrClOTgw
// [3] https://searchfox.org/mozilla-central/source/browser/extensions/webcompat/data/shims.js
//user_pref("extensions.webcompat.enable_shims", true); // [HIDDEN] enabled with "Strict"
//user_pref("extensions.webcompat.smartblockEmbeds.enabled", true); // [DEFAULT FF137+]
// PREF: allow embedded tweets and reddit posts [FF136+]
// [TEST - reddit embed] https://www.pcgamer.com/amazing-halo-infinite-bugs-are-already-rolling-in/
// [TEST - instagram embed] https://www.ndtv.com/entertainment/bharti-singh-and-husband-haarsh-limbachiyaa-announce-pregnancy-see-trending-post-2646359
// [TEST - tweet embed] https://www.newsweek.com/cryptic-tweet-britney-spears-shows-elton-john-collab-may-date-back-2015-1728036
// [TEST - tiktok embed] https://www.vulture.com/article/snl-adds-four-new-cast-members-for-season-48.html
// [TEST - truthsocial embed] https://www.newsweek.com/donald-trump-congratulates-patrick-brittany-mahomes-new-baby-2027097
// [1] https://www.reddit.com/r/firefox/comments/l79nxy/firefox_dev_is_ignoring_social_tracking_preference/gl84ukk
// [2] https://www.reddit.com/r/firefox/comments/pvds9m/reddit_embeds_not_loading/
// [3] https://github.com/yokoffing/Betterfox/issues/413
//user_pref("urlclassifier.trackingSkipURLs", "*://embed.reddit.com/*,*://*.twitter.com/*,*://*.twimg.com/*"); // MANUAL
//user_pref("urlclassifier.features.socialtracking.skipURLs", "*://*.twitter.com/*,*://*.twimg.com/*"); // MANUAL
// PREF: allow embedded tweets, Instagram and Reddit posts, and TikTok embeds [before FF136+]
//user_pref("urlclassifier.trackingSkipURLs", "*.reddit.com, *.twitter.com, *.twimg.com, *.tiktok.com"); // MANUAL
//user_pref("urlclassifier.features.socialtracking.skipURLs", "*.instagram.com, *.twitter.com, *.twimg.com"); // MANUAL
// PREF: lower the priority of network loads for resources on the tracking protection list [NIGHTLY]
// [1] https://github.com/arkenfox/user.js/issues/102#issuecomment-298413904
//user_pref("privacy.trackingprotection.lower_network_priority", true);
// PREF: Site Isolation (sandboxing) [FF100+]
// [ABOUT] View in about:processes.
// Site Isolation (Fission) builds upon a new security architecture that extends current
// protection mechanisms by separating web content and loading each site
// in its own operating system process. This new security architecture allows
// Firefox to completely separate code originating from different sites and, in turn,
// defend against malicious sites trying to access sensitive information from other sites you are visiting.
// [1] https://hacks.mozilla.org/2021/05/introducing-firefox-new-site-isolation-security-architecture/
// [2] https://hacks.mozilla.org/2022/05/improved-process-isolation-in-firefox-100/
// [3] https://hacks.mozilla.org/2021/12/webassembly-and-back-again-fine-grained-sandboxing-in-firefox-95/
// [4] https://www.reddit.com/r/firefox/comments/r69j52/firefox_content_process_limit_is_gone/
// [5] https://hg.mozilla.org/mozilla-central/file/tip/dom/ipc/ProcessIsolation.cpp#l53
//user_pref("fission.autostart", true); // DEFAULT [DO NOT TOUCH]
//user_pref("fission.webContentIsolationStrategy", 1); // DEFAULT
// PREF: GPU sandboxing [FF110+] [WINDOWS]
// [1] https://www.ghacks.net/2023/01/17/firefox-110-will-launch-with-gpu-sandboxing-on-windows/
// [2] https://techdows.com/2023/02/disable-gpu-sandboxing-firefox.html
// 0=disabled, 1=enabled (default)
//user_pref("security.sandbox.gpu.level", 1); // DEFAULT WINDOWS
// PREF: State Partitioning [Dynamic First-Party Isolation (dFPI), Total Cookie Protection (TCP)]
// Firefox manages client-side state (i.e., data stored in the browser) to mitigate the ability of websites to abuse state
// for cross-site tracking. This effort aims to achieve that by providing what is effectively a "different", isolated storage
// location to every website a user visits.
// dFPI is a more web-compatible version of FPI, which double keys all third-party state by the origin of the top-level
// context. dFPI isolates user's browsing data for each top-level eTLD+1, but is flexible enough to apply web
// compatibility heuristics to address resulting breakage by dynamically modifying a frame's storage principal.
// dFPI isolates most sites while applying heuristics to allow sites through the isolation in certain circumstances for usability.
// [NOTE] dFPI partitions all of the following caches by the top-level site being visited: HTTP cache, image cache,
// favicon cache, HSTS cache, OCSP cache, style sheet cache, font cache, DNS cache, HTTP Authentication cache,
// Alt-Svc cache, and TLS certificate cache.
// [1] https://bugzilla.mozilla.org/show_bug.cgi?id=1549587
// [2] https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Privacy/State_Partitioning
// [3] https://blog.mozilla.org/security/2021/02/23/total-cookie-protection/
// [4] https://blog.mozilla.org/en/mozilla/firefox-rolls-out-total-cookie-protection-by-default-to-all-users-worldwide/
// [5] https://hacks.mozilla.org/2021/02/introducing-state-partitioning/
// [6] https://github.com/arkenfox/user.js/issues/1281
// [7] https://hacks.mozilla.org/2022/02/improving-the-storage-access-api-in-firefox/
// [8] https://blog.includesecurity.com/2025/04/cross-site-websocket-hijacking-exploitation-in-2025/
//user_pref("network.cookie.cookieBehavior", 5); // DEFAULT FF103+
//user_pref("network.cookie.cookieBehavior.optInPartitioning", true); // [ETP FF132+]
//user_pref("browser.contentblocking.reject-and-isolate-cookies.preferences.ui.enabled", true); // DEFAULT
// PREF: Network Partitioning
// Networking-related APIs are not intended to be used for websites to store data, but they can be abused for
// cross-site tracking. Network APIs and caches are permanently partitioned by the top-level site.
// Network Partitioning (isolation) will allow Firefox to associate resources on a per-website basis rather than together
// in the same pool. This includes cache, favicons, CSS files, images, and even speculative connections.
// [1] https://www.zdnet.com/article/firefox-to-ship-network-partitioning-as-a-new-anti-tracking-defense/
// [2] https://developer.mozilla.org/en-US/docs/Web/Privacy/State_Partitioning#network_partitioning
// [3] https://blog.mozilla.org/security/2021/01/26/supercookie-protections/
//user_pref("privacy.partition.network_state", true); // DEFAULT
//user_pref("privacy.partition.serviceWorkers", true); // [DEFAULT: true FF105+]
//user_pref("privacy.partition.network_state.ocsp_cache", true); // [DEFAULT: true FF123+]
//user_pref("privacy.partition.bloburl_per_partition_key", true); // [FF118+]
// enable APS (Always Partitioning Storage) [FF104+]
//user_pref("privacy.partition.always_partition_third_party_non_cookie_storage", true); // [DEFAULT: true FF109+]
//user_pref("privacy.partition.always_partition_third_party_non_cookie_storage.exempt_sessionstorage", false); // [DEFAULT: false FF109+]
// PREF: Redirect Tracking Prevention / Cookie Purging
// All storage is cleared (more or less) daily from origins that are known trackers and that
// haven’t received a top-level user interaction (including scroll) within the last 45 days.
// [1] https://www.ghacks.net/2020/08/06/how-to-enable-redirect-tracking-in-firefox/
// [2] https://www.cookiestatus.com/firefox/#other-first-party-storage
// [3] https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Privacy/Redirect_tracking_protection
// [4] https://www.ghacks.net/2020/03/04/firefox-75-will-purge-site-data-if-associated-with-tracking-cookies/
// [5] https://github.com/arkenfox/user.js/issues/1089
// [6] https://firefox-source-docs.mozilla.org/toolkit/components/antitracking/anti-tracking/cookie-purging/index.html
//user_pref("privacy.purge_trackers.enabled", true); // DEFAULT
// PREF: SameSite Cookies
// Currently, the absence of the SameSite attribute implies that cookies will be
// attached to any request for a given origin, no matter who initiated that request.
// This behavior is equivalent to setting SameSite=None.
// So the pref allows the lack of attribution, or SameSite=None, only on HTTPS sites
// to prevent CSFRs on plaintext sites.
// [1] https://hacks.mozilla.org/2020/08/changes-to-samesite-cookie-behavior/
// [2] https://caniuse.com/?search=samesite
// [3] https://github.com/arkenfox/user.js/issues/1640#issuecomment-1464093950
// [4] https://support.mozilla.org/en-US/questions/1364032
// [5] https://blog.mozilla.org/security/2018/04/24/same-site-cookies-in-firefox-60/
// [6] https://web.dev/samesite-cookies-explained/
// [7] https://portswigger.net/web-security/csrf/bypassing-samesite-restrictions
// [8] https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies
// [9] https://blog.includesecurity.com/2025/04/cross-site-websocket-hijacking-exploitation-in-2025/
// [TEST] https://samesite-sandbox.glitch.me/
//user_pref("network.cookie.sameSite.laxByDefault", true);
//user_pref("network.cookie.sameSite.noneRequiresSecure", true); // [DEFAULT FF131+]
//user_pref("network.cookie.sameSite.schemeful", true);
// PREF: Hyperlink Auditing (click tracking)
//user_pref("browser.send_pings", false); // DEFAULT
// PREF: Beacon API
// Allows websites to asynchronously transmit small amounts of data to servers
// without impacting page load performance. This allows things like activity tracking
// to be done reliably in the background. Other tracking methods like form submissions
// and XHR requests already allow similar capabilities but hurt performance.
// Disabling the Beacon API wouldn't make the data unavailable - sites could still
// collect it synchronously instead.
// [NOTE] Disabling this API sometimes causes site breakage.
// [TEST] https://vercel.com/
// [1] https://developer.mozilla.org/docs/Web/API/Navigator/sendBeacon
// [2] https://github.com/arkenfox/user.js/issues/1586
//user_pref("beacon.enabled", false);
// PREF: battery status tracking
// [NOTE] Pref remains, but API is depreciated.
// [1] https://developer.mozilla.org/en-US/docs/Web/API/Battery_Status_API#browser_compatibility
//user_pref("dom.battery.enabled", false);
// PREF: remove temp files opened from non-PB windows with an external application
// [1] https://bugzilla.mozilla.org/buglist.cgi?bug_id=302433,1738574
// [2] https://github.com/arkenfox/user.js/issues/1732
// [3] https://bugzilla.mozilla.org/302433
user_pref("browser.download.start_downloads_in_tmp_dir", true); // [FF102+]
//user_pref("browser.helperApps.deleteTempFileOnExit", true); // DEFAULT [FF108]
// PREF: disable UITour backend
// This way, there is no chance that a remote page can use it.
user_pref("browser.uitour.enabled", false);
//user_pref("browser.uitour.url", "");
// PREF: disable remote debugging
// [1] https://gitlab.torproject.org/tpo/applications/tor-browser/-/issues/16222
//user_pref("devtools.debugger.remote-enabled", false); // DEFAULT
// PREF: Global Privacy Control (GPC) [FF118+]
// A privacy signal that tells the websites that the user
// doesn’t want to be tracked and doesn’t want their data to be sold.
// Honored by many highly ranked sites [3].
// [SETTING] Privacy & Security > Website Privacy Preferences > Tell websites not to sell or share my data
// [TEST] https://global-privacy-control.glitch.me/
// [1] https://bugzilla.mozilla.org/show_bug.cgi?id=1830623
// [2] https://globalprivacycontrol.org/press-release/20201007.html
// [3] https://github.com/arkenfox/user.js/issues/1542#issuecomment-1279823954
// [4] https://blog.mozilla.org/netpolicy/2021/10/28/implementing-global-privacy-control/
// [5] https://help.duckduckgo.com/duckduckgo-help-pages/privacy/gpc/
// [6] https://brave.com/web-standards-at-brave/4-global-privacy-control/
// [7] https://www.eff.org/gpc-privacy-badger
// [8] https://www.eff.org/issues/do-not-track
user_pref("privacy.globalprivacycontrol.enabled", true);
//user_pref("privacy.globalprivacycontrol.functionality.enabled", true); // [FF120+]
//user_pref("privacy.globalprivacycontrol.pbmode.enabled", true); // [FF120+]
/****************************************************************************
* SECTION: OSCP & CERTS / HPKP (HTTP Public Key Pinning) *
****************************************************************************/
// Online Certificate Status Protocol (OCSP)
// OCSP leaks your IP and domains you visit to the CA when OCSP Stapling is not available on visited host.
// OCSP is vulnerable to replay attacks when nonce is not configured on the OCSP responder.
// Short-lived certificates are not checked for revocation (security.pki.cert_short_lifetime_in_days, default:10).
// Firefox falls back on plain OCSP when must-staple is not configured on the host certificate.
// [1] https://scotthelme.co.uk/revocation-is-broken/
// [2] https://blog.mozilla.org/security/2013/07/29/ocsp-stapling-in-firefox/
// [3] https://github.com/arkenfox/user.js/issues/1576#issuecomment-1304590235
// PREF: disable OCSP fetching to confirm current validity of certificates
// OCSP (non-stapled) leaks information about the sites you visit to the CA (cert authority).
// It's a trade-off between security (checking) and privacy (leaking info to the CA).
// Unlike Chrome, Firefox’s default settings also query OCSP responders to confirm the validity
// of SSL/TLS certificates. However, because OCSP query failures are so common, Firefox
// (like other browsers) implements a “soft-fail” policy.
// [NOTE] This pref only controls OCSP fetching and does not affect OCSP stapling
// [SETTING] Privacy & Security>Security>Certificates>Query OCSP responder servers...
// [1] https://en.wikipedia.org/wiki/Ocsp
// [2] https://www.ssl.com/blogs/how-do-browsers-handle-revoked-ssl-tls-certificates/#ftoc-heading-3
// 0=disabled, 1=enabled (default), 2=enabled for EV certificates only
user_pref("security.OCSP.enabled", 0);
// PREF: set OCSP fetch failures to hard-fail
// When a CA cannot be reached to validate a cert, Firefox just continues the connection (=soft-fail)
// Setting this pref to true tells Firefox to instead terminate the connection (=hard-fail)
// It is pointless to soft-fail when an OCSP fetch fails: you cannot confirm a cert is still valid (it
// could have been revoked) and/or you could be under attack (e.g. malicious blocking of OCSP servers)
// [WARNING] Expect breakage:
// security.OCSP.require will make the connection fail when the OCSP responder is unavailable
// security.OCSP.require is known to break browsing on some captive portals
// [1] https://blog.mozilla.org/security/2013/07/29/ocsp-stapling-in-firefox/
// [2] https://www.imperialviolet.org/2014/04/19/revchecking.html
// [3] https://www.ssl.com/blogs/how-do-browsers-handle-revoked-ssl-tls-certificates/#ftoc-heading-3
// [4] https://letsencrypt.org/2024/12/05/ending-ocsp/
//user_pref("security.OCSP.require", true);
// PREF: CRLite
// CRLite covers valid certs, and it doesn't fall back to OCSP in mode 2 [FF84+].
// CRLite is faster and more private than OCSP [2].
// 0 = disabled
// 1 = consult CRLite but only collect telemetry
// 2 = consult CRLite and enforce both "Revoked" and "Not Revoked" results (default)
// 3 = consult CRLite and enforce "Not Revoked" results, but defer to OCSP for "Revoked" (removed FF145)
// [1] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1429800,1670985,1753071
// [2] https://blog.mozilla.org/security/tag/crlite/
//user_pref("security.remote_settings.crlite_filters.enabled", true); // [DEFAULT: true FF137+]
//user_pref("security.pki.crlite_mode", 2); // [DEFAULT: 2 FF142+]
// PREF: HTTP Public Key Pinning (HPKP)
// HPKP enhances the security of SSL certificates by associating
// a host with their expected public key. It prevents attackers
// from impersonating the host using fraudulent certificates,
// even if they hold a valid certificate from a trusted certification authority.
// HPKP ensures that the client maintains a secure connection with
// the correct server, thereby reducing the risk of man-in-the-middle (MITM) attacks.
// [NOTE] If you rely on an antivirus to protect your web browsing
// by inspecting ALL your web traffic, then leave at 1.
// [ERROR] MOZILLA_PKIX_ERROR_KEY_PINNING_FAILURE
// By default, pinning enforcement is not applied if a user-installed
// certificate authority (CA) is present. However, this allows user-installed
// CAs to override pins for any site, negating the security benefits of HPKP.
// 0=disabled, 1=allow user MiTM (such as your antivirus) (default), 2=strict
// [1] https://gitlab.torproject.org/tpo/applications/tor-browser/-/issues/16206
// [2] https://bugzilla.mozilla.org/show_bug.cgi?id=1168603
// [3] https://github.com/yokoffing/Betterfox/issues/53#issuecomment-1035554783
//user_pref("security.cert_pinning.enforcement_level", 2);
// PREF: do not trust installed third-party root certificates [FF120+]
// Disable Enterprise Root Certificates of the operating system.
// For users trying to get intranet sites on managed networks,
// or who have security software configured to analyze web traffic.
// [1] https://bugzilla.mozilla.org/show_bug.cgi?id=1848815
//user_pref("security.enterprise_roots.enabled", false);
//user_pref("security.certerrors.mitm.auto_enable_enterprise_roots", false);
// PREF: disable content analysis by Data Loss Prevention (DLP) agents [FF124+]
// DLP agents are background processes on managed computers that
// allow enterprises to monitor locally running applications for
// data exfiltration events, which they can allow/block based on
// customer-defined DLP policies.
// [1] https://github.com/chromium/content_analysis_sdk
// [2] https://bugzilla.mozilla.org/show_bug.cgi?id=1880314
//user_pref("browser.contentanalysis.enabled", false); // [FF121+] [DEFAULT]
//user_pref("browser.contentanalysis.default_result", 0; // [FF127+] [DEFAULT]
// PREF: disable referrer and storage access for resources injected by content scripts [FF139+]
user_pref("privacy.antitracking.isolateContentScriptResources", true);
// PREF: disable CSP Level 2 Reporting [FF140+]
// [1] https://github.com/yokoffing/Betterfox/issues/415
user_pref("security.csp.reporting.enabled", false);
/****************************************************************************
* SECTION: SSL (Secure Sockets Layer) / TLS (Transport Layer Security) *
****************************************************************************/
// PREF: display warning on the padlock for "broken security"
// [NOTE] Warning padlock not indicated for subresources on a secure page! [2]
// [1] https://wiki.mozilla.org/Security:Renegotiation
// [2] https://bugzilla.mozilla.org/1353705
user_pref("security.ssl.treat_unsafe_negotiation_as_broken", true);
// PREF: require safe negotiation
// [ERROR] SSL_ERROR_UNSAFE_NEGOTIATION
// [WARNING] Breaks ea.com login (Sep 2023).
// Blocks connections to servers that don't support RFC 5746 [2]
// as they're potentially vulnerable to a MiTM attack [3].
// A server without RFC 5746 can be safe from the attack if it
// disables renegotiations but the problem is that the browser can't
// know that. Setting this pref to true is the only way for the
// browser to ensure there will be no unsafe renegotiations on
// the channel between the browser and the server.
// [STATS] SSL Labs > Renegotiation Support (May 2024) reports over 99.7% of top sites have secure renegotiation [4].
// [1] https://wiki.mozilla.org/Security:Renegotiation
// [2] https://datatracker.ietf.org/doc/html/rfc5746
// [3] https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2009-3555
// [4] https://www.ssllabs.com/ssl-pulse/
//user_pref("security.ssl.require_safe_negotiation", true);
// PREF: display advanced information on Insecure Connection warning pages
// [TEST] https://expired.badssl.com/
user_pref("browser.xul.error_pages.expert_bad_cert", true);
// PREF: disable 0-RTT (round-trip time) to improve TLS 1.3 security [FF51+]
// This data is not forward secret, as it is encrypted solely under keys derived using
// the offered PSK. There are no guarantees of non-replay between connections.
// [1] https://github.com/tlswg/tls13-spec/issues/1001
// [2] https://www.rfc-editor.org/rfc/rfc9001.html#name-replay-attacks-with-0-rtt
// [3] https://blog.cloudflare.com/tls-1-3-overview-and-q-and-a/
user_pref("security.tls.enable_0rtt_data", false);
// PREF: enable hybrid post-quantum key exchange
// [1] https://pq.cloudflareresearch.com
// [2] https://github.com/zen-browser/desktop/pull/2275
//user_pref("security.tls.enable_kyber", true);
//user_pref("network.http.http3.enable_kyber", true);
/****************************************************************************
* SECTION: FINGERPRINT PROTECTION (FPP) *
****************************************************************************/
// PREF: enable FingerPrint Protection (FPP) [WiP]
// [1] https://github.com/arkenfox/user.js/issues/1661
// [2] https://bugzilla.mozilla.org/show_bug.cgi?id=1816064
//user_pref("privacy.resistFingerprinting.randomization.daily_reset.enabled", true);
//user_pref("privacy.resistFingerprinting.randomization.daily_reset.private.enabled", true);
/****************************************************************************
* SECTION: RESIST FINGERPRINTING (RFP) *
****************************************************************************/
// PREF: enable advanced fingerprinting protection (RFP)
// [WARNING] Leave disabled unless you're okay with all the drawbacks
// [1] https://librewolf.net/docs/faq/#what-are-the-most-common-downsides-of-rfp-resist-fingerprinting
// [2] https://www.reddit.com/r/firefox/comments/wuqpgi/comment/ile3whx/?context=3
//user_pref("privacy.resistFingerprinting", true);
// PREF: set new window size rounding max values [FF55+]
// [SETUP-CHROME] sizes round down in hundreds: width to 200s and height to 100s, to fit your screen
// [1] https://bugzilla.mozilla.org/1330882
//user_pref("privacy.window.maxInnerWidth", 1600);
//user_pref("privacy.window.maxInnerHeight", 900);
// PREF: disable showing about:blank as soon as possible during startup [FF60+]
// [1] https://github.com/arkenfox/user.js/issues/1618
// [2] https://bugzilla.mozilla.org/1448423
//user_pref("browser.startup.blankWindow", false);
// PREF: disable ICC color management
// Use a color calibrator for best results [WINDOWS]
// Also may help improve font rendering on WINDOWS
// [SETTING] General>Language and Appearance>Fonts and Colors>Colors>Use system colors
// default=false NON-WINDOWS
// [1] https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Releases/3.5/ICC_color_correction_in_Firefox
//user_pref("browser.display.use_system_colors", false);
/****************************************************************************
* SECTION: DISK AVOIDANCE *
****************************************************************************/
// PREF: set media cache in Private Browsing to in-memory
// [NOTE] MSE (Media Source Extensions) are already stored in-memory in PB
user_pref("browser.privatebrowsing.forceMediaMemoryCache", true);
// PREF: minimum interval (in ms) between session save operations
// Firefox periodically saves the user's session so it can restore
// their most recent tabs and windows if the browser crashes or restarts.
// The value sets the minimum time between these session save operations.
// Firefox only saves session data when the state has changed since the last save [2].
// Work has been done to mitigate potential performance drawbacks of frequent session saving [3].
// [1] https://kb.mozillazine.org/Browser.sessionstore.interval
// [2] https://bugzilla.mozilla.org/show_bug.cgi?id=1304389#c64
// [3] https://bugzilla.mozilla.org/show_bug.cgi?id=1304389#c66
user_pref("browser.sessionstore.interval", 60000); // 1 minute; default=15000 (15s); 900000=15 min; 1800000=30 min
// PREF: store extra session data when crashing or restarting to install updates
// Dictates whether sites may save extra session data such as form content,
// scrollbar positions, and POST data.
// 0=everywhere (default), 1=unencrypted sites, 2=nowhere
//user_pref("browser.sessionstore.privacy_level", 2);
// PREF: disable automatic Firefox start and session restore after reboot [WINDOWS]
// [1] https://bugzilla.mozilla.org/603903
//user_pref("toolkit.winRegisterApplicationRestart", false);
// PREF: disable favicons in shortcuts [WINDOWS]
// Fetches and stores favicons for Windows .URL shortcuts created by drag and drop
// [NOTE] .URL shortcut files will be created with a generic icon.
// Favicons are stored as .ico files in profile_dir\shortcutCache.
//user_pref("browser.shell.shortcutFavicons", false);
// PREF: disable page thumbnails capturing
// Page thumbnails are only used in chrome/privileged contexts.
//user_pref("browser.pagethumbnails.capturing_disabled", true); // [HIDDEN PREF]
/******************************************************************************
* SECTION: SANITIZE HISTORY *
******************************************************************************/
// PREF: reset default 'Time range to clear' for "Clear Data" and "Clear History"
// Firefox remembers your last choice. This will reset the value when you start Firefox.
// 0=everything, 1=last hour, 2=last two hours, 3=last four hours,
// 4=today, 5=last five minutes, 6=last twenty-four hours
// The values 5 + 6 are not listed in the dropdown, which will display a
// blank value if they are used, but they do work as advertised.
//user_pref("privacy.sanitize.timeSpan", 0);
// PREF: sanitize site data: set manual "Clear Data" items [FF128+]
// Firefox remembers your last choices. This will reset them when you start Firefox
// [SETTING] Privacy & Security>Browser Privacy>Cookies and Site Data>Clear Data
//user_pref("privacy.clearSiteData.cache", true);
//user_pref("privacy.clearSiteData.cookiesAndStorage", false); // keep false until it respects "allow" site exceptions
//user_pref("privacy.clearSiteData.historyFormDataAndDownloads", true);
//user_pref("privacy.clearSiteData.siteSettings", false);
// PREF: sanitize history: set manual "Clear History" items, also via Ctrl-Shift-Del | clearHistory migration is FF128+
// Firefox remembers your last choices. This will reset them when you start Firefox.
// [NOTE] Regardless of what you set "downloads" to, as soon as the dialog
// for "Clear Recent History" is opened, it is synced to the same as "history".
// [SETTING] Privacy & Security>History>Custom Settings>Clear History
//user_pref("privacy.cpd.cache", true); // [DEFAULT]
//user_pref("privacy.clearHistory.cache", true);
//user_pref("privacy.cpd.formdata", true); // [DEFAULT]
//user_pref("privacy.cpd.history", true); // [DEFAULT]
//user_pref("privacy.cpd.downloads", true); // not used; see note above
//user_pref("privacy.clearHistory.historyFormDataAndDownloads", true);
//user_pref("privacy.cpd.cookies", false);
//user_pref("privacy.cpd.sessions", true); // [DEFAULT]
//user_pref("privacy.cpd.offlineApps", false); // [DEFAULT]
//user_pref("privacy.clearHistory.cookiesAndStorage", false);
//user_pref("privacy.cpd.openWindows", false); // Session Restore
//user_pref("privacy.cpd.passwords", false);
//user_pref("privacy.cpd.siteSettings", false);
//user_pref("privacy.clearHistory.siteSettings", false);
// PREF: purge session icon in Private Browsing windows
user_pref("browser.privatebrowsing.resetPBM.enabled", true);
// PREF: delete files downloaded in Private Browsing when all private windows are closed
// When downloading a file in private browsing mode, the user will be prompted
// to chose whether they want to keep or delete files that are downloaded
// while in private browsing.
//user_pref("browser.download.enableDeletePrivate", true);
//user_pref("browser.download.deletePrivateChosen", true);
//user_pref("browser.download.deletePrivate", true);
/******************************************************************************
* SECTION: SHUTDOWN & SANITIZING *
******************************************************************************/
// PREF: set History section to show all options
// Settings>Privacy>History>Use custom settings for history
// [INFOGRAPHIC] https://bugzilla.mozilla.org/show_bug.cgi?id=1765533#c1
user_pref("privacy.history.custom", true);
// PREF: clear browsing data on shutdown, while respecting site exceptions
// Set cookies, site data, cache, etc. to clear on shutdown.
// [SETTING] Privacy & Security>History>Custom Settings>Clear history when Firefox closes>Settings
// [NOTE] "sessions": Active Logins: refers to HTTP Basic Authentication [1], not logins via cookies
// [NOTE] "offlineApps": Offline Website Data: localStorage, service worker cache, QuotaManager (IndexedDB, asm-cache)
// Clearing "offlineApps" may affect login items after browser restart [2].
// [1] https://en.wikipedia.org/wiki/Basic_access_authentication
// [2] https://github.com/arkenfox/user.js/issues/1291
// [3] https://github.com/yokoffing/Betterfox/issues/272
//user_pref("privacy.sanitize.sanitizeOnShutdown", true);
// PREF: sanitize on shutdown: no site exceptions | v2 migration [FF128+]
// [NOTE] If "history" is true, downloads will also be cleared.
//user_pref("privacy.clearOnShutdown.cache", true); // [DEFAULT]
//user_pref("privacy.clearOnShutdown_v2.cache", true); // [FF128+] [DEFAULT]
//user_pref("privacy.clearOnShutdown.downloads", true); // [DEFAULT]
//user_pref("privacy.clearOnShutdown.formdata", true); // [DEFAULT]
//user_pref("privacy.clearOnShutdown.history", true); // [DEFAULT]
//user_pref("privacy.clearOnShutdown_v2.historyFormDataAndDownloads", true); // [FF128+] [DEFAULT]
//user_pref("privacy.clearOnShutdown.siteSettings", false); // [DEFAULT]
//user_pref("privacy.clearOnShutdown_v2.siteSettings", false); // [FF128+] [DEFAULT]
// PREF: set Session Restore to clear on shutdown [FF34+]
// [NOTE] Not needed if Session Restore is not used or it is already cleared with history (2811)
// [NOTE] However, if true, this pref prevents resuming from crashes.
//user_pref("privacy.clearOnShutdown.openWindows", true);
// PREF: sanitize on shutdown: respects allow site exceptions | v2 migration [FF128+]
// Set cookies, site data, cache, etc. to clear on shutdown.
// [SETTING] Privacy & Security>History>Custom Settings>Clear history when Firefox closes>Settings
// [NOTE] "sessions": Active Logins (has no site exceptions): refers to HTTP Basic Authentication [1], not logins via cookies.
// [NOTE] "offlineApps": Offline Website Data: localStorage, service worker cache, QuotaManager (IndexedDB, asm-cache).
// Clearing "offlineApps" may affect login items after browser restart.
// [1] https://en.wikipedia.org/wiki/Basic_access_authentication
//user_pref("privacy.clearOnShutdown.cookies", true); // Cookies
//user_pref("privacy.clearOnShutdown.offlineApps", true); // Site Data
//user_pref("privacy.clearOnShutdown.sessions", true); // Active Logins [DEFAULT]
//user_pref("privacy.clearOnShutdown_v2.cookiesAndStorage", true); // Cookies, Site Data, Active Logins [FF128+]
// PREF: configure site exceptions
// [NOTE] Currently, there is no way to add sites via about:config.
// [SETTING] to add site exceptions: Ctrl+I>Permissions>Cookies>Allow (when on the website in question)
// [SETTING] To manage site exceptions: Options>Privacy & Security>Cookies & Site Data>Manage Exceptions
// [NOTE] Exceptions: A "cookie" permission also controls "offlineApps" (see note below). For cross-domain logins,
// add exceptions for both sites e.g. https://www.youtube.com (site) + https://accounts.google.com (single sign on)
// [WARNING] Be selective with what cookies you keep, as they also disable partitioning [1]
// [1] https://bugzilla.mozilla.org/show_bug.cgi?id=1767271
/******************************************************************************
* SECTION: SEARCH / URL BAR *
******************************************************************************/
// PREF: darken certain parts of the URL [FF75+]
// Makes the domain name more prominent by graying out other parts of the URL.
// Also hidse https:// and www parts from the suggestion URL.
// [1] https://udn.realityripple.com/docs/Mozilla/Preferences/Preference_reference/browser.urlbar.trimURLs
// [2] https://winaero.com/firefox-75-strips-https-and-www-from-address-bar-results/
//user_pref("browser.urlbar.trimURLs", true); // DEFAULT
// PREF: trim HTTPS from the URL bar [FF119+]
// Firefox will hide https:// from the address bar, but not subdomains like www.
// It saves some space. Betterfox already uses HTTPS-by-Default and insecure sites
// get a padlock with a red stripe. Copying the URL still copies the scheme,
// so it's not like we need to see https. It's not a privacy issue, so you can add to your overrides.
// [TEST] http://www.http2demo.io/
// [1] https://www.ghacks.net/2023/09/19/firefox-119-will-launch-with-an-important-address-bar-change/
user_pref("browser.urlbar.trimHttps", true);
user_pref("browser.urlbar.untrimOnUserInteraction.featureGate", true);
// PREF: display "Not Secure" text on HTTP sites
// Needed with HTTPS-First Policy; not needed with HTTPS-Only Mode.
//user_pref("security.insecure_connection_text.enabled", true); // [DEFAULT FF136+]
//user_pref("security.insecure_connection_text.pbmode.enabled", true); // [DEFAULT FF136+]
// PREF: do not show search terms in URL bar [FF110+]
// Show search query instead of URL on search results pages.
// [SETTING] Search>Search Bar>Use the address bar for search and navigation>Show search terms instead of URL...
//user_pref("browser.urlbar.showSearchTerms.enabled", false);
//user_pref("browser.urlbar.showSearchTerms.featureGate", false); // DEFAULT
// PREF: enable seperate search engine for Private Windows
// [SETTINGS] Preferences>Search>Default Search Engine>"Use this search engine in Private Windows"
user_pref("browser.search.separatePrivateDefault.ui.enabled", true);
// [SETTINGS] "Choose a different default search engine for Private Windows only"
//user_pref("browser.search.separatePrivateDefault", true); // DEFAULT
// PREF: enable option to add custom search engine
// Before FF140, this pref was hidden.
// [SETTINGS] Settings -> Search -> Search Shortcuts -> Add
// [EXAMPLE] https://search.brave.com/search?q=%s
// [EXAMPLE] https://lite.duckduckgo.com/lite/?q=%s
// [1] https://reddit.com/r/firefox/comments/xkzswb/adding_firefox_search_engine_manually/
// [2] https://www.mozilla.org/en-US/firefox/140.0/releasenotes/
//user_pref("browser.urlbar.update2.engineAliasRefresh", true); // [DEFAULT FF140+]
// PREF: disable live search suggestions (Google, Bing, etc.)
// [WARNING] Search engines keylog every character you type from the URL bar.
// Override these if you trust and use a privacy respecting search engine.
// [NOTE] Both prefs must be true for live search to work in the location bar.
// [SETTING] Search>Provide search suggestions > Show search suggestions in address bar result
user_pref("browser.search.suggest.enabled", false);
//user_pref("browser.search.suggest.enabled.private", false); // DEFAULT
// PREF: disable Show recent searches
// [SETTING] Search > Search Suggestions > Show recent searches
//user_pref("browser.urlbar.suggest.recentsearches", false);
// PREF: disable Firefox Suggest
// [1] https://github.com/arkenfox/user.js/issues/1257
user_pref("browser.urlbar.quicksuggest.enabled", false); // controls whether the UI is shown
//user_pref("browser.urlbar.suggest.quicksuggest.sponsored", false); // [FF92+]
//user_pref("browser.urlbar.suggest.quicksuggest.nonsponsored", false); // [FF95+]
// hide Firefox Suggest label in URL dropdown box
user_pref("browser.urlbar.groupLabels.enabled", false);
// PREF: disable search and form history
// Be aware that autocomplete form data can be read by third parties [1][2].
// Form data can easily be stolen by third parties.
// [SETTING] Privacy & Security>History>Custom Settings>Remember search and form history
// [1] https://blog.mindedsecurity.com/2011/10/autocompleteagain.html
// [2] https://bugzilla.mozilla.org/381681
user_pref("browser.formfill.enable", false);
// PREF: URL bar domain guessing
// Domain guessing intercepts DNS "hostname not found errors" and resends a
// request (e.g. by adding www or .com). This is inconsistent use (e.g. FQDNs), does not work
// via Proxy Servers (different error), is a flawed use of DNS (TLDs: why treat .com
// as the 411 for DNS errors?), privacy issues (why connect to sites you didn't
// intend to), can leak sensitive data (e.g. query strings: e.g. Princeton attack),
// and is a security risk (e.g. common typos & malicious sites set up to exploit this).
//user_pref("browser.fixup.alternate.enabled", false); // [DEFAULT FF104+]
// PREF: disable location bar autofill
// https://support.mozilla.org/en-US/kb/address-bar-autocomplete-firefox#w_url-autocomplete
//user_pref("browser.urlbar.autoFill", false);
// PREF: enforce Punycode for Internationalized Domain Names to eliminate possible spoofing
// Firefox has some protections, but it is better to be safe than sorry.
// [!] Might be undesirable for non-latin alphabet users since legitimate IDN's are also punycoded.
// [EXAMPLE] https://www.techspot.com/news/100555-malvertising-attack-uses-punycode-character-spread-malware-through.html
// [TEST] https://www.xn--80ak6aa92e.com/ (www.apple.com)
// [1] https://wiki.mozilla.org/IDN_Display_Algorithm
// [2] https://en.wikipedia.org/wiki/IDN_homograph_attack
// [3] CVE-2017-5383: https://www.mozilla.org/security/advisories/mfsa2017-02/
// [4] https://www.xudongz.com/blog/2017/idn-phishing/
user_pref("network.IDN_show_punycode", true);
/******************************************************************************
* SECTION: HTTPS-FIRST POLICY *
******************************************************************************/
// PREF: HTTPS-First Policy
// Firefox attempts to make all connections to websites secure,
// and falls back to insecure connections only when a website
// does not support it. Unlike HTTPS-Only Mode, Firefox
// will NOT ask for your permission before connecting to a website
// that doesn’t support secure connections.
// As of October 2025, Google estimates that 3-5% of traffic
// is insecure, allowing attackers to eavesdrop on or change that data [8].
// [NOTE] HTTPS-Only Mode needs to be disabled for HTTPS First to work.
// [TEST] http://example.com [upgrade]
// [TEST] http://httpforever.com/ [no upgrade]
// [1] https://blog.mozilla.org/security/2021/08/10/firefox-91-introduces-https-by-default-in-private-browsing/
// [2] https://brave.com/privacy-updates/22-https-by-default/
// [3] https://github.com/brave/adblock-lists/blob/master/brave-lists/https-upgrade-exceptions-list.txt
// [4] https://web.dev/why-https-matters/
// [5] https://www.cloudflare.com/learning/ssl/why-use-https/
// [6] https://blog.chromium.org/2023/08/towards-https-by-default.html
// [7] https://attackanddefense.dev/2025/03/31/https-first-in-firefox-136.html
// [8] https://security.googleblog.com/2025/10/https-by-default.html
//user_pref("dom.security.https_first", true); // [DEFAULT FF136+]
//user_pref("dom.security.https_first_pbm", true); // [DEFAULT FF91+]
//user_pref("dom.security.https_first_schemeless", true); // [FF120+] [DEFAULT FF129+]
// PREF: block insecure passive content (images) on HTTPS pages
// [WARNING] This preference blocks all mixed content, including upgradable.
// Firefox still attempts an HTTP connection if it can't find a secure one,
// even with HTTPS First Policy. Although rare, this leaves a small risk of
// a malicious image being served through a MITM attack.
// Disable this pref if using HTTPS-Only Mode.
// [NOTE] Enterprise users may need to enable this setting [1].
// [1] https://blog.mozilla.org/security/2024/06/05/firefox-will-upgrade-more-mixed-content-in-version-127/
//user_pref("security.mixed_content.block_display_content", true); // Defense-in-depth (see HTTPS-Only mode)
/******************************************************************************
* SECTION: HTTPS-ONLY MODE *
******************************************************************************/
// Firefox displays a warning page if HTTPS is not supported
// by a server. Options to use HTTP are then provided.
// [NOTE] When "https_only_mode" (all windows) is true,
// "https_only_mode_pbm" (private windows only) is ignored.
// As of October 2025, Google estimates that 3-5% of traffic
// is insecure, allowing attackers to eavesdrop on or change that data [6].
// [SETTING] to add site exceptions: Padlock>HTTPS-Only mode>On/Off/Off temporarily
// [SETTING] Privacy & Security>HTTPS-Only Mode
// [TEST] http://example.com [upgrade]
// [TEST] http://httpforever.com/ [no upgrade]
// [1] https://bugzilla.mozilla.org/1613063
// [2] https://blog.mozilla.org/security/2020/11/17/firefox-83-introduces-https-only-mode/
// [3] https://web.dev/why-https-matters/
// [4] https://www.cloudflare.com/learning/ssl/why-use-https/
// [5] https://blog.chromium.org/2023/08/towards-https-by-default.html
// [6] https://security.googleblog.com/2025/10/https-by-default.html
// PREF: enable HTTPS-Only mode in all windows
// When the top-level is HTTPS, insecure subresources are also upgraded (silent fail)
// [SETTING] to add site exceptions: Padlock>HTTPS-Only mode>On (after "Continue to HTTP Site")
// [SETTING] Privacy & Security>HTTPS-Only Mode (and manage exceptions)
// [TEST] http://example.com [upgrade]
// [TEST] http://httpforever.com/ | http://http.rip [no upgrade]
user_pref("dom.security.https_only_mode", true); // [FF76+]
//user_pref("dom.security.https_only_mode_pbm", true); // [FF80+] Private Browsing windows only
// PREF: offer suggestion for HTTPS site when available
// [1] https://x.com/leli_gibts_scho/status/1371463866606059528
user_pref("dom.security.https_only_mode_error_page_user_suggestions", true);
// PREF: HTTP background requests in HTTPS-only Mode
// When attempting to upgrade, if the server doesn't respond within a few seconds,
// Firefox sends HTTP requests in order to check if the server supports HTTPS or not.
// This is done to avoid waiting for a timeout which takes 90 seconds.
// Firefox only sends top level domain when falling back to http.
// [WARNING] Disabling causes long timeouts when no path to HTTPS is present.
// [NOTE] Use "Manage Exceptions" for sites known for no HTTPS.
// [1] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1642387,1660945
// [2] https://blog.mozilla.org/attack-and-defense/2021/03/10/insights-into-https-only-mode/
//user_pref("dom.security.https_only_mode_send_http_background_request", true); // DEFAULT
/******************************************************************************
* SECTION: DNS-over-HTTPS *
******************************************************************************/
// PREF: DNS-over-HTTPS (DoH) implementation
// [NOTE] Mode 3 has site exceptions with a nice UI on the error page.
// [SETTINGS] Privacy & Security > DNS over HTTPS > Enable secure DNS using:
// [NOTE] Mode 3 has site-exceptions with a nice UI on the error page.
// [1] https://hacks.mozilla.org/2018/05/a-cartoon-intro-to-dns-over-https/
// [2] https://wiki.mozilla.org/Security/DOH-resolver-policy
// [3] https://support.mozilla.org/en-US/kb/dns-over-https#w_protection-levels-explained
// 0= Default Protection: Firefox decides when to use secure DNS (default)
// 2= Increased Protection: use DoH and fall back to native DNS if necessary
// 3= Max Protection: only use DoH; do not fall back to native DNS
// 5= Off: disable DoH
//user_pref("network.trr.mode", 0); // DEFAULT
// PREF: lower max attempts to use DoH
// If DNS requests take too long, FF will fallback to your default DNS much quicker.
//user_pref("network.trr.max-fails", 5); // default=15
// PREF: display fallback warning page [FF115+]
// Show a warning checkbox UI in modes 0 or 2 above.
//user_pref("network.trr_ui.show_fallback_warning_option", false); // DEFAULT
//user_pref("network.trr.display_fallback_warning", false); // DEFAULT
// PREF: DoH resolver
// [1] https://github.com/uBlockOrigin/uBlock-issues/issues/1710
//user_pref("network.trr.uri", "https://xxxx/dns-query");
//user_pref("network.trr.custom_uri", "https://xxxx/dns-query");
// PREF: set DoH bootstrap address [FF89+]
// Firefox uses the system DNS to initially resolve the IP address of your DoH server.
// When set to a valid, working value that matches your "network.trr.uri" Firefox
// won't use the system DNS. If the IP doesn't match then DoH won't work
//user_pref("network.trr.bootstrapAddr", "10.0.0.1"); // [HIDDEN PREF]
// PREF: adjust providers
//user_pref("network.trr.resolvers", '[{ "name": "Cloudflare", "url": "https://mozilla.cloudflare-dns.com/dns-query" },{ "name": "SecureDNS", "url": "https://doh.securedns.eu/dns-query" },{ "name": "AppliedPrivacy", "url": "https://doh.appliedprivacy.net/query" },{ "name": "Digitale Gesellschaft (CH)", "url": "https://dns.digitale-gesellschaft.ch/dns-query" }, { "name": "Quad9", "url": "https://dns.quad9.net/dns-query" }]');
// PREF: EDNS Client Subnet (ECS)
// [WARNING] In some circumstances, enabling ECS may result
// in suboptimal routing between CDN origins and end users [2].
// [NOTE] You will also need to enable this with your
// DoH provider most likely.
// [1] https://en.wikipedia.org/wiki/EDNS_Client_Subnet
// [2] https://www.quad9.net/support/faq/#edns
// [3] https://datatracker.ietf.org/doc/html/rfc7871
//user_pref("network.trr.disable-ECS", true); // DEFAULT
// PREF: DNS Rebind Protection
// false=do not allow RFC 1918 private addresses in TRR responses (default)
// true=allow RFC 1918 private addresses in TRR responses
// [1] https://docs.controld.com/docs/dns-rebind-option
//user_pref("network.trr.allow-rfc1918", false); // DEFAULT
// PREF: assorted options
//user_pref("network.trr.confirmationNS", "skip"); // skip undesired DOH test connection
//user_pref("network.trr.skip-AAAA-when-not-supported", true); // [DEFAULT] If Firefox detects that your system does not have IPv6 connectivity, it will not request IPv6 addresses from the DoH server
//user_pref("network.trr.clear-cache-on-pref-change", true); // [DEFAULT] DNS+TRR cache will be cleared when a relevant TRR pref changes
//user_pref("network.trr.wait-for-portal", false); // [DEFAULT] set this to true to tell Firefox to wait for the captive portal detection before TRR is used
// PREF: DOH exlcusions
//user_pref("network.trr.excluded-domains", ""); // DEFAULT; comma-separated list of domain names to be resolved using the native resolver instead of TRR. This pref can be used to make /etc/hosts works with DNS over HTTPS in Firefox.
//user_pref("network.trr.builtin-excluded-domains", "localhost,local"); // DEFAULT; comma-separated list of domain names to be resolved using the native resolver instead of TRR
// PREF: Oblivious HTTP (OHTTP) (DoOH)
// [Oct 2023] Cloudflare are the only ones running an OHTTP server and resolver,
// but there needs to be a relay, and it's not the cheapest thing to run.
// [1] https://blog.cloudflare.com/stronger-than-a-promise-proving-oblivious-http-privacy-properties/
// [2] https://www.ietf.org/archive/id/draft-thomson-http-oblivious-01.html
// [3] https://old.reddit.com/r/dnscrypt/comments/11ukt43/what_is_dns_over_oblivious_http_targetrelay/ji1nl0m/?context=3
//user_pref("network.trr.mode", 2);
//user_pref("network.trr.ohttp.config_uri", "https://dooh.cloudflare-dns.com/.well-known/doohconfig");
//user_pref("network.trr.ohttp.uri", "https://dooh.cloudflare-dns.com/dns-query");
//user_pref("network.trr.ohttp.relay_uri", ""); // custom
//user_pref("network.trr.use_ohttp", true);
// PREF: Encrypted Client Hello (ECH) [FF118]
// [NOTE] HTTP is already isolated with network partitioning.
// [TEST] https://www.cloudflare.com/ssl/encrypted-sni
// [1] https://support.mozilla.org/en-US/kb/understand-encrypted-client-hello
// [2] https://blog.mozilla.org/en/products/firefox/encrypted-hello/
// [3] https://support.mozilla.org/en-US/kb/faq-encrypted-client-hello#w_can-i-use-ech-alongside-other-security-tools-like-vpnsre
// [4] https://wiki.mozilla.org/Security/Encrypted_Client_Hello#Preferences
//user_pref("network.dns.echconfig.enabled", true); // use ECH for TLS Connections
//user_pref("network.dns.http3_echconfig.enabled", true); // use ECH for QUIC connections
//user_pref("network.dns.echconfig.fallback_to_origin_when_all_failed", false); // fallback to non-ECH without an authenticated downgrade signal
/******************************************************************************
* SECTION: PROXY / SOCKS / IPv6 *
******************************************************************************/
// PREF: disable IPv6
// If you are not masking your IP, then this won't make much difference.
// And some VPNs now cover IPv6.
// [TEST] https://ipleak.org/
// [1] https://www.internetsociety.org/tag/ipv6-security/ (Myths 2,4,5,6)
//user_pref("network.dns.disableIPv6", true);
// PREF: set the proxy server to do any DNS lookups when using SOCKS
// e.g. in Tor, this stops your local DNS server from knowing your Tor destination
// as a remote Tor node will handle the DNS request.
// [1] https://trac.torproject.org/projects/tor/wiki/doc/TorifyHOWTO/WebBrowsers
// [SETTING] Settings>Network Settings>Proxy DNS when using SOCKS v5
//user_pref("network.proxy.socks_remote_dns", true);
// PREF: disable using UNC (Uniform Naming Convention) paths [FF61+]
// [SETUP-CHROME] Can break extensions for profiles on network shares.
// [1] https://gitlab.torproject.org/tpo/applications/tor-browser/-/issues/26424
//user_pref("network.file.disable_unc_paths", true); // [HIDDEN PREF]
// PREF: disable GIO as a potential proxy bypass vector
// Gvfs/GIO has a set of supported protocols like obex, network,
// archive, computer, dav, cdda, gphoto2, trash, etc.
// From FF87-117, by default only sftp was accepted.
// [1] https://bugzilla.mozilla.org/1433507
// [2] https://en.wikipedia.org/wiki/GVfs
// [3] https://en.wikipedia.org/wiki/GIO_(software)
//user_pref("network.gio.supported-protocols", ""); // [HIDDEN PREF] [DEFAULT FF118+]
// PREF: disable check for proxies
//user_pref("network.notify.checkForProxies", false);
/******************************************************************************
* SECTION: PASSWORDS *
******************************************************************************/
// PREF: disable password manager
// [NOTE] This does not clear any passwords already saved.
// [SETTING] Privacy & Security>Logins and Passwords>Ask to save logins and passwords for websites
//user_pref("signon.rememberSignons", false);
//user_pref("signon.schemeUpgrades", true); // DEFAULT
//user_pref("signon.showAutoCompleteFooter", true); // DEFAULT
//user_pref("signon.autologin.proxy", false); // DEFAULT
// PREF: disable auto-filling username & password form fields
// Can leak in cross-site forms and be spoofed.
// [NOTE] Username and password is still available when you enter the field.
// [SETTING] Privacy & Security>Logins and Passwords>Autofill logins and passwords
//user_pref("signon.autofillForms", false);
//user_pref("signon.autofillForms.autocompleteOff", true); // DEFAULT
// PREF: disable formless login capture for Password Manager [FF51+]
// [1] https://bugzilla.mozilla.org/show_bug.cgi?id=1166947
user_pref("signon.formlessCapture.enabled", false);
// PREF: disable capturing credentials in private browsing
user_pref("signon.privateBrowsingCapture.enabled", false);
// PREF: disable autofilling saved passwords on HTTP pages
// [1] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1217152,1319119
//user_pref("signon.autofillForms.http", false); // DEFAULT
// PREF: disable Firefox built-in password generator
// Create passwords with random characters and numbers.
// [NOTE] Doesn't work with Lockwise disabled!
// [1] https://wiki.mozilla.org/Toolkit:Password_Manager/Password_Generation
//user_pref("signon.generation.enabled", false);
// PREF: disable Firefox Lockwise (about:logins)
// [NOTE] No usernames or passwords are sent to third-party sites.
// [1] https://lockwise.firefox.com/
// [2] https://support.mozilla.org/en-US/kb/firefox-lockwise-managing-account-data
// user_pref("signon.management.page.breach-alerts.enabled", false);
//user_pref("signon.management.page.breachAlertUrl", "");
//user_pref("browser.contentblocking.report.lockwise.enabled", false);
//user_pref("browser.contentblocking.report.lockwise.how_it_works.url", "");
// PREF: disable Firefox Relay
// Privacy & Security > Passwords > Suggest Firefox Relay email masks to protect your email address
//user_pref("signon.firefoxRelay.feature", "");
// PREF: disable websites autocomplete
// Don't let sites dictate use of saved logins and passwords.
//user_pref("signon.storeWhenAutocompleteOff", false);
// PREF: limit (or disable) HTTP authentication credentials dialogs triggered by sub-resources [FF41+]
// Hardens against potential credentials phishing.
// [WARNING] Hardening this pref may prevent you from subscribing to SoGo calendars in Thunderbird 138
// 0=don't allow sub-resources to open HTTP authentication credentials dialogs
// 1=don't allow cross-origin sub-resources to open HTTP authentication credentials dialogs
// 2=allow sub-resources to open HTTP authentication credentials dialogs (default)
// [1] https://web.archive.org/web/20181123134351/https://www.fxsitecompat.com/en-CA/docs/2015/http-auth-dialog-can-no-longer-be-triggered-by-cross-origin-resources/
user_pref("network.auth.subresource-http-auth-allow", 1);
// PREF: prevent password truncation when submitting form data
// [1] https://www.ghacks.net/2020/05/18/firefox-77-wont-truncate-text-exceeding-max-length-to-address-password-pasting-issues/
user_pref("editor.truncate_user_pastes", false);
// PREF: reveal password icon
//user_pref("layout.forms.reveal-password-context-menu.enabled", true); // right-click menu option; DEFAULT [FF112]
// [DO NOT TOUCH] Icons will double-up if the website implements it natively.
//user_pref("layout.forms.reveal-password-button.enabled", true); // always show icon in password fields
// PREF: disable automatic authentication on Microsoft sites [WINDOWS]
// [1] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1695693,1719301
//user_pref("network.http.windows-sso.enabled", false);
/****************************************************************************
* SECTION: ADDRESS + CREDIT CARD MANAGER *
****************************************************************************/
// PREF: disable form autofill
// [NOTE] stored data is not secure (uses a JSON file)
// [1] https://wiki.mozilla.org/Firefox/Features/Form_Autofill
// [2] https://www.ghacks.net/2017/05/24/firefoxs-new-form-autofill-is-awesome
//user_pref("extensions.formautofill.addresses.enabled", false);
//user_pref("extensions.formautofill.creditCards.enabled", false);
/****************************************************************************
* SECTION: EXTENSIONS *
****************************************************************************/
// PREF: limit allowed extension directories
// 1=profile, 2=user, 4=application, 8=system, 16=temporary, 31=all
// The pref value represents the sum: e.g. 5 would be profile and application directories.
// [WARNING] Breaks usage of files which are installed outside allowed directories.
// [1] https://archive.is/DYjAM
user_pref("extensions.enabledScopes", 5); // [HIDDEN PREF]
//user_pref("extensions.autoDisableScopes", 15); // [DEFAULT: 15]
// PREF: skip 3rd party panel when installing recommended addons [FF82+]
// [1] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1659530,1681331
//user_pref("extensions.postDownloadThirdPartyPrompt", false);
// PREF: disable mozAddonManager Web API [FF57+]
// [NOTE] To allow extensions to work on AMO, you also need extensions.webextensions.restrictedDomains.
// [1] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1384330,1406795,1415644,1453988
//user_pref("privacy.resistFingerprinting.block_mozAddonManager", true);
// PREF: disable webextension restrictions on Mozilla domains [FF60+]
// [1] https://www.reddit.com/r/firefox/comments/n1lpaf/make_addons_work_on_mozilla_sites/gwdy235/?context=3
// [2] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1384330,1406795,1415644,1453988
//user_pref("extensions.webextensions.restrictedDomains", "");
// PREF: do not require signing for extensions [ESR/DEV/NIGHTLY ONLY]
// [1] https://support.mozilla.org/en-US/kb/add-on-signing-in-firefox#w_what-are-my-options-if-i-want-to-use-an-unsigned-add-on-advanced-users
//user_pref("xpinstall.signatures.required", false);
// PREF: disable Quarantined Domains [FF115+]
// Users may see a notification when running add-ons that are not monitored by Mozilla when they visit certain sites.
// The notification informs them that “some extensions are not allowed” and were blocked from running on that site.
// There's no details as to which sites are affected.
// [1] https://support.mozilla.org/kb/quarantined-domains
// [2] https://www.ghacks.net/2023/07/04/firefox-115-new-esr-base-and-some-add-ons-may-be-blocked-from-running-on-certain-sites/
//user_pref("extensions.quarantinedDomains.enabled", true); // [DEFAULT: true]
/******************************************************************************
* SECTION: HEADERS / REFERERS *
******************************************************************************/
// PREF: default referrer policy (used unless overriden by the site)
// 0=no-referrer, 1=same-origin, 2=strict-origin-when-cross-origin (default),
// 3=no-referrer-when-downgrade
// [1] https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy#examples
// [2] https://plausible.io/blog/referrer-policy
//user_pref("network.http.referer.defaultPolicy", 2); // DEFAULT
//user_pref("network.http.referer.defaultPolicy.pbmode", 2); // DEFAULT
// PREF: default Referrer Policy for trackers (used unless overriden by the site)
// Applied to third-party trackers when the default
// cookie policy is set to reject third-party trackers.
// 0=no-referrer, 1=same-origin, 2=strict-origin-when-cross-origin (default),
// 3=no-referrer-when-downgrade
// [1] https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy#examples
//user_pref("network.http.referer.defaultPolicy.trackers", 1);
//user_pref("network.http.referer.defaultPolicy.trackers.pbmode", 1);
// PREF: HTTP Referrer Header
// [NOTE] Only cross-origin referers need control.
// See network.http.referer.XOriginPolicy.
// This may cause breakage where third party images and videos
// may not load, and with authentication on sites such as banks.
// 0 = Never send
// 1 = Send only when clicking on links and similar elements
// 2 = Send on all requests (default)
//user_pref("network.http.sendRefererHeader", 2); // DEFAULT
// PREF: control when to send a cross-origin referer
// Controls whether or not to send a referrer across different sites.
// This includes images, links, and embedded social media on pages.
// This may cause breakage where third party images and videos
// may not load, and with authentication on sites such as banks.
// [NOTE] Most navigational "tracking" is harmless (i.e., the same for everyone)
// and effectively blocking cross-site referers just breaks a lot of sites.
// 0=always send referrer (default)
// 1=send across subdomains [from a.example.com to b.example.com] (breaks Instagram embeds, Bing login, MangaPill, and some streaming sites)
// 2=full host name must match [from c.example.com to c.example.com] (breaks Vimeo, iCloud, Instagram, Amazon book previews, and more)
// [TEST] https://www.jeffersonscher.com/res/jstest.php
// [1] https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy#examples
// [2] https://web.dev/referrer-best-practices/
//user_pref("network.http.referer.XOriginPolicy", 0); // DEFAULT
// PREF: control the amount of cross-origin information to send
// Controls how much referrer to send across origins (different domains).
// 0=send full URI (default), 1=scheme+host+port+path, 2=scheme+host+port
// [1] https://blog.mozilla.org/security/2021/03/22/firefox-87-trims-http-referrers-by-default-to-protect-user-privacy/
// [2] https://web.dev/referrer-best-practices/
// [3] https://www.reddit.com/r/waterfox/comments/16px8yq/comment/k29r6bu/?context=3
user_pref("network.http.referer.XOriginTrimmingPolicy", 2);
/******************************************************************************
* SECTION: CONTAINERS *
******************************************************************************/
// PREF: enable Container Tabs and its UI setting [FF50+]
// [NOTE] No longer a privacy benefit due to Firefox upgrades (see State Partitioning and Network Partitioning)
// Useful if you want to login to the same site under different accounts
// You also may want to download Multi-Account Containers for extra options (2)
// [SETTING] General>Tabs>Enable Container Tabs
// [1] https://wiki.mozilla.org/Security/Contextual_Identity_Project/Containers
// [2] https://addons.mozilla.org/en-US/firefox/addon/multi-account-containers/
user_pref("privacy.userContext.ui.enabled", true);
//user_pref("privacy.userContext.enabled", true);
// PREF: set behavior on "+ Tab" button to display container menu on left click [FF74+]
// [NOTE] The menu is always shown on long press and right click.
// [SETTING] General>Tabs>Enable Container Tabs>Settings>Select a container for each new tab
//user_pref("privacy.userContext.newTabContainerOnLeftClick.enabled", true);
// PREF: set external links to open in site-specific containers [FF123+]
// Depending on your container extension(s) and their settings:
// true=Firefox will not choose a container (so your extension can)
// false=Firefox will choose the container/no-container (default)
// [1] https://bugzilla.mozilla.org/1874599
//user_pref("browser.link.force_default_user_context_id_for_external_opens", true);
/******************************************************************************
* SECTION: WEBRTC *
******************************************************************************/
// PREF: disable WebRTC (Web Real-Time Communication)
// Firefox desktop uses mDNS hostname obfuscation and the private IP is never exposed until
// required in TRUSTED scenarios; i.e. after you grant device (microphone or camera) access.
// [TEST] https://browserleaks.com/webrtc
// [1] https://groups.google.com/g/discuss-webrtc/c/6stQXi72BEU/m/2FwZd24UAQAJ
// [2] https://datatracker.ietf.org/doc/html/draft-ietf-mmusic-mdns-ice-candidates#section-3.1.1
//user_pref("media.peerconnection.enabled", false);
// PREF: enable WebRTC Global Mute Toggles [NIGHTLY]
//user_pref("privacy.webrtc.globalMuteToggles", true);
// PREF: force WebRTC inside the proxy [FF70+]
//user_pref("media.peerconnection.ice.proxy_only_if_behind_proxy", true);
// PREF: force a single network interface for ICE candidates generation [FF42+]
// When using a system-wide proxy, it uses the proxy interface.
// [1] https://developer.mozilla.org/en-US/docs/Web/API/RTCIceCandidate
// [2] https://wiki.mozilla.org/Media/WebRTC/Privacy
// [3] https://github.com/zen-browser/desktop/issues/972
//user_pref("media.peerconnection.ice.default_address_only", true);
// PREF: force exclusion of private IPs from ICE candidates [FF51+]
// [SETUP-HARDEN] This will protect your private IP even in TRUSTED scenarios after you
// grant device access, but often results in breakage on video-conferencing platforms.
//user_pref("media.peerconnection.ice.no_host", true);
/******************************************************************************
* SECTION: PLUGINS *
******************************************************************************/
// PREF: disable GMP (Gecko Media Plugins)
// [1] https://wiki.mozilla.org/GeckoMediaPlugins
//user_pref("media.gmp-provider.enabled", false);
// PREF: disable widevine CDM (Content Decryption Module)
// [NOTE] This is covered by the EME master switch.
//user_pref("media.gmp-widevinecdm.enabled", false);
// PREF: disable all DRM content (EME: Encryption Media Extension)
// EME is a JavaScript API for playing DRMed (not free) video content in HTML.
// A DRM component called a Content Decryption Module (CDM) decrypts,
// decodes, and displays the video.
// e.g. Netflix, Amazon Prime, Hulu, HBO, Disney+, Showtime, Starz, DirectTV
// DRM is a propriety and closed source, but disabling is overkill.
// [SETTING] General>DRM Content>Play DRM-controlled content
// [TEST] https://bitmovin.com/demos/drm
// [1] https://www.eff.org/deeplinks/2017/10/drms-dead-canary-how-we-just-lost-web-what-we-learned-it-and-what-we-need-do-next
// [2] https://www.reddit.com/r/firefox/comments/10gvplf/comment/j55htc7
//user_pref("media.eme.enabled", false);
// Optionally, hide the setting which also disables the DRM prompt:
//user_pref("browser.eme.ui.enabled", false);
/******************************************************************************
* SECTION: JIT *
******************************************************************************/
// PREF: Just-In-Time Compilation
// Around half of zero-day exploits are directly related to "just in time"
// (JIT) compilers, and disabling that can greatly improve your protection against
// these potential exploits.
// [1] https://microsoftedge.github.io/edgevr/posts/Super-Duper-Secure-Mode/
// [2] https://www.youtube.com/watch?v=i7qlZeDt9o4
// PREF: JavaScript JIT
// PREF: disable Ion and baseline JIT to harden against JS exploits
// [NOTE] When both Ion and JIT are disabled, and trustedprincipals
// is enabled, then Ion can still be used by extensions [4].
// Tor Browser doesn't even ship with these disabled by default.
// [1] https://cve.mitre.org/cgi-bin/cvekey.cgi?keyword=firefox+jit
// [2] https://microsoftedge.github.io/edgevr/posts/Super-Duper-Secure-Mode/
// [3] https://support.microsoft.com/en-us/microsoft-edge/enhance-your-security-on-the-web-with-microsoft-edge-b8199f13-b21b-4a08-a806-daed31a1929d
// [4] https://bugzilla.mozilla.org/show_bug.cgi?id=1599226
// [5] https://wiki.mozilla.org/IonMonkey
// [6] https://github.com/arkenfox/user.js/issues/1791#issuecomment-1891273681
//user_pref("javascript.options.baselinejit", false);
//user_pref("javascript.options.ion", false);
//user_pref("javascript.options.jit_trustedprincipals", false);
// PREF: WebAssembly JIT [FF52+]
// Vulnerabilities [1] have increasingly been found, including those known and fixed
// in native programs years ago [2]. WASM has powerful low-level access, making
// certain attacks (brute-force) and vulnerabilities more possible.
// [STATS] ~0.2% of websites, about half of which are for cryptomining / malvertising [2][3]
// [1] https://cve.mitre.org/cgi-bin/cvekey.cgi?keyword=wasm
// [2] https://spectrum.ieee.org/tech-talk/telecom/security/more-worries-over-the-security-of-web-assembly
// [3] https://www.zdnet.com/article/half-of-the-websites-using-webassembly-use-it-for-malicious-purposes
//user_pref("javascript.options.wasm", false);
//user_pref("javascript.options.wasm_trustedprincipals", false);
//user_pref("javascript.options.wasm_baselinejit", false);
//user_pref("javascript.options.wasm_optimizingjit", false);
// PREF: Asm.js JIT [FF22+]
// [1] http://asmjs.org/
// [2] https://cve.mitre.org/cgi-bin/cvekey.cgi?keyword=asm.js
// [3] https://rh0dev.github.io/blog/2017/the-return-of-the-jit/
//user_pref("javascript.options.asmjs", false);
// PREF: Blinterp (JIT-like)
//user_pref("javascript.options.blinterp", false);
/******************************************************************************
* SECTION: VARIOUS *
******************************************************************************/
// PREF: decode URLs in other languages
// [WARNING] Causes unintended consequences when copy+paste links with underscores.
// [1] https://bugzilla.mozilla.org/show_bug.cgi?id=1320061
//user_pref("browser.urlbar.decodeURLsOnCopy", false); // DEFAULT
// PREF: number of usages of the web console
// If this is less than 5, then pasting code into the web console is disabled.
//user_pref("devtools.selfxss.count", 5);
// PREF: disable middle click on new tab button opening URLs or searches using clipboard [FF115+]
// Enable if you're using LINUX.
//user_pref("browser.tabs.searchclipboardfor.middleclick", false); // DEFAULT WINDOWS macOS
// PREF: do not allow PDFs to load javascript
// [1] https://www.reddit.com/r/uBlockOrigin/comments/mulc86/firefox_88_now_supports_javascript_in_pdf_files/
// PREF: enforce PDFJS, disable PDFJS scripting
// This setting controls if the option "Display in Firefox" is available in the setting below
// and by effect controls whether PDFs are handled in-browser or externally ("Ask" or "Open With").
// [WHY] pdfjs is lightweight, open source, and secure: the last exploit was June 2015 [1].
// It doesn't break "state separation" of browser content (by not sharing with OS, independent apps).
// It maintains disk avoidance and application data isolation. It's convenient. You can still save to disk.
// [NOTE] JS can still force a pdf to open in-browser by bundling its own code.
// [SETUP-CHROME] You may prefer a different pdf reader for security/workflow reasons.
// [SETTING] General>Applications>Portable Document Format (PDF)
// [1] https://cve.mitre.org/cgi-bin/cvekey.cgi?keyword=pdf.js+firefox
// [2] https://www.reddit.com/r/uBlockOrigin/comments/mulc86/firefox_88_now_supports_javascript_in_pdf_files/
//user_pref("pdfjs.disabled", false); // [DEFAULT: false]
user_pref("pdfjs.enableScripting", false); // [FF86+]
/******************************************************************************
* SECTION: SAFE BROWSING (SB) *
******************************************************************************/
// A full url is never sent to Google, only a part-hash of the prefix,
// hidden with noise of other real part-hashes. Firefox takes measures such as
// stripping out identifying parameters, and since SBv4 (FF57+), doesn't even use cookies.
// (Turn on browser.safebrowsing.debug to monitor this activity)
// [1] https://feeding.cloud.geek.nz/posts/how-safe-browsing-works-in-firefox/
// [2] https://wiki.mozilla.org/Security/Safe_Browsing
// [3] https://support.mozilla.org/kb/how-does-phishing-and-malware-protection-work
// [4] https://educatedguesswork.org/posts/safe-browsing-privacy/
// [5] https://www.google.com/chrome/privacy/whitepaper.html#malware
// [6] https://security.googleblog.com/2022/08/how-hash-based-safe-browsing-works-in.html
// PREF: Safe Browsing
// [WARNING] Be sure to have alternate security measures if you disable SB! Adblockers do not count!
// [SETTING] Privacy & Security>Security>... Block dangerous and deceptive content
// [ALTERNATIVE] Enable local checks only: https://github.com/yokoffing/Betterfox/issues/87
// [1] https://support.mozilla.org/en-US/kb/how-does-phishing-and-malware-protection-work#w_what-information-is-sent-to-mozilla-or-its-partners-when-phishing-and-malware-protection-is-enabled
// [2] https://wiki.mozilla.org/Security/Safe_Browsing
// [3] https://developers.google.com/safe-browsing/v4
// [4] https://github.com/privacyguides/privacyguides.org/discussions/423#discussioncomment-1752006
// [5] https://github.com/privacyguides/privacyguides.org/discussions/423#discussioncomment-1767546
// [6] https://wiki.mozilla.org/Security/Safe_Browsing
// [7] https://ashkansoltani.org/2012/02/25/cookies-from-nowhere (outdated)
// [8] https://blog.cryptographyengineering.com/2019/10/13/dear-apple-safe-browsing-might-not-be-that-safe/ (outdated)
// [9] https://the8-bit.com/apple-proxies-google-safe-browsing-privacy/
// [10] https://github.com/brave/brave-browser/wiki/Deviations-from-Chromium-(features-we-disable-or-remove)#services-we-proxy-through-brave-servers
//user_pref("browser.safebrowsing.malware.enabled", false); // all checks happen locally
//user_pref("browser.safebrowsing.phishing.enabled", false); // all checks happen locally
//user_pref("browser.safebrowsing.blockedURIs.enabled", false); // all checks happen locally
//user_pref("browser.safebrowsing.provider.google4.gethashURL", "");
//user_pref("browser.safebrowsing.provider.google4.updateURL", "");
//user_pref("browser.safebrowsing.provider.google.gethashURL", "");
//user_pref("browser.safebrowsing.provider.google.updateURL", "");
// PREF: disable SB checks for downloads
// This is the master switch for the safebrowsing.downloads prefs (both local lookups + remote).
// [NOTE] Still enable this for checks to happen locally.
// [SETTING] Privacy & Security>Security>... "Block dangerous downloads"
//user_pref("browser.safebrowsing.downloads.enabled", false); // all checks happen locally
// PREF: disable SB checks for downloads (remote)
// To verify the safety of certain executable files, Firefox may submit some information about the
// file, including the name, origin, size and a cryptographic hash of the contents, to the Google
// Safe Browsing service which helps Firefox determine whether or not the file should be blocked.
// [NOTE] If you do not understand the consequences, override this.
user_pref("browser.safebrowsing.downloads.remote.enabled", false);
//user_pref("browser.safebrowsing.downloads.remote.url", "");
// disable SB checks for unwanted software
// [SETTING] Privacy & Security>Security>... "Warn you about unwanted and uncommon software"
//user_pref("browser.safebrowsing.downloads.remote.block_potentially_unwanted", false);
//user_pref("browser.safebrowsing.downloads.remote.block_uncommon", false);
// PREF: allow user to "ignore this warning" on SB warnings
// If clicked, it bypasses the block for that session. This is a means for admins to enforce SB.
// Report false positives to [2]
// [TEST] see https://github.com/arkenfox/user.js/wiki/Appendix-A-Test-Sites#-mozilla
// [1] https://bugzilla.mozilla.org/1226490
// [2] https://safebrowsing.google.com/safebrowsing/report_general/
//user_pref("browser.safebrowsing.allowOverride", true); // DEFAULT
/******************************************************************************
* SECTION: MOZILLA *
******************************************************************************/
// PREF: prevent accessibility services from accessing your browser [RESTART]
// Accessibility Service may negatively impact Firefox browsing performance.
// Disable it if you’re not using any type of physical impairment assistive software.
// [1] https://support.mozilla.org/kb/accessibility-services
// [2] https://www.ghacks.net/2021/08/25/firefox-tip-turn-off-accessibility-services-to-improve-performance/
// [3] https://www.reddit.com/r/firefox/comments/p8g5zd/why_does_disabling_accessibility_services_improve
// [4] https://winaero.com/firefox-has-accessibility-service-memory-leak-you-should-disable-it/
// [5] https://www.ghacks.net/2022/12/26/firefoxs-accessibility-performance-is-getting-a-huge-boost/
//user_pref("accessibility.force_disabled", 1);
//user_pref("devtools.accessibility.enabled", false);
// PREF: disable Firefox Sync
// [ALTERNATIVE] Use xBrowserSync [1]
// [1] https://addons.mozilla.org/en-US/firefox/addon/xbs
// [2] https://github.com/arkenfox/user.js/issues/1175
//user_pref("identity.fxaccounts.enabled", false);
//user_pref("identity.fxaccounts.autoconfig.uri", "");
// PREF: disable Firefox View [FF106+]
// You can no longer disable Firefox View as of [FF127+].
// To hide the icon from view, see [2].
// [1] https://support.mozilla.org/en-US/kb/how-set-tab-pickup-firefox-view#w_what-is-firefox-view
// [2] https://support.mozilla.org/en-US/kb/how-set-tab-pickup-firefox-view#w_how-do-i-remove-firefox-view-from-the-tabs-bar
// PREF: disable the Firefox View tour from popping up
//user_pref("browser.firefox-view.feature-tour", "{\"screen\":\"\",\"complete\":true}");
// PREF: disable Push Notifications API [FF44+]
// [WHY] Website "push" requires subscription, and the API is required for CRLite.
// Push is an API that allows websites to send you (subscribed) messages even when the site
// isn't loaded, by pushing messages to your userAgentID through Mozilla's Push Server.
// You shouldn't need to disable this.
// [NOTE] To remove all subscriptions, reset "dom.push.userAgentID"
// [1] https://support.mozilla.org/en-US/kb/push-notifications-firefox
// [2] https://developer.mozilla.org/en-US/docs/Web/API/Push_API
// [3] https://www.reddit.com/r/firefox/comments/fbyzd4/the_most_private_browser_isnot_firefox/
//user_pref("dom.push.enabled", false);
//user_pref("dom.push.userAgentID", "");
// PREF: default permission for Web Notifications
// To add site exceptions: Page Info>Permissions>Receive Notifications
// To manage site exceptions: Options>Privacy & Security>Permissions>Notifications>Settings
// 0=always ask (default), 1=allow, 2=block
// [1] https://easylinuxtipsproject.blogspot.com/p/security.html#ID5
// [2] https://github.com/yokoffing/Betterfox/wiki/Common-Overrides#site-notifications
user_pref("permissions.default.desktop-notification", 2);
// PREF: default permission for Location Requests
// 0=always ask (default), 1=allow, 2=block
user_pref("permissions.default.geo", 2);
// PREF: use alternative geolocation service instead of Google
// [NOTE] Mozilla's geolocation service was discontinued in June 2024 [1].
// BeaconDB is its replacement.
// [1] https://github.com/mozilla/ichnaea/issues/2065
// [2] https://codeberg.org/beacondb/beacondb
// [3] https://github.com/yokoffing/Betterfox/issues/378
user_pref("geo.provider.network.url", "https://beacondb.net/v1/geolocate");
// PREF: disable using the OS's geolocation service
//user_pref("geo.provider.ms-windows-location", false); // [WINDOWS]
//user_pref("geo.provider.use_corelocation", false); // [MAC]
//user_pref("geo.provider.use_geoclue", false); // [FF102+] [LINUX]
// PREF: logging geolocation to the console
//user_pref("geo.provider.network.logging.enabled", true);
// PREF: disable region updates
// [1] https://firefox-source-docs.mozilla.org/toolkit/modules/toolkit_modules/Region.html
//user_pref("browser.region.update.enabled", false);
//user_pref("browser.region.network.url", "");
// PREF: enforce Firefox blocklist for extensions + no hiding tabs
// This includes updates for "revoked certificates".
// [1] https://blog.mozilla.org/security/2015/03/03/revoking-intermediate-certificates-introducing-onecrl/
// [2] https://trac.torproject.org/projects/tor/ticket/16931
//user_pref("extensions.blocklist.enabled", true); // DEFAULT
// PREF: disable auto-INSTALLING Firefox updates [NON-WINDOWS]
// [NOTE] In FF65+ on Windows this SETTING (below) is now stored in a file and the pref was removed.
// [SETTING] General>Firefox Updates>Check for updates but let you choose to install them
//user_pref("app.update.auto", false);
// PREF: disable automatic extension updates
//user_pref("extensions.update.enabled", false);
// PREF: disable search engine updates (e.g. OpenSearch)
// Prevent Firefox from adding back search engines after you removed them.
// [NOTE] This does not affect Mozilla's built-in or Web Extension search engines.
user_pref("browser.search.update", false);
// PREF: remove special permissions for certain mozilla domains [FF35+]
// default = resource://app/defaults/permissions
user_pref("permissions.manager.defaultsUrl", "");
// PREF: remove webchannel whitelist
//user_pref("webchannel.allowObject.urlWhitelist", ""); // [DEFAULT FF132+]
// PREF: disable metadata caching for installed add-ons by default
// [1] https://blog.mozilla.org/addons/how-to-opt-out-of-add-on-metadata-updates/
user_pref("extensions.getAddons.cache.enabled", false);
/******************************************************************************
* SECTION: TELEMETRY *
******************************************************************************/
// PREF: disable new data submission [FF41+]
// If disabled, no policy is shown or upload takes place, ever.
// [1] https://bugzilla.mozilla.org/1195552
user_pref("datareporting.policy.dataSubmissionEnabled", false);
// PREF: disable Health Reports
// [SETTING] Privacy & Security>Firefox Data Collection & Use>Allow Firefox to send technical data.
user_pref("datareporting.healthreport.uploadEnabled", false);
// PREF: disable telemetry
// - If "unified" is false then "enabled" controls the telemetry module
// - If "unified" is true then "enabled" only controls whether to record extended data
// [NOTE] "toolkit.telemetry.enabled" is now LOCKED to reflect prerelease (true) or release builds (false) [2]
// [1] https://firefox-source-docs.mozilla.org/toolkit/components/telemetry/telemetry/internals/preferences.html
// [2] https://medium.com/georg-fritzsche/data-preference-changes-in-firefox-58-2d5df9c428b5
user_pref("toolkit.telemetry.unified", false);
user_pref("toolkit.telemetry.enabled", false); // see [NOTE]
user_pref("toolkit.telemetry.server", "data:,");
user_pref("toolkit.telemetry.archive.enabled", false);
user_pref("toolkit.telemetry.newProfilePing.enabled", false);
user_pref("toolkit.telemetry.shutdownPingSender.enabled", false);
user_pref("toolkit.telemetry.updatePing.enabled", false);
user_pref("toolkit.telemetry.bhrPing.enabled", false); // [FF57+] Background Hang Reporter
user_pref("toolkit.telemetry.firstShutdownPing.enabled", false);
//user_pref("toolkit.telemetry.dap_enabled", false); // DEFAULT [FF108]
// PREF: disable Telemetry Coverage
// [1] https://blog.mozilla.org/data/2018/08/20/effectively-measuring-search-in-firefox/
// [2] https://github.com/yokoffing/Betterfox/issues/443
user_pref("toolkit.telemetry.coverage.opt-out", true); // [HIDDEN PREF]
user_pref("toolkit.coverage.opt-out", true); // [FF64+] [HIDDEN PREF]
user_pref("toolkit.coverage.endpoint.base", "");
// PREF: disable Firefox Home (Activity Stream) telemetry
user_pref("browser.newtabpage.activity-stream.feeds.telemetry", false);
user_pref("browser.newtabpage.activity-stream.telemetry", false);
// PREF: disable daily active users [FF136+]
user_pref("datareporting.usage.uploadEnabled", false);
/******************************************************************************
* SECTION: EXPERIMENTS *
******************************************************************************/
// PREF: disable Studies
// [SETTING] Privacy & Security>Firefox Data Collection & Use>Allow Firefox to install and run studies
user_pref("app.shield.optoutstudies.enabled", false);
// PREF: disable Normandy/Shield [FF60+]
// Shield is an telemetry system (including Heartbeat) that can also push and test "recipes".
// [1] https://mozilla.github.io/normandy/
user_pref("app.normandy.enabled", false);
user_pref("app.normandy.api_url", "");
/******************************************************************************
* SECTION: CRASH REPORTS *
******************************************************************************/
// PREF: disable crash reports
user_pref("breakpad.reportURL", "");
user_pref("browser.tabs.crashReporting.sendReport", false);
//user_pref("browser.crashReports.unsubmittedCheck.enabled", false); // DEFAULT
// PREF: enforce no submission of backlogged crash reports
// [SETTING] Privacy & Security>Firefox Data Collection & Use>Allow Firefox to send backlogged crash reports
//user_pref("browser.crashReports.unsubmittedCheck.autoSubmit2", false); // [DEFAULT FF132+]
/******************************************************************************
* SECTION: DETECTION *
******************************************************************************/
// PREF: disable Captive Portal detection
// [WARNING] Do NOT use for mobile devices. May NOT be able to use Firefox on public wifi (hotels, coffee shops, etc).
// [1] https://www.eff.org/deeplinks/2017/08/how-captive-portals-interfere-wireless-security-and-privacy
// [2] https://wiki.mozilla.org/Necko/CaptivePortal
//user_pref("captivedetect.canonicalURL", "");
//user_pref("network.captive-portal-service.enabled", false);
// PREF: disable Network Connectivity checks
// [WARNING] Do NOT use for mobile devices. May NOT be able to use Firefox on public wifi (hotels, coffee shops, etc).
// [1] https://bugzilla.mozilla.org/1460537
//user_pref("network.connectivity-service.enabled", false);
// PREF: disable Privacy-Preserving Attribution [FF128+]
// [NOTE] PPA disabled if main telemetry switches are disabled.
// [SETTING] Privacy & Security>Website Advertising Preferences>Allow websites to perform privacy-preserving ad measurement
// [1] https://support.mozilla.org/kb/privacy-preserving-attribution
// [2] https://searchfox.org/mozilla-central/rev/f3e4b33a6122ce63bf81ae8c30cc5ac37458864b/dom/privateattribution/PrivateAttributionService.sys.mjs#267
//user_pref("dom.private-attribution.submission.enabled", false);
//user_pref("toolkit.telemetry.dap_helper", ""); // [OPTIONAL HARDENING]
//user_pref("toolkit.telemetry.dap_leader", ""); // [OPTIONAL HARDENING]
// PREF: software that continually reports what default browser you are using [WINDOWS]
// [WARNING] Breaks "Make Default..." button in Preferences to set Firefox as the default browser [2].
// [1] https://techdows.com/2020/04/what-is-firefox-default-browser-agent-and-how-to-disable-it.html
// [2] https://github.com/yokoffing/Betterfox/issues/166
//user_pref("default-browser-agent.enabled", false);
// PREF: "report extensions for abuse"
//user_pref("extensions.abuseReport.enabled", false);
// PREF: SERP Telemetry [FF125+]
// [1] https://blog.mozilla.org/en/products/firefox/firefox-search-update/
//user_pref("browser.search.serpEventTelemetryCategorization.enabled", false);
// PREF: assorted telemetry
// [NOTE] Shouldn't be needed for user.js, but browser forks may want to disable these prefs.
//user_pref("doh-rollout.disable-heuristics", true); // ensure DoH doesn't get enabled automatically
//user_pref("dom.security.unexpected_system_load_telemetry_enabled", false);
//user_pref("messaging-system.rsexperimentloader.enabled", false);
//user_pref("network.trr.confirmation_telemetry_enabled", false);
//user_pref("security.app_menu.recordEventTelemetry", false);
//user_pref("security.certerrors.mitm.priming.enabled", false);
//user_pref("security.certerrors.recordEventTelemetry", false);
//user_pref("security.protectionspopup.recordEventTelemetry", false);
//user_pref("signon.recipes.remoteRecipes.enabled", false);
//user_pref("privacy.trackingprotection.emailtracking.data_collection.enabled", false);
//user_pref("messaging-system.askForFeedback", true); // DEFAULT [FF120+]
| yokoffing/Betterfox | 10,046 | Firefox user.js for optimal privacy and security. Your favorite browser, but better. | JavaScript | yokoffing | ||
Smoothfox.js | JavaScript |
/****************************************************************************************
* Smoothfox *
* "Faber est suae quisque fortunae" *
* priority: better scrolling *
* version: 137 *
* url: https://github.com/yokoffing/Betterfox *
***************************************************************************************/
// Use only one option at a time!
// Reset prefs if you decide to use different option.
/****************************************************************************************
* OPTION: SHARPEN SCROLLING *
****************************************************************************************/
// credit: https://github.com/black7375/Firefox-UI-Fix
// only sharpen scrolling
user_pref("apz.overscroll.enabled", true); // DEFAULT NON-LINUX
user_pref("general.smoothScroll", true); // DEFAULT
user_pref("mousewheel.min_line_scroll_amount", 10); // adjust this number to your liking; default=5
user_pref("general.smoothScroll.mouseWheel.durationMinMS", 80); // default=50
user_pref("general.smoothScroll.currentVelocityWeighting", "0.15"); // default=.25
user_pref("general.smoothScroll.stopDecelerationWeighting", "0.6"); // default=.4
// Firefox Nightly only:
// [1] https://bugzilla.mozilla.org/show_bug.cgi?id=1846935
user_pref("general.smoothScroll.msdPhysics.enabled", false); // [FF122+ Nightly]
/****************************************************************************************
* OPTION: INSTANT SCROLLING (SIMPLE ADJUSTMENT) *
****************************************************************************************/
// recommended for 60hz+ displays
user_pref("apz.overscroll.enabled", true); // DEFAULT NON-LINUX
user_pref("general.smoothScroll", true); // DEFAULT
user_pref("mousewheel.default.delta_multiplier_y", 275); // 250-400; adjust this number to your liking
// Firefox Nightly only:
// [1] https://bugzilla.mozilla.org/show_bug.cgi?id=1846935
user_pref("general.smoothScroll.msdPhysics.enabled", false); // [FF122+ Nightly]
/****************************************************************************************
* OPTION: SMOOTH SCROLLING *
****************************************************************************************/
// recommended for 90hz+ displays
user_pref("apz.overscroll.enabled", true); // DEFAULT NON-LINUX
user_pref("general.smoothScroll", true); // DEFAULT
user_pref("general.smoothScroll.msdPhysics.enabled", true);
user_pref("mousewheel.default.delta_multiplier_y", 300); // 250-400; adjust this number to your liking
/****************************************************************************************
* OPTION: NATURAL SMOOTH SCROLLING V3 [MODIFIED] *
****************************************************************************************/
// credit: https://github.com/AveYo/fox/blob/cf56d1194f4e5958169f9cf335cd175daa48d349/Natural%20Smooth%20Scrolling%20for%20user.js
// recommended for 120hz+ displays
// largely matches Chrome flags: Windows Scrolling Personality and Smooth Scrolling
user_pref("apz.overscroll.enabled", true); // DEFAULT NON-LINUX
user_pref("general.smoothScroll", true); // DEFAULT
user_pref("general.smoothScroll.msdPhysics.continuousMotionMaxDeltaMS", 12);
user_pref("general.smoothScroll.msdPhysics.enabled", true);
user_pref("general.smoothScroll.msdPhysics.motionBeginSpringConstant", 600);
user_pref("general.smoothScroll.msdPhysics.regularSpringConstant", 650);
user_pref("general.smoothScroll.msdPhysics.slowdownMinDeltaMS", 25);
user_pref("general.smoothScroll.msdPhysics.slowdownMinDeltaRatio", "2");
user_pref("general.smoothScroll.msdPhysics.slowdownSpringConstant", 250);
user_pref("general.smoothScroll.currentVelocityWeighting", "1");
user_pref("general.smoothScroll.stopDecelerationWeighting", "1");
user_pref("mousewheel.default.delta_multiplier_y", 300); // 250-400; adjust this number to your liking
| yokoffing/Betterfox | 10,046 | Firefox user.js for optimal privacy and security. Your favorite browser, but better. | JavaScript | yokoffing | ||
install.py | Python | #!/usr/bin/env python3
from datetime import datetime
from os import name, getenv
from json import loads
from re import compile, IGNORECASE, sub
from pathlib import Path
from configparser import ConfigParser
from argparse import ArgumentParser
from shutil import copytree, ignore_patterns
from urllib.request import urlopen
from subprocess import check_output
from io import BytesIO
from zipfile import ZipFile
"""
install(-betterfox).py
Usage:
python install.py
When called without arguments, it will:
- Backup your current firefox profile
- Automatically download user.js from the latest Betterfox release compatible with your Firefox version into the profile
- Apply user-overrides in the same directory
However, you can check out install.py/betterfox-install.exe --help to customise most behaviours!
Limitations:
- When using a different repositoy as a source, that repository needs to use the same releases workflow
- Over time, the get_releases might not list older releases due to limited page size. This can be expanded down the road, though
Building into an exe (on Windows):
- pipx install pyinstaller (note: you can try without pipx, but this didn't work for me)
- Run:
- CMD: `pyinstaller --onefile --name install-betterfox install.py && move %cd%\\dist\\install-betterfox.exe %cd% && del install-betterfox.spec && rmdir /S /Q build && rmdir dist`
- BASH: `pyinstaller --onefile --name install-betterfox install.py && && mv dist/install-betterfox.exe . && rm install-betterfox.spec && rm -rf ./build/ && rmdir dist`
(Sorry, didn't want to add a .gitignore solely for the install script)
- Done!
If there's any problems with the script, feel free to mention @Denperidge on GitHub!
"""
re_find_version = compile(r"mozilla.org/.*?/firefox/(?P<version>[\d.]*?)/", IGNORECASE)
re_find_overrides = r"(overrides|prefs).*\n(?P<space>\n)"
INSTALLATIONS_TO_CHECK = [
# windows
{
"command": [str(Path("C:/Program Files/Mozilla Firefox/firefox"))],
"root": Path(getenv("APPDATA") or "").joinpath("Mozilla/Firefox").resolve(),
},
{
"command": [str(Path(getenv("LOCALAPPDATA") or "").joinpath("Mozilla Firefox/firefox").resolve())],
"root": Path(getenv("APPDATA") or "").joinpath("Mozilla/Firefox").resolve(),
},
# linux
{
"command": ["firefox"],
"root": Path.home().joinpath(".mozilla/firefox").absolute(),
},
# flatpak
{
"command": ["flatpak", "run", "org.mozilla.firefox"],
"root": Path.home().joinpath(".var/app/org.mozilla.firefox/.mozilla/firefox").absolute(),
},
# macOS
{
"command": ["/Applications/Firefox.app/Contents/MacOS/firefox"],
"root": Path.home().joinpath("Library/Application Support/Firefox").absolute(),
},
]
# command is a list, eg. ["firefox"] or ["flatpak", "run", "org.mozilla.firefox"]
def _get_firefox_version(command):
ver_string = check_output(command + ["--version"], encoding="UTF-8")
return ver_string[ver_string.rindex(" ")+1:].strip()
def _get_default_firefox_version_and_root():
print("Searching for Firefox installation...")
for installation in INSTALLATIONS_TO_CHECK:
try:
print(f" '{' '.join(installation['command'])}': ", end="")
version = _get_firefox_version(installation["command"])
print("YES")
print(f"Root: {installation['root']}")
return version, installation["root"]
except Exception:
print("no")
continue
raise Exception("Firefox binary not found. Please ensure Firefox is installed and the path is correct.")
def _get_default_profile_folder(firefox_root):
config_path = firefox_root.joinpath("profiles.ini")
print(f"Reading {config_path}...")
config_parser = ConfigParser(strict=False)
config_parser.read(config_path)
path = None
for section in config_parser.sections():
if "Default" in config_parser[section]:
section_default_value = config_parser[section]["Default"]
if section_default_value:
print("Default detected from section: " + section)
# Confirm whether a 0 value is possible, keep fallback until then
if section_default_value == "0":
continue
if section_default_value == "1":
path = config_parser[section]["Path"]
else:
path = section_default_value
break
if path is not None:
return firefox_root.joinpath(path)
else:
raise Exception("Could not determine default Firefox profile! Exiting...")
def _get_releases(repository_owner, repository_name):
releases = []
raw_releases = loads(urlopen(f"https://api.github.com/repos/{repository_owner}/{repository_name}/releases").read())
for raw_release in raw_releases:
name = raw_release["name"] or raw_release["tag_name"] # or fixes 126.0 not being lodaded
body = raw_release["body"]
# Find which firefox releases are supported. Manual overrides for ones that don't have it written in their thing!
if name == "user.js v.122.1":
supported = ["107.0", "107.1", "108.0", "108.0.1", "108.0.2", "109.0", "109.0", "110.1", "110.0.1", "111.0", "111.0.1", "112.0", "112.0.1", "112.0.2", "113.0", "113.0.1", "113.0.2", "114.0", "114.0.1", "114.0.2", "115.0", "115.0.1", "115.0.2", "115.0.3", "115.1.0", "115.10.0", "115.11.0", "115.12.0", "115.13.0", "115.14.0", "115.15.0", "115.16.0", "115.16.1", "115.17.0", "115.2.0", "115.2.1", "115.3.0", "115.3.1", "115.4.0", "115.5.0", "115.6.0", "115.7.0", "115.8.0", "115.9.0", "115.9.1", "116.0", "116.0.1", "116.0.2", "116.0.3", "117.0", "117.0.1", "118.0", "118.0.1", "118.0.2", "119.0", "119.0.1", "120.0", "120.0.1", "121.0", "121.0.1", "122.0", "122.0.1"]
elif name == "user.js 116.1":
supported = ["116.0", "116.0.1", "116.0.2", "116.0.3"]
elif name == "Betterfox v.107":
supported = ["107.0"]
elif "firefox release" in body.lower():
trim_body = body.lower()[body.lower().index("firefox release"):]
supported = re_find_version.findall(trim_body)
if len(supported) == 0:
print(f"Could not parse release in '{name}'. Please post this error message on https://github.com/{repository_owner}/{repository_name}/issues")
continue
else:
print(f"Could not find firefox release header '{name}'. Please post this error message on https://github.com/{repository_owner}/{repository_name}/issues")
continue
releases.append({
"name": name,
"url": raw_release["zipball_url"],
"supported": supported,
})
return releases
def _get_latest_compatible_release(releases):
for release in releases:
if firefox_version in release["supported"]:
return release
return None
def backup_profile(src):
dest = f"{src}-backup-{datetime.today().strftime('%Y-%m-%d-%H-%M-%S')}"
copytree(src, dest, ignore=ignore_patterns("*lock"))
print("Backed up profile to " + dest)
def download_betterfox(url):
data = BytesIO()
data.write(urlopen(url).read())
return data
def extract_betterfox(data, profile_folder):
zipfile = ZipFile(data)
userjs_zipinfo = None
for file in zipfile.filelist:
if "/zen/" in file.filename and not args.zen:
continue
if file.filename.endswith("user.js"):
userjs_zipinfo = file
userjs_zipinfo.filename = Path(userjs_zipinfo.filename).name
if not userjs_zipinfo:
raise BaseException("Could not find user.js!")
return zipfile.extract(userjs_zipinfo, profile_folder)
def list_releases(releases, only_supported=False, add_index=False):
print()
print(f"Listing {'compatible' if only_supported else 'all'} Betterfox releases:")
if only_supported:
print("Use --list-all to view all available releases")
else:
print(f"Releases marked with '> ' are documented to be compatible with your Firefox version ({firefox_version})")
print()
i = 0
for release in releases:
supported = firefox_version in release["supported"]
if not only_supported or (only_supported and supported):
print(f"{f'[{i}]' if add_index else ''}{'> ' if supported else ' '}{release['name'].ljust(20)}\t\t\tSupported: {','.join(release['supported'])}")
i+=1
def _press_enter_to_exit(args):
if not args.no_wait_for_exit:
input("Press ENTER to exit...")
if __name__ == "__main__":
firefox_version, firefox_root = _get_default_firefox_version_and_root()
default_profile_folder = _get_default_profile_folder(firefox_root)
argparser = ArgumentParser(
)
argparser.add_argument("--overrides", "-o", default=default_profile_folder.joinpath("user-overrides.js"), help="if the provided file exists, add overrides to user.js. Defaults to " + str(default_profile_folder.joinpath("user-overrides.js"))),
argparser.add_argument("--zen", "-z", action="store_true", default=False, help="Install user.js for the Zen browser instead. Defaults to False"),
advanced = argparser.add_argument_group("Advanced")
advanced.add_argument("--betterfox-version", "-bv", default=None, help=f"Which version of Betterfox to install. Defaults to the latest compatible release for your installed Firefox version")
advanced.add_argument("--profile-dir", "-p", "-pd", default=default_profile_folder, help=f"Which profile dir to install user.js in. Defaults to {default_profile_folder}")
advanced.add_argument("--repository-owner", "-ro", default="yokoffing", help="owner of the Betterfox repository. Defaults to yokoffing")
advanced.add_argument("--repository-name", "-rn", default="Betterfox", help="name of the Betterfox repository. Defaults to Betterfox")
disable = argparser.add_argument_group("Disable functionality")
disable.add_argument("--no-backup", "-nb", action="store_true", default=False, help="disable backup of current profile (not recommended)"),
disable.add_argument("--no-install", "-ni", action="store_true", default=False, help="don't install Betterfox"),
modes = argparser.add_mutually_exclusive_group()
modes.add_argument("--list", action="store_true", default=False, help=f"List all Betterfox releases compatible with your version of Firefox ({firefox_version})")
modes.add_argument("--list-all", action="store_true", default=False, help=f"List all Betterfox releases")
modes.add_argument("--interactive", "-i", action="store_true", default=False, help=f"Interactively select Betterfox version")
behaviour = argparser.add_argument_group("Script behaviour")
behaviour.add_argument("--no-wait-for-exit", "-nwfe", action="store_true", default=False, help="Disable 'Press ENTER to exit...' and exit immediately"),
args = argparser.parse_args()
releases = _get_releases(args.repository_owner, args.repository_name)
selected_release = None
if args.list or args.list_all:
list_releases(releases, args.list)
_press_enter_to_exit(args)
exit()
if not args.no_backup:
backup_profile(args.profile_dir)
if args.betterfox_version:
# If not None AND not string, default value has been used
if not isinstance(args.betterfox_version, str):
selected_release = args.betterfox_version
print(f"Using latest compatible Betterfox version ({selected_release['name']})...")
# If string has been passed
else:
selected_release = next(rel for rel in releases if rel['name'] == args.betterfox_version)
print(f"Using manually selected Betterfox version ({selected_release['name']})")
if not args.betterfox_version:
selected_release = _get_latest_compatible_release(releases)
if args.interactive or not selected_release:
if not selected_release:
print("Could not find a compatible Betterfox version for your Firefox installation.")
list_releases(releases, False, True)
selection = int(input(f"Select Betterfox version, or press enter without typing a number to cancel [0-{len(releases) - 1}]: "))
selected_release = releases[selection]
if not args.no_install:
userjs_path = extract_betterfox(
download_betterfox(selected_release["url"]),
args.profile_dir
)
print(f"Installed user.js to {userjs_path} !")
if Path(args.overrides).exists():
print("Found overrides at " + str(args.overrides))
with open(str(args.overrides), "r", encoding="utf-8") as overrides_file:
overrides = overrides_file.read()
with open(userjs_path, "r", encoding="utf-8") as userjs_file:
old_content = userjs_file.read()
new_content = sub(re_find_overrides, "\n" + overrides + "\n", old_content, count=1, flags=IGNORECASE)
with open(userjs_path, "w", encoding="utf-8") as userjs_file:
userjs_file.write(new_content)
else:
print(f"Found no overrides in {args.overrides}")
_press_enter_to_exit(args)
| yokoffing/Betterfox | 10,046 | Firefox user.js for optimal privacy and security. Your favorite browser, but better. | JavaScript | yokoffing | ||
personal/user-overrides.js | JavaScript |
/****************************************************************************
* *
* DISCLAIMER *
* *
* This file is NOT INTENDED FOR OFFICIAL USE *
* It is a mix of PERSONAL and TESTING prefs and *
* may cause breakage or contain changes you do not want! *
* DO NOT USE unless you know what you are doing! *
* *
****************************************************************************/
/****************************************************************************
* START: MY OVERRIDES *
****************************************************************************/
/** SETUP ON FIRST INSTALLATION ***/
//user_pref("network.trr.uri", "https://dns.nextdns.io/******/Firefox"); // TRR/DoH
/** FASTFOX ***/
user_pref("browser.sessionstore.restore_pinned_tabs_on_demand", true);
// SPECULATIVE LOADING WITHOUT PREDICTOR
user_pref("network.http.speculative-parallel-limit", 20);
//user_pref("network.dns.disablePrefetch", false);
//user_pref("network.dns.disablePrefetchFromHTTPS", false);
//user_pref("dom.prefetch_dns_for_anchor_https_document", true);
user_pref("browser.urlbar.speculativeConnect.enabled", true);
user_pref("browser.places.speculativeConnect.enabled", true);
user_pref("network.prefetch-next", true);
user_pref("network.http.max-persistent-connections-per-server", 20); // increase download connections
/** SECUREFOX ***/
user_pref("privacy.trackingprotection.allow_list.convenience.enabled", false); // disable Strict allowlist of convenience features
user_pref("signon.rememberSignons", false); // disable password manager
user_pref("extensions.formautofill.addresses.enabled", false); // disable address manager
user_pref("extensions.formautofill.creditCards.enabled", false); // disable credit card manager
user_pref("browser.urlbar.suggest.recentsearches", false); // unselect "Show recent searches" for clean UI
user_pref("browser.urlbar.showSearchSuggestionsFirst", false); // unselect "Show search suggestions ahead of browsing history in address bar results" for clean UI
//user_pref("browser.urlbar.groupLabels.enabled", false); // hide Firefox Suggest label in URL dropdown box
user_pref("signon.management.page.breach-alerts.enabled", false); // extra hardening
user_pref("signon.autofillForms", false); // unselect "Autofill logins and passwords" for clean UI
user_pref("signon.generation.enabled", false); // unselect "Suggest and generate strong passwords" for clean UI
user_pref("signon.firefoxRelay.feature", ""); // unselect suggestions from Firefox Relay for clean UI
user_pref("browser.safebrowsing.downloads.enabled", false); // deny SB to scan downloads to identify suspicious files; local checks only
user_pref("browser.safebrowsing.downloads.remote.url", ""); // enforce no remote checks for downloads by SB
user_pref("browser.safebrowsing.downloads.remote.block_potentially_unwanted", false); // clean up UI; not needed in user.js if remote downloads are disabled
user_pref("browser.safebrowsing.downloads.remote.block_uncommon", false); // clean up UI; not needed in user.js if remote downloads are disabled
user_pref("browser.safebrowsing.allowOverride", false); // do not allow user to override SB
user_pref("browser.search.update", false); // do not update opensearch engines
user_pref("network.trr.confirmationNS", "skip"); // skip TRR confirmation request
user_pref("extensions.webextensions.restrictedDomains", ""); // remove Mozilla domains so adblocker works on pages
user_pref("identity.fxaccounts.enabled", false); // disable Firefox Sync
user_pref("browser.firefox-view.feature-tour", "{\"screen\":\"\",\"complete\":true}"); // disable the Firefox View tour from popping up for new profiles
user_pref("accessibility.force_disabled", 1); // disable Accessibility features
user_pref("security.cert_pinning.enforcement_level", 2); // strict public key pinning
user_pref("captivedetect.canonicalURL", ""); // disable captive portal detection
user_pref("network.captive-portal-service.enabled", false); // disable captive portal detection
user_pref("network.connectivity-service.enabled", false); // disable captive portal detection
user_pref("browser.download.enableDeletePrivate", true); // Delete files downloaded in private browsing when all private windows are closed
user_pref("browser.download.deletePrivateChosen", true); // Delete files downloaded in private browsing when all private windows are closed
user_pref("browser.download.deletePrivate", true); // Delete files downloaded in private browsing when all private windows are closed
/** PESKYFOX ***/
user_pref("devtools.accessibility.enabled", false); // removes un-needed "Inspect Accessibility Properties" on right-click
user_pref("browser.newtabpage.activity-stream.showSponsoredTopSites", false); // Settings>Home>Firefox Home Content>Recent Activity>Shortcuts>Sponsored shortcuts
user_pref("browser.newtabpage.activity-stream.showSponsored", false); // Settings>Home>Firefox Home Content>Recent Activity>Recommended by Pocket>Sponsored Stories
user_pref("browser.newtabpage.activity-stream.section.highlights.includeBookmarks", false); // Settings>Home>Firefox Home Content>Recent Activity>Bookmarks
user_pref("browser.newtabpage.activity-stream.section.highlights.includeDownloads", false); // Settings>Home>Firefox Home Content>Recent Activity>Most Recent Download
user_pref("browser.newtabpage.activity-stream.section.highlights.includeVisited", false); // Settings>Home>Firefox Home Content>Recent Activity>Visited Pages
user_pref("browser.newtabpage.activity-stream.section.highlights.includePocket", false); // Settings>Home>Firefox Home Content>Recent Activity>Pages Saved to Pocket
//user_pref("browser.download.useDownloadDir", true); // use direct downloads
//user_pref("browser.download.folderList", 0); // 0=desktop, 1=downloads, 2=last used
user_pref("browser.toolbars.bookmarks.visibility", "never"); // always hide bookmark bar
user_pref("browser.startup.homepage_override.mstone", "ignore"); // What's New page after updates; master switch
user_pref("browser.urlbar.suggest.history", false); // Browsing history; hide URL bar dropdown suggestions
user_pref("browser.urlbar.suggest.bookmark", false); // Bookmarks; hide URL bar dropdown suggestions
user_pref("browser.urlbar.suggest.openpage", false); // Open tabs; hide URL bar dropdown suggestions
user_pref("browser.urlbar.suggest.topsites", false); // Shortcuts; disable dropdown suggestions with empty query
user_pref("browser.urlbar.suggest.engines", false); // Search engines; tab-to-search
user_pref("browser.urlbar.quicksuggest.enabled", false); // hide Firefox Suggest UI in the settings
//user_pref("browser.urlbar.maxRichResults", 1); // minimum suggestion needed for URL bar autofill
user_pref("browser.bookmarks.max_backups", 0); // minimize disk use; manually back-up
user_pref("view_source.wrap_long_lines", true); // wrap source lines
user_pref("devtools.debugger.ui.editor-wrapping", true); // wrap lines in devtools
user_pref("browser.zoom.full", false); // text-only zoom, not all elements on page
//user_pref("pdfjs.sidebarViewOnLoad", 2); // force showing of Table of Contents in sidebar for PDFs (if available)
user_pref("layout.word_select.eat_space_to_next_word", false); // do not select the space next to a word when selecting a word
//user_pref("browser.tabs.loadInBackground", false); // CTRL+SHIFT+CLICK for background tabs; Settings>General>Tabs>When you open a link, image or media in a new tab, switch to it immediately
user_pref("browser.tabs.loadBookmarksInTabs", true); // force bookmarks to open in a new tab, not the current tab
user_pref("ui.key.menuAccessKey", 0); // remove underlined characters from various settings
user_pref("general.autoScroll", false); // disable unintentional behavior for middle click
user_pref("ui.SpellCheckerUnderlineStyle", 1); // [HIDDEN] dots for spell check errors
user_pref("media.videocontrols.picture-in-picture.display-text-tracks.size", "small"); // PiP
user_pref("media.videocontrols.picture-in-picture.urlbar-button.enabled", false); // PiP in address bar
user_pref("reader.parse-on-load.enabled", false); // disable reader mode
//user_pref("reader.color_scheme", "auto"); // match system theme for when reader is enabled
//user_pref("browser.urlbar.openintab", true); // stay on current site and open new tab when typing in URL bar
/** DELETE IF NOT NIGHTLY ***/
user_pref("privacy.userContext.enabled", false); // disable Containers functionality
user_pref("browser.crashReports.unsubmittedCheck.enabled", false); // true by default on NIGHTLY
//user_pref("xpinstall.signatures.required", false); // [ESR/DEV/NIGHTLY]
//user_pref("browser.urlbar.suggest.trending", false); // FF119+ disable showing trending searches; unselect for clean UI
//user_pref("browser.urlbar.suggest.quickactions", false); // Quick actions; hide URL bar dropdown suggestions
//user_pref("browser.urlbar.suggest.clipboard", false); // Clipboard; hide URL bar dropdown suggestions
/** DELETE IF NOT WINDOWS DESKTOP ***/
user_pref("network.trr.mode", 3); // enable TRR (without System fallback)
//user_pref("browser.startup.preXulSkeletonUI", false); // WINDOWS
user_pref("default-browser-agent.enabled", false); // deny Mozilla monitoring default browser (breaks "Make Default" button)
user_pref("geo.provider.ms-windows-location", false); // [WINDOWS]
user_pref("pdfjs.defaultZoomValue", "125"); // alt=page-width; PDF zoom level
user_pref("gfx.font_rendering.cleartype_params.rendering_mode", 5);
user_pref("gfx.font_rendering.cleartype_params.cleartype_level", 100);
user_pref("gfx.font_rendering.cleartype_params.force_gdi_classic_for_families", "");
user_pref("gfx.font_rendering.directwrite.use_gdi_table_loading", false);
//user_pref("gfx.font_rendering.cleartype_params.enhanced_contrast", 100);
//user_pref("font.name.serif.x-western", "Roboto Slab"); // serif font
//user_pref("font.name.sans-serif.x-western", "Roboto"); // sans-serif font
//user_pref("font.name.monospace.x-western", "Fira Code"); // monospace font
/** DELETE IF NOT ENTERPRISE WINDOWS LAPTOP ***/
user_pref("urlclassifier.trackingSkipURLs", ""); // do not allow embedded tweets, Instagram, Reddit, and Tiktok posts
user_pref("urlclassifier.features.socialtracking.skipURLs", ""); // do not allow embedded tweets, Instagram, Reddit, and Tiktok posts
user_pref("browser.search.suggest.enabled", true); // search suggestions
user_pref("browser.urlbar.showSearchSuggestionsFirst", true); // Show search suggestions ahead of browsing history in address bar results
//user_pref("network.connectivity-service.enabled", true); // public wifi
//user_pref("network.trr.confirmationNS", "example.com"); // TRR confirmation request
//user_pref("network.trr.mode", 2); // enable TRR (without System fallback)
//user_pref("browser.startup.preXulSkeletonUI", false); // WINDOWS
user_pref("gfx.font_rendering.cleartype_params.rendering_mode", 5);
user_pref("gfx.font_rendering.cleartype_params.cleartype_level", 100);
user_pref("gfx.font_rendering.cleartype_params.force_gdi_classic_for_families", "");
user_pref("gfx.font_rendering.directwrite.use_gdi_table_loading", false);
user_pref("gfx.font_rendering.cleartype_params.enhanced_contrast", 100);
user_pref("toolkit.legacyUserProfileCustomizations.stylesheets", false); // no need for userChrome
//user_pref("browser.urlbar.suggest.history", true); // Browsing history
//user_pref("browser.urlbar.suggest.bookmark", true); // Bookmarks
//user_pref("browser.urlbar.suggest.openpage", true); // Open tabs
//user_pref("browser.urlbar.suggest.topsites", true); // Shortcuts
/** DELETE IF NOT macOS LAPTOP ***/
user_pref("network.trr.mode", 2); // enable TRR (with System fallback)
user_pref("network.trr.max-fails", 5); // lower max attempts to use DoH
user_pref("geo.provider.use_corelocation", false); // geolocation [MAC]
user_pref("pdfjs.defaultZoomValue", "page-width"); // PDF zoom level
user_pref("app.update.auto", false); // disable auto-installing Firefox updates [NON-WINDOWS]
//user_pref("font.name.monospace.x-western", "SF Mono"); // monospace font
/** DELETE IF NOT LINUX LAPTOP ***/
user_pref("network.trr.mode", 2); // enable TRR (with System fallback)
user_pref("network.trr.max-fails", 5); // lower max attempts to use DoH
user_pref("geo.provider.use_geoclue", false); // [LINUX]
user_pref("pdfjs.defaultZoomValue", "page-width"); // PDF zoom level
| yokoffing/Betterfox | 10,046 | Firefox user.js for optimal privacy and security. Your favorite browser, but better. | JavaScript | yokoffing | ||
user.js | JavaScript | //
/* You may copy+paste this file and use it as it is.
*
* If you make changes to your about:config while the program is running, the
* changes will be overwritten by the user.js when the application restarts.
*
* To make lasting changes to preferences, you will have to edit the user.js.
*/
/****************************************************************************
* Betterfox *
* "Ad meliora" *
* version: 146 *
* url: https://github.com/yokoffing/Betterfox *
****************************************************************************/
/****************************************************************************
* SECTION: FASTFOX *
****************************************************************************/
/** GENERAL ***/
user_pref("gfx.content.skia-font-cache-size", 32);
/** GFX ***/
user_pref("gfx.webrender.layer-compositor", true);
user_pref("gfx.canvas.accelerated.cache-items", 32768);
user_pref("gfx.canvas.accelerated.cache-size", 4096);
user_pref("webgl.max-size", 16384);
/** DISK CACHE ***/
user_pref("browser.cache.disk.enable", false);
/** MEMORY CACHE ***/
user_pref("browser.cache.memory.capacity", 131072);
user_pref("browser.cache.memory.max_entry_size", 20480);
user_pref("browser.sessionhistory.max_total_viewers", 4);
user_pref("browser.sessionstore.max_tabs_undo", 10);
/** MEDIA CACHE ***/
user_pref("media.memory_cache_max_size", 262144);
user_pref("media.memory_caches_combined_limit_kb", 1048576);
user_pref("media.cache_readahead_limit", 600);
user_pref("media.cache_resume_threshold", 300);
/** IMAGE CACHE ***/
user_pref("image.cache.size", 10485760);
user_pref("image.mem.decode_bytes_at_a_time", 65536);
/** NETWORK ***/
user_pref("network.http.max-connections", 1800);
user_pref("network.http.max-persistent-connections-per-server", 10);
user_pref("network.http.max-urgent-start-excessive-connections-per-host", 5);
user_pref("network.http.request.max-start-delay", 5);
user_pref("network.http.pacing.requests.enabled", false);
user_pref("network.dnsCacheEntries", 10000);
user_pref("network.dnsCacheExpiration", 3600);
user_pref("network.ssl_tokens_cache_capacity", 10240);
/** SPECULATIVE LOADING ***/
user_pref("network.http.speculative-parallel-limit", 0);
user_pref("network.dns.disablePrefetch", true);
user_pref("network.dns.disablePrefetchFromHTTPS", true);
user_pref("browser.urlbar.speculativeConnect.enabled", false);
user_pref("browser.places.speculativeConnect.enabled", false);
user_pref("network.prefetch-next", false);
/****************************************************************************
* SECTION: SECUREFOX *
****************************************************************************/
/** TRACKING PROTECTION ***/
user_pref("browser.contentblocking.category", "strict");
user_pref("browser.download.start_downloads_in_tmp_dir", true);
user_pref("browser.uitour.enabled", false);
user_pref("privacy.globalprivacycontrol.enabled", true);
/** OCSP & CERTS / HPKP ***/
user_pref("security.OCSP.enabled", 0);
user_pref("privacy.antitracking.isolateContentScriptResources", true);
user_pref("security.csp.reporting.enabled", false);
/** SSL / TLS ***/
user_pref("security.ssl.treat_unsafe_negotiation_as_broken", true);
user_pref("browser.xul.error_pages.expert_bad_cert", true);
user_pref("security.tls.enable_0rtt_data", false);
/** DISK AVOIDANCE ***/
user_pref("browser.privatebrowsing.forceMediaMemoryCache", true);
user_pref("browser.sessionstore.interval", 60000);
/** SHUTDOWN & SANITIZING ***/
user_pref("privacy.history.custom", true);
user_pref("browser.privatebrowsing.resetPBM.enabled", true);
/** SEARCH / URL BAR ***/
user_pref("browser.urlbar.trimHttps", true);
user_pref("browser.urlbar.untrimOnUserInteraction.featureGate", true);
user_pref("browser.search.separatePrivateDefault.ui.enabled", true);
user_pref("browser.search.suggest.enabled", false);
user_pref("browser.urlbar.quicksuggest.enabled", false);
user_pref("browser.urlbar.groupLabels.enabled", false);
user_pref("browser.formfill.enable", false);
user_pref("network.IDN_show_punycode", true);
/** HTTPS-ONLY MODE ***/
user_pref("dom.security.https_only_mode", true);
user_pref("dom.security.https_only_mode_error_page_user_suggestions", true);
/** PASSWORDS ***/
user_pref("signon.formlessCapture.enabled", false);
user_pref("signon.privateBrowsingCapture.enabled", false);
user_pref("network.auth.subresource-http-auth-allow", 1);
user_pref("editor.truncate_user_pastes", false);
/** EXTENSIONS ***/
user_pref("extensions.enabledScopes", 5);
/** HEADERS / REFERERS ***/
user_pref("network.http.referer.XOriginTrimmingPolicy", 2);
/** CONTAINERS ***/
user_pref("privacy.userContext.ui.enabled", true);
/** VARIOUS ***/
user_pref("pdfjs.enableScripting", false);
/** SAFE BROWSING ***/
user_pref("browser.safebrowsing.downloads.remote.enabled", false);
/** MOZILLA ***/
user_pref("permissions.default.desktop-notification", 2);
user_pref("permissions.default.geo", 2);
user_pref("geo.provider.network.url", "https://beacondb.net/v1/geolocate");
user_pref("browser.search.update", false);
user_pref("permissions.manager.defaultsUrl", "");
user_pref("extensions.getAddons.cache.enabled", false);
/** TELEMETRY ***/
user_pref("datareporting.policy.dataSubmissionEnabled", false);
user_pref("datareporting.healthreport.uploadEnabled", false);
user_pref("toolkit.telemetry.unified", false);
user_pref("toolkit.telemetry.enabled", false);
user_pref("toolkit.telemetry.server", "data:,");
user_pref("toolkit.telemetry.archive.enabled", false);
user_pref("toolkit.telemetry.newProfilePing.enabled", false);
user_pref("toolkit.telemetry.shutdownPingSender.enabled", false);
user_pref("toolkit.telemetry.updatePing.enabled", false);
user_pref("toolkit.telemetry.bhrPing.enabled", false);
user_pref("toolkit.telemetry.firstShutdownPing.enabled", false);
user_pref("toolkit.telemetry.coverage.opt-out", true);
user_pref("toolkit.coverage.opt-out", true);
user_pref("toolkit.coverage.endpoint.base", "");
user_pref("browser.newtabpage.activity-stream.feeds.telemetry", false);
user_pref("browser.newtabpage.activity-stream.telemetry", false);
user_pref("datareporting.usage.uploadEnabled", false);
/** EXPERIMENTS ***/
user_pref("app.shield.optoutstudies.enabled", false);
user_pref("app.normandy.enabled", false);
user_pref("app.normandy.api_url", "");
/** CRASH REPORTS ***/
user_pref("breakpad.reportURL", "");
user_pref("browser.tabs.crashReporting.sendReport", false);
/****************************************************************************
* SECTION: PESKYFOX *
****************************************************************************/
/** MOZILLA UI ***/
user_pref("extensions.getAddons.showPane", false);
user_pref("extensions.htmlaboutaddons.recommendations.enabled", false);
user_pref("browser.discovery.enabled", false);
user_pref("browser.shell.checkDefaultBrowser", false);
user_pref("browser.newtabpage.activity-stream.asrouter.userprefs.cfr.addons", false);
user_pref("browser.newtabpage.activity-stream.asrouter.userprefs.cfr.features", false);
user_pref("browser.preferences.moreFromMozilla", false);
user_pref("browser.aboutConfig.showWarning", false);
user_pref("browser.startup.homepage_override.mstone", "ignore");
user_pref("browser.aboutwelcome.enabled", false);
user_pref("browser.profiles.enabled", true);
/** THEME ADJUSTMENTS ***/
user_pref("toolkit.legacyUserProfileCustomizations.stylesheets", true);
user_pref("browser.compactmode.show", true);
user_pref("browser.privateWindowSeparation.enabled", false); // WINDOWS
/** AI ***/
user_pref("browser.ml.enable", false);
user_pref("browser.ml.chat.enabled", false);
user_pref("browser.ml.chat.menu", false);
user_pref("browser.tabs.groups.smart.enabled", false);
user_pref("browser.ml.linkPreview.enabled", false);
/** FULLSCREEN NOTICE ***/
user_pref("full-screen-api.transition-duration.enter", "0 0");
user_pref("full-screen-api.transition-duration.leave", "0 0");
user_pref("full-screen-api.warning.timeout", 0);
/** URL BAR ***/
user_pref("browser.urlbar.trending.featureGate", false);
/** NEW TAB PAGE ***/
user_pref("browser.newtabpage.activity-stream.default.sites", "");
user_pref("browser.newtabpage.activity-stream.showSponsoredTopSites", false);
user_pref("browser.newtabpage.activity-stream.feeds.section.topstories", false);
user_pref("browser.newtabpage.activity-stream.showSponsored", false);
user_pref("browser.newtabpage.activity-stream.showSponsoredCheckboxes", false);
/** DOWNLOADS ***/
user_pref("browser.download.manager.addToRecentDocs", false);
/** PDF ***/
user_pref("browser.download.open_pdf_attachments_inline", true);
/** TAB BEHAVIOR ***/
user_pref("browser.bookmarks.openInTabClosesMenu", false);
user_pref("browser.menu.showViewImageInfo", true);
user_pref("findbar.highlightAll", true);
user_pref("layout.word_select.eat_space_to_next_word", false);
/****************************************************************************
* START: MY OVERRIDES *
****************************************************************************/
// visit https://github.com/yokoffing/Betterfox/wiki/Common-Overrides
// visit https://github.com/yokoffing/Betterfox/wiki/Optional-Hardening
// Enter your personal overrides below this line:
/****************************************************************************
* SECTION: SMOOTHFOX *
****************************************************************************/
// visit https://github.com/yokoffing/Betterfox/blob/main/Smoothfox.js
// Enter your scrolling overrides below this line:
/****************************************************************************
* END: BETTERFOX *
****************************************************************************/
| yokoffing/Betterfox | 10,046 | Firefox user.js for optimal privacy and security. Your favorite browser, but better. | JavaScript | yokoffing | ||
zen/user.js | JavaScript | //
/* You may copy+paste this file and use it as it is.
*
* If you make changes to your about:config while the program is running, the
* changes will be overwritten by the user.js when the application restarts.
*
* To make lasting changes to preferences, you will have to edit the user.js.
*/
/****************************************************************************
* BetterZen *
* "Ex nihilo nihil fit" *
* version: 142 *
* url: https://github.com/yokoffing/Betterfox *
****************************************************************************/
/****************************************************************************
* SECTION: FASTFOX *
****************************************************************************/
/** GFX ***/
user_pref("gfx.canvas.accelerated.cache-size", 512);
/** DISK CACHE ***/
user_pref("browser.cache.disk.enable", false);
/** NETWORK ***/
user_pref("network.http.pacing.requests.enabled", false);
/** SPECULATIVE LOADING ***/
user_pref("network.dns.disablePrefetch", true);
user_pref("network.dns.disablePrefetchFromHTTPS", true);
user_pref("network.prefetch-next", false);
user_pref("network.predictor.enabled", false);
user_pref("network.predictor.enable-prefetch", false);
/****************************************************************************
* SECTION: SECUREFOX *
****************************************************************************/
/** TRACKING PROTECTION ***/
user_pref("browser.contentblocking.category", "strict");
user_pref("privacy.trackingprotection.allow_list.baseline.enabled", true);
user_pref("privacy.trackingprotection.allow_list.convenience.enabled", true);
user_pref("browser.download.start_downloads_in_tmp_dir", true);
/** OCSP & CERTS / HPKP ***/
user_pref("security.OCSP.enabled", 0);
user_pref("security.pki.crlite_mode", 2);
/** DISK AVOIDANCE ***/
user_pref("browser.sessionstore.interval", 60000);
/** SHUTDOWN & SANITIZING ***/
user_pref("browser.privatebrowsing.resetPBM.enabled", true);
user_pref("privacy.history.custom", true);
/** SEARCH / URL BAR ***/
user_pref("browser.urlbar.quicksuggest.enabled", false);
/** PASSWORDS ***/
user_pref("signon.formlessCapture.enabled", false);
user_pref("signon.privateBrowsingCapture.enabled", false);
user_pref("network.auth.subresource-http-auth-allow", 1);
user_pref("editor.truncate_user_pastes", false);
/** HEADERS / REFERERS ***/
user_pref("network.http.referer.XOriginTrimmingPolicy", 2);
/** SAFE BROWSING ***/
user_pref("browser.safebrowsing.downloads.remote.enabled", false);
/** MOZILLA ***/
user_pref("permissions.default.desktop-notification", 2);
user_pref("permissions.default.geo", 2);
user_pref("geo.provider.network.url", "https://beacondb.net/v1/geolocate");
user_pref("browser.search.update", false);
user_pref("permissions.manager.defaultsUrl", "");
/****************************************************************************
* SECTION: PESKYFOX *
****************************************************************************/
/** MOZILLA UI ***/
user_pref("browser.shell.checkDefaultBrowser", false);
/** NEW TAB PAGE ***/
user_pref("browser.newtabpage.activity-stream.default.sites", "");
/** URL BAR ***/
user_pref("dom.text_fragments.create_text_fragment.enabled", true);
/****************************************************************************
* START: ZEN-SPECIFIC OVERRIDES *
****************************************************************************/
// Remove the slashes to enable the prefs
// PREF: re-enable Windows efficiency mode
//user_pref("dom.ipc.processPriorityManager.backgroundUsesEcoQoS", true);
// PREF: disable new tab preload since they are off by default
//user_pref("browser.newtab.preload", false);
// PREF: show Enhance Tracking Protection shield in URL bar
// Currently bugged if you click to view what's blocked
//user_pref("zen.urlbar.show-protections-icon", true);
// PREF: Disable the Picture in picture pop-out when changing tabs
//user_pref("media.videocontrols.picture-in-picture.enable-when-switching-tabs.enabled", false);
/****************************************************************************
* START: MY OVERRIDES *
****************************************************************************/
// visit https://github.com/yokoffing/Betterfox/wiki/Common-Overrides
// visit https://github.com/yokoffing/Betterfox/wiki/Optional-Hardening
// Enter your personal overrides below this line:
/****************************************************************************
* SECTION: SMOOTHFOX *
****************************************************************************/
// Reset Zen's custom scrolling prefs to their Firefox defaults before making changes!
// [1] Zen changes: https://github.com/zen-browser/desktop/blob/3932ec21f5661440c4b20796f90341a6ac725818/src/browser/app/profile/zen-browser.js#L297-L312
// [2] Firefox defaults: https://searchfox.org/mozilla-release/source/modules/libpref/init/StaticPrefList.yaml
// Then apply an example from Smoothfox
// [3] https://github.com/yokoffing/Betterfox/blob/main/Smoothfox.js
// Enter your scrolling overrides below this line:
/****************************************************************************
* END: BETTERFOX *
****************************************************************************/
| yokoffing/Betterfox | 10,046 | Firefox user.js for optimal privacy and security. Your favorite browser, but better. | JavaScript | yokoffing | ||
Package.swift | Swift | // swift-tools-version:5.1
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "Stringly",
products: [
.executable(name: "stringly", targets: ["Stringly"]),
.library(name: "StringlyKit", targets: ["StringlyKit"])
],
dependencies: [
.package(url: "https://github.com/jpsim/Yams", from: "1.0.0"),
.package(url: "https://github.com/kylef/PathKit", from: "1.0.1"),
.package(url: "https://github.com/onevcat/Rainbow", from: "3.1.0"),
.package(url: "https://github.com/jakeheis/SwiftCLI", from: "6.0.3"),
.package(url: "https://github.com/dduan/TOMLDeserializer", from: "0.2.4"),
.package(url: "https://github.com/yonaskolb/Codability", from: "0.2.1"),
],
targets: [
.target(
name: "Stringly",
dependencies: ["StringlyCLI"]),
.target(
name: "StringlyCLI",
dependencies: [
"Yams",
"Rainbow",
"SwiftCLI",
"PathKit",
"TOMLDeserializer",
"StringlyKit",
]),
.target(
name: "StringlyKit",
dependencies: ["Codability"]),
.testTarget(
name: "StringlyCLITests",
dependencies: ["StringlyCLI", "PathKit"]),
.testTarget(
name: "StringlyKitTests",
dependencies: ["StringlyKit", "PathKit"]),
]
)
| yonaskolb/Stringly | 18 | Manage and generate localization files | Swift | yonaskolb | Yonas Kolb | |
Sources/Stringly/main.swift | Swift |
import Foundation
import SwiftCLI
import StringlyCLI
let cli = StringlyCLI()
let status = cli.run()
exit(status)
| yonaskolb/Stringly | 18 | Manage and generate localization files | Swift | yonaskolb | Yonas Kolb | |
Sources/StringlyCLI/CLI.swift | Swift | //
// File.swift
//
//
// Created by Yonas Kolb on 17/10/19.
//
import Foundation
import SwiftCLI
import PathKit
public class StringlyCLI {
let version = "0.9.0"
let cli: CLI
public init() {
cli = CLI(name: "stringly", version: version, description: "Generates localization files from a spec", commands: [
GenerateCommand(),
GenerateFileCommand(),
])
}
public func run(arguments: [String] = []) -> Int32 {
if arguments.isEmpty {
return cli.go()
} else {
return cli.go(with: arguments)
}
}
}
extension Path: ConvertibleFromString {
public init?(input: String) {
self.init(input)
}
}
| yonaskolb/Stringly | 18 | Manage and generate localization files | Swift | yonaskolb | Yonas Kolb | |
Sources/StringlyCLI/Commands/GenerateCommand.swift | Swift | //
// File.swift
//
//
// Created by Yonas Kolb on 17/10/19.
//
import Foundation
import SwiftCLI
import StringlyKit
import PathKit
import Rainbow
class GenerateCommand: Command {
let name: String = "generate"
let shortDescription: String = "Generates all required localization files for a given platform"
let platform = Key<PlatformType>("--platform", "-p", description: "The platform to generate files for. Defaults to apple")
@Param
var sourcePath: Path
let directoryPath = Key<Path>("--directory", "-d", description: "The directory to generate the files in. Defaults to the directory the source path is in")
let baseLanguage = Key<String>("--base", "-b", description: "The base language to use. Defaults to en")
func execute() throws {
let sourcePath = self.sourcePath.normalize()
let directoryPath = self.directoryPath.value ?? sourcePath.parent()
let baseLanguage = self.baseLanguage.value ?? "en"
let platform = self.platform.value ?? .apple
let strings = try Loader.loadStrings(from: sourcePath, baseLanguage: baseLanguage)
let languages = strings.getLanguages()
switch platform {
case .apple:
for language in languages {
try FileWriter.write(fileType: .strings, strings: strings, language: language, destinationPath: directoryPath + "\(language).lproj/Strings.strings")
if strings.languageHasPlurals(language) {
try FileWriter.write(fileType: .stringsDict, strings: strings, language: language, destinationPath: directoryPath + "\(language).lproj/Strings.stringsdict")
}
}
try FileWriter.write(fileType: .swift, strings: strings, language: baseLanguage, destinationPath: directoryPath + "Strings.swift")
case .android:
fatalError("Android not yet supported".red)
}
}
}
| yonaskolb/Stringly | 18 | Manage and generate localization files | Swift | yonaskolb | Yonas Kolb | |
Sources/StringlyCLI/Commands/GenerateFileCommand.swift | Swift | //
// File.swift
//
//
// Created by Yonas Kolb on 17/10/19.
//
import Foundation
import SwiftCLI
import StringlyKit
import PathKit
import Yams
import TOMLDeserializer
import Rainbow
class GenerateFileCommand: Command {
let name: String = "generate-file"
let shortDescription: String = "Generates a specific file for a language"
let longDescription: String = """
Generates a single localization file in a single language from a source file. If no destination path is passed the file content will be written to stdout
"""
let language = Key<String>("--language", "-l", description: "The language to generate. Defaults to en")
let baseLanguage = Key<String>("--base", "-b", description: "The base language to use. Defaults to en")
let type = Key<FileType>("--type", "-t", description: "The file type to generate. Defaults to inferring from the destination file extension")
@Param
var sourcePath: Path
@Param
var destinationPath: Path?
func execute() throws {
let sourcePath = self.sourcePath.normalize()
let destinationPath = self.destinationPath?.normalize()
let language = self.language.value ?? "en"
let baseLanguage = self.baseLanguage.value ?? "en"
let strings = try Loader.loadStrings(from: sourcePath, baseLanguage: baseLanguage)
let fileType: FileType
if let type = self.type.value {
fileType = type
} else {
if let destinationPath = destinationPath, let type = FileType(path: destinationPath) {
fileType = type
} else {
throw GenerateError.unknownFileType(destinationPath?.extension ?? "")
}
}
try FileWriter.write(fileType: fileType, strings: strings, language: language, destinationPath: destinationPath)
}
}
| yonaskolb/Stringly | 18 | Manage and generate localization files | Swift | yonaskolb | Yonas Kolb | |
Sources/StringlyCLI/FileType.swift | Swift | //
// File.swift
//
//
// Created by Yonas Kolb on 27/10/19.
//
import Foundation
import SwiftCLI
import PathKit
import StringlyKit
public enum FileType: String, ConvertibleFromString {
case strings
case stringsDict
case swift
init?(path: Path) {
switch path.extension?.lowercased() {
case "strings": self = .strings
case "stringsdict": self = .stringsDict
case "swift": self = .swift
default: return nil
}
}
var generator: Generator {
switch self {
case .strings: return StringsGenerator()
case .stringsDict: return StringsDictGenerator()
case .swift: return SwiftGenerator()
}
}
}
| yonaskolb/Stringly | 18 | Manage and generate localization files | Swift | yonaskolb | Yonas Kolb | |
Sources/StringlyCLI/FileWriter.swift | Swift | //
// File.swift
//
//
// Created by Yonas Kolb on 27/10/19.
//
import Foundation
import PathKit
import SwiftCLI
import StringlyKit
public struct FileWriter {
public static func write(fileType: FileType, strings: StringGroup, language: String, destinationPath: Path?) throws {
do {
let generator = fileType.generator
let content = try generator.generate(stringGroup: strings, language: language)
try write(content: content, to: destinationPath)
} catch {
throw GenerateError.encodingError(error)
}
}
static func write(content: String, to destinationPath: Path?) throws {
if let destinationPath = destinationPath {
do {
try destinationPath.parent().mkpath()
if destinationPath.exists, try destinationPath.read() == content {
// same content, don't write
} else {
try destinationPath.write(content)
}
} catch {
throw GenerateError.writingError(error)
}
} else {
Term.stdout.print(content)
}
}
}
| yonaskolb/Stringly | 18 | Manage and generate localization files | Swift | yonaskolb | Yonas Kolb | |
Sources/StringlyCLI/GenerateError.swift | Swift | //
// File.swift
//
//
// Created by Yonas Kolb on 27/10/19.
//
import Foundation
import SwiftCLI
enum GenerateError: ProcessError {
case sourceParseError(Error)
case unstructuredContent
case missingSource
case encodingError(Error)
case writingError(Error)
case unknownFileType(String)
var exitStatus: Int32 { 1 }
var message: String? {
return description.red
}
var description: String {
switch self {
case .sourceParseError: return "Failed to parse source file"
case .unstructuredContent: return "Source file has unstructured content"
case .missingSource: return "Source file does not exist"
case .encodingError: return "Failed to encode file"
case .writingError: return "Failed to write file"
case .unknownFileType(let type): return "Unknown file type \"\(type)\""
}
}
}
| yonaskolb/Stringly | 18 | Manage and generate localization files | Swift | yonaskolb | Yonas Kolb | |
Sources/StringlyCLI/Loader.swift | Swift | //
// File.swift
//
//
// Created by Yonas Kolb on 27/10/19.
//
import Foundation
import StringlyKit
import TOMLDeserializer
import PathKit
import Yams
public struct Loader {
public static func loadStrings(from sourcePath: Path, baseLanguage: String) throws -> StringGroup {
if !sourcePath.exists {
throw GenerateError.missingSource
}
let sourceString: String = try sourcePath.read()
let dictionary: [String: Any]
do {
switch sourcePath.extension {
case "toml", "tml":
dictionary = try TOMLDeserializer.tomlTable(with: sourceString)
default:
let yaml = try Yams.load(yaml: sourceString)
guard let dict = yaml as? [String: Any] else {
throw GenerateError.unstructuredContent
}
dictionary = dict
}
} catch {
throw GenerateError.sourceParseError(error)
}
let strings = StringGroup(dictionary, baseLanguage: baseLanguage)
return strings
}
}
| yonaskolb/Stringly | 18 | Manage and generate localization files | Swift | yonaskolb | Yonas Kolb | |
Sources/StringlyCLI/PlatformType.swift | Swift | //
// File.swift
//
//
// Created by Yonas Kolb on 27/10/19.
//
import Foundation
import SwiftCLI
public enum PlatformType: String, ConvertibleFromString {
case apple
case android
}
| yonaskolb/Stringly | 18 | Manage and generate localization files | Swift | yonaskolb | Yonas Kolb | |
Sources/StringlyKit/Generator.swift | Swift | //
// File.swift
//
//
// Created by Yonas Kolb on 2/1/20.
//
import Foundation
public protocol Generator {
func generate(stringGroup: StringGroup, language: String) throws -> String
}
| yonaskolb/Stringly | 18 | Manage and generate localization files | Swift | yonaskolb | Yonas Kolb | |
Sources/StringlyKit/Generators/StringsDictGenerator.swift | Swift | //
// File.swift
//
//
// Created by Yonas Kolb on 22/10/19.
//
import Foundation
import Codability
struct StringsDict: Encodable {
var keys: [String: FormatKey]
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: RawCodingKey.self)
for (key, format) in keys {
try container.encode(format, forKey: .init(string: key))
}
}
struct FormatKey: Encodable {
var format: String
var rules: [String: Rule]
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: RawCodingKey.self)
try container.encode(format, forKey: "NSStringLocalizedFormatKey")
for (name, variable) in rules {
try container.encode(variable, forKey: .init(string: name))
}
}
}
struct Rule: Encodable {
var format: String
var plurals: [StringLocalization.Plural: String]
var ruleType = "NSStringPluralRuleType"
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: RawCodingKey.self)
try container.encode(ruleType, forKey: "NSStringFormatSpecTypeKey")
try container.encode(format, forKey: "NSStringFormatValueTypeKey")
for (plural, value) in plurals {
try container.encode(value, forKey: .init(string: plural.rawValue))
}
}
}
}
public struct StringsDictGenerator: Generator {
public init() {}
public func generate(stringGroup: StringGroup, language: String) throws -> String {
let encoder = PropertyListEncoder()
encoder.outputFormat = .xml
var keys: [String: StringsDict.FormatKey] = [:]
func handleGroup(_ group: StringGroup) {
for (key, string) in group.strings {
guard let language = string.languages[language], !language.plurals.isEmpty else { continue }
var formatString = language.string
for placeholder in string.placeholders {
formatString = formatString.replacingOccurrences(of: placeholder.originalPlaceholder, with: "%#@\(placeholder.name)@")
}
var format = StringsDict.FormatKey(format: formatString, rules: [:])
for (placeholderString, plurals) in language.plurals {
guard let placeholder = string.getPlaceholder(name: placeholderString),
let placeholderType = placeholder.type else { continue }
let plurals = plurals.mapValues {
string.replacePlaceholders($0) { $0.applePattern }
}
let rule = StringsDict.Rule(format: placeholderType, plurals: plurals)
format.rules[placeholderString] = rule
}
let stringKey = "\(group.pathString)\(group.path.isEmpty ? "" : ".")\(key)"
keys[stringKey] = format
}
for group in group.groups {
handleGroup(group)
}
}
handleGroup(stringGroup)
let stringsDict = StringsDict(keys: keys)
let data = try encoder.encode(stringsDict)
return String(data: data, encoding: .utf8) ?? ""
}
}
| yonaskolb/Stringly | 18 | Manage and generate localization files | Swift | yonaskolb | Yonas Kolb | |
Sources/StringlyKit/Generators/StringsGenerator.swift | Swift | //
// File.swift
//
//
// Created by Yonas Kolb on 22/10/19.
//
import Foundation
import Codability
public struct StringsGenerator: Generator {
public init() {}
public func generate(stringGroup: StringGroup, language: String) throws -> String {
let description = "// This file was auto-generated with https://github.com/yonaskolb/Stringly"
return "\(description)\n\(lines(stringGroup, language: language).joined(separator: "\n"))"
}
func lines(_ stringGroup: StringGroup, language: String) -> [String] {
var array: [String] = []
array += stringGroup.strings
.compactMap { (key, localisationString) in
guard let language = localisationString.languages[language] else { return nil }
let key = "\(stringGroup.pathString)\(stringGroup.path.isEmpty ? "" : ".")\(key)"
let string = localisationString.replacePlaceholders(language.string) { $0.applePattern }
return "\"\(key)\" = \"\(string)\";"
}
.sorted()
let sortedGroups = stringGroup.groups
.map { group -> [String] in
// let comment = "\n/*** \(group.pathString.uppercased()) \(String(repeating: "*", count: 50 - group.pathString.count))/"
// let commentChar = "#"
// let lineLength = 50
// let spacing = lineLength - group.pathString.count - 4
// let commentLine = String(repeating: commentChar, count: lineLength)
// let middleLine = "\(String(repeating: " ", count: Int(Double(spacing)/2 + 0.5)))\(group.pathString) \(String(repeating: " ", count: Int(Double(spacing)/2 + 0.5)))"
// let comment = "\n\(commentLine)\n\(commentChar)\(middleLine)\(commentChar)\n\(commentLine)"
if group.strings.values.contains(where: { $0.hasLanguage(language) }) {
let comment = "\n// \(group.pathString.uppercased())"
return [comment] + lines(group, language: language)
} else {
return lines(group, language: language)
}
}
let groupLines = sortedGroups.reduce([]) { $0 + $1 }
array += groupLines
return array
}
}
extension StringLocalization.Placeholder {
var applePattern: String {
return "%" + (type ?? "@")
}
}
| yonaskolb/Stringly | 18 | Manage and generate localization files | Swift | yonaskolb | Yonas Kolb | |
Sources/StringlyKit/Generators/SwiftGenerator.swift | Swift | //
// File.swift
//
//
// Created by Yonas Kolb on 26/10/19.
//
import Foundation
public struct SwiftGenerator: Generator {
let namespace = "Strings"
var tableName: String { namespace }
public init() {}
public func generate(stringGroup: StringGroup, language: String) -> String {
let content = parseGroup(stringGroup, language: language).replacingOccurrences(of: "\n", with: "\n ")
let file = """
// This file was auto-generated with https://github.com/yonaskolb/Stringly
// swiftlint:disable all
import Foundation
public enum \(namespace) {\(content)
}
public protocol StringGroup {
static var localizationKey: String { get }
}
extension StringGroup {
public static func string(for key: String, _ args: CVarArg...) -> String {
return \(namespace).localized(key: "\\(localizationKey).\\(key)", args: args)
}
}
extension \(namespace) {
/// The bundle uses for localization
public static var bundle: Bundle = Bundle(for: BundleToken.self)
/// Allows overriding any particular key, for A/B tests for example. Values need to be correct for the current language
public static var overrides: [String: String] = [:]
fileprivate static func localized(_ key: String, in group: String, _ args: CVarArg...) -> String {
return \(namespace).localized(key: "\\(group).\\(key)", args: args)
}
fileprivate static func localized(_ key: String, _ args: CVarArg...) -> String {
return \(namespace).localized(key: key, args: args)
}
fileprivate static func localized(key: String, args: [CVarArg]) -> String {
let format = overrides[key] ?? NSLocalizedString(key, tableName: "\(tableName)", bundle: bundle, comment: "")
return String(format: format, locale: Locale.current, arguments: args)
}
}
private final class BundleToken {}
"""
return file
}
func parseGroup(_ group: StringGroup, language: String) -> String {
var content = ""
if !group.path.isEmpty {
content += "public static let localizationKey = \"\(group.pathString)\""
}
let strings = group.strings.sorted { $0.key < $1.key }
for (key, localizedString) in strings {
let placeholders: [(name: String, type: String, named: Bool)] = localizedString.placeholders.enumerated().map { index, placeholder in
let name = placeholder.hasName ? placeholder.name : "p\(index)"
let type = PlaceholderType(string: placeholder.type ?? "@")?.rawValue ?? "CVarArg"
return (name, type, placeholder.hasName)
}
let name = key
var key = "\"\(name)\""
if !group.path.isEmpty {
key += ", in: localizationKey"
}
let line: String
if placeholders.isEmpty {
line = "public static let \(name) = \(namespace).localized(\(key))"
} else {
let params = placeholders
.map { "\($0.named ? "" : "_ ")\($0.name): \($0.type)" }
.joined(separator: ", ")
let callingParams = placeholders
.map { $0.name }
.joined(separator: ", ")
line = """
public static func \(name)(\(params)) -> String {
\(namespace).localized(\(key), \(callingParams))
}
"""
}
let languageString = localizedString.languages[language]!
let comment = localizedString.replacePlaceholders(languageString.string) { "**{\(languageString.plurals.isEmpty ? "" : "pluralized ")\($0.name)}**"}
content += "\n/// \(comment)\n\(line)"
}
for group in group.groups {
content += """
public enum \(group.path.last!): StringGroup {
\(parseGroup(group, language: language).replacingOccurrences(of: "\n", with: "\n "))
}
"""
}
return content
}
}
fileprivate enum PlaceholderType: String {
case object = "String"
case float = "Float"
case int = "Int"
case char = "CChar"
case cString = "UnsafePointer<CChar>"
case pointer = "UnsafeRawPointer"
static let unknown = pointer
init?(string: String) {
guard let firstChar = string.lowercased().first else {
return nil
}
switch firstChar {
case "@":
self = .object
case "a", "e", "f", "g":
self = .float
case "d", "i", "o", "u", "x":
self = .int
case "c":
self = .char
case "s":
self = .cString
case "p":
self = .pointer
default:
return nil
}
}
}
| yonaskolb/Stringly | 18 | Manage and generate localization files | Swift | yonaskolb | Yonas Kolb | |
Sources/StringlyKit/StringGroup.swift | Swift | //
// File.swift
//
//
// Created by Yonas Kolb on 17/10/19.
//
import Foundation
public struct StringGroup: Equatable {
public var path: [String] = []
public var groups: [StringGroup] = []
public var strings: [String: StringLocalization] = [:]
public var pathString: String { path.joined(separator: ".") }
public init(_ dictionary: [String: Any], baseLanguage: String) {
self.init(dictionary: dictionary, depth: [], baseLanguage: baseLanguage)
}
init(dictionary: [String: Any], depth: [String], baseLanguage: String) {
path = depth
for (key, value) in dictionary {
if let dictionary = value as? [String: Any] {
if dictionary.keys.contains(baseLanguage) {
let localization = StringLocalization(dictionary)
strings[key] = localization
} else {
let group = StringGroup(dictionary: dictionary, depth: depth + [key], baseLanguage: baseLanguage)
groups.append(group)
}
} else if let string = value as? String {
strings[key] = StringLocalization(language: baseLanguage, string: string)
}
}
self.groups.sort { $0.pathString < $1.pathString }
}
public init(path: [String] = [], groups: [StringGroup] = [], strings: [String: StringLocalization] = [:]) {
self.path = path
self.groups = groups
self.strings = strings
}
public var hasPlurals: Bool {
strings.values.contains { $0.hasPlurals } || groups.contains { $0.hasPlurals }
}
public var hasPlaceholders: Bool {
strings.values.contains { $0.hasPlaceholders } || groups.contains { $0.hasPlaceholders }
}
public func languageHasPlurals(_ language: String) -> Bool {
strings.values.contains { $0.languageHasPlurals(language) } || groups.contains { $0.languageHasPlurals(language) }
}
public func hasLanguage(_ language: String) -> Bool {
strings.values.contains { $0.hasLanguage(language) } || groups.contains { $0.hasLanguage(language) }
}
public func getLanguages() -> Set<String> {
Set(
strings.values.reduce([]) { $0 + $1.languages.keys } +
groups.reduce([]) { $0 + Array($1.getLanguages()) }
)
}
}
| yonaskolb/Stringly | 18 | Manage and generate localization files | Swift | yonaskolb | Yonas Kolb | |
Sources/StringlyKit/StringLocalization.swift | Swift | //
// File.swift
//
//
// Created by Yonas Kolb on 27/10/19.
//
import Foundation
public struct StringLocalization: Equatable {
public let languages: [String: Language]
public let placeholders: [Placeholder]
var defaultLanguage: Language {
languages["base"] ?? languages["en"]!
}
var hasPlurals: Bool {
languages.values.contains { !$0.plurals.isEmpty }
}
var hasPlaceholders: Bool {
!placeholders.isEmpty
}
func hasLanguage(_ language: String) -> Bool {
languages[language] != nil
}
func languageHasPlurals(_ language: String) -> Bool {
if let language = languages[language] {
return !language.plurals.isEmpty
} else {
return false
}
}
func getLanguages() -> Set<String> {
Set(languages.keys)
}
public init(language: String, string: String) {
self.languages = [language: Language(code: language, string: string, plurals: [:])]
self.placeholders = Self.parsePlaceholders(string)
}
public init(languages: [String: Language], placeholders: [Placeholder] = []) {
self.languages = languages
self.placeholders = placeholders
}
public init(language: String, string: String, placeholders: [Placeholder]) {
self.languages = [language: Language(code: language, string: string, plurals: [:])]
self.placeholders = placeholders
}
public struct Language: Equatable {
public let code: String
public var string: String
public var plurals: [String: [Plural: String]]
public init(code: String, string: String, plurals: [String: [Plural: String]] = [:]) {
self.code = code
self.string = string
self.plurals = plurals
}
}
public struct Placeholder: Equatable {
public var name: String
public var type: String?
public var originalPlaceholder: String {
"{\(name)\(type.map { ":\($0)" } ?? "")}"
}
public init(name: String, type: String? = nil) {
self.name = name
self.type = type
}
public var hasName: Bool { !name.isEmpty }
}
public enum Plural: String, CaseIterable {
case zero
case one
case two
case few
case many
case other
}
static let regex = try! NSRegularExpression(pattern: #"\{(\S*)\}"#, options: [])
static func parsePlaceholders(_ string: String) -> [Placeholder] {
guard string.contains("{") else { return [] }
let range = NSRange(string.startIndex..<string.endIndex, in: string)
let matches = Self.regex.matches(in: string, options: [], range: range)
var placeholders: [Placeholder] = []
for match in matches {
let nsRange = match.range(at: 1)
if let placeholderRange = Range(nsRange, in: string) {
if nsRange.location > 1,
let precedingCharRange = Range(NSRange(location: nsRange.location-2, length: 1), in: string),
String(string[precedingCharRange]) == "\\" {
// exclude escaped placeholders
continue
}
let placeholder = String(string[placeholderRange])
let placeholderParts = placeholder.split(separator: ":").map(String.init)
switch placeholderParts.count {
case 0:
placeholders.append(Placeholder(name: placeholder))
case 1:
placeholders.append(Placeholder(name: placeholder))
case 2:
placeholders.append(Placeholder(name: placeholderParts[0], type: placeholderParts[1]))
default:
fatalError("Placeholder cannot contain more than one \":\"")
}
}
}
return placeholders
}
public static func en(_ string: String) -> StringLocalization {
StringLocalization(language: "en", string: string)
}
public static func base(_ string: String) -> StringLocalization {
StringLocalization(language: "base", string: string)
}
public func getPlaceholder(name: String) -> Placeholder? {
placeholders.first { $0.name == name }
}
public func replacePlaceholders(_ string: String, pattern: (Placeholder) -> String) -> String {
guard string.contains("{") else { return string }
var string = string
for placeholder in placeholders {
string = string.replacingOccurrences(of: placeholder.originalPlaceholder, with: pattern(placeholder))
}
string = string.replacingOccurrences(of: #"\\\{(\S+)\}"#, with: "{$1}", options: .regularExpression)
return string
}
}
extension StringLocalization {
init(_ dictionary: [String: Any]) {
var placeholders: [Placeholder] = []
var languages: [String: Language] = [:]
for (key, value) in dictionary {
let keyParts = key.components(separatedBy: ".")
let code = keyParts[0]
var language = languages[code] ?? Language(code: code, string: "", plurals: [:])
switch keyParts.count {
case 1:
if let string = value as? String {
language.string = string
let stringPlaceholders = Self.parsePlaceholders(string)
for placeholder in stringPlaceholders {
if !placeholders.contains { $0.name == placeholder.name } {
placeholders.append(placeholder)
}
}
}
case 2:
let placeholder = keyParts[1]
if let pluralDictionary = value as? [String: String] {
for (pluralString, pluralValue) in pluralDictionary {
if let plural = Plural(rawValue: pluralString) {
language.plurals[placeholder, default: [:]][plural] = pluralValue
}
}
}
default:
break
}
languages[code] = language
}
self.placeholders = placeholders
self.languages = languages
}
}
| yonaskolb/Stringly | 18 | Manage and generate localization files | Swift | yonaskolb | Yonas Kolb | |
Tests/Fixtures/Strings.swift | Swift | // This file was auto-generated with https://github.com/yonaskolb/Stringly
// swiftlint:disable all
import Foundation
public enum Strings {
/// Ok
public static let ok = Strings.localized("ok")
public enum auth: StringGroup {
public static let localizationKey = "auth"
/// Email
public static let emailTitle = Strings.localized("emailTitle", in: localizationKey)
/// Log In
public static let loginButton = Strings.localized("loginButton", in: localizationKey)
/// Password
public static let passwordTitle = Strings.localized("passwordTitle", in: localizationKey)
public enum error: StringGroup {
public static let localizationKey = "auth.error"
/// Incorrect email/password combination
public static let wrongEmailPassword = Strings.localized("wrongEmailPassword", in: localizationKey)
}
}
public enum languages: StringGroup {
public static let localizationKey = "languages"
/// Hello
public static let greeting = Strings.localized("greeting", in: localizationKey)
}
public enum placeholders: StringGroup {
public static let localizationKey = "placeholders"
/// Text with escaped {braces}
public static let escaped = Strings.localized("escaped", in: localizationKey)
/// **{name}** with number **{number}**
public static func hello(name: String, number: Int) -> String {
Strings.localized("hello", in: localizationKey, name, number)
}
/// Text **{}**
public static func unnamed(_ p0: String) -> String {
Strings.localized("unnamed", in: localizationKey, p0)
}
}
public enum plurals: StringGroup {
public static let localizationKey = "plurals"
/// There **{pluralized appleCount}** in the garden
public static func apples(appleCount: Int) -> String {
Strings.localized("apples", in: localizationKey, appleCount)
}
}
public enum welcome: StringGroup {
public static let localizationKey = "welcome"
/// Hello %@
public static let title = Strings.localized("title", in: localizationKey)
}
}
public protocol StringGroup {
static var localizationKey: String { get }
}
extension StringGroup {
public static func string(for key: String, _ args: CVarArg...) -> String {
return Strings.localized(key: "\(localizationKey).\(key)", args: args)
}
}
extension Strings {
/// The bundle uses for localization
public static var bundle: Bundle = Bundle(for: BundleToken.self)
/// Allows overriding any particular key, for A/B tests for example. Values need to be correct for the current language
public static var overrides: [String: String] = [:]
fileprivate static func localized(_ key: String, in group: String, _ args: CVarArg...) -> String {
return Strings.localized(key: "\(group).\(key)", args: args)
}
fileprivate static func localized(_ key: String, _ args: CVarArg...) -> String {
return Strings.localized(key: key, args: args)
}
fileprivate static func localized(key: String, args: [CVarArg]) -> String {
let format = overrides[key] ?? NSLocalizedString(key, tableName: "Strings", bundle: bundle, comment: "")
return String(format: format, locale: Locale.current, arguments: args)
}
}
private final class BundleToken {} | yonaskolb/Stringly | 18 | Manage and generate localization files | Swift | yonaskolb | Yonas Kolb | |
Tests/StringlyCLITests/StringDiff.swift | Swift | import Foundation
// https://gist.github.com/kristopherjohnson/543687c763cd6e524c91
/// Find first differing character between two strings
///
/// :param: s1 First String
/// :param: s2 Second String
///
/// :returns: .DifferenceAtIndex(i) or .NoDifference
public func firstDifferenceBetweenStrings(_ s1: String, _ s2: String) -> FirstDifferenceResult {
let len1 = s1.count
let len2 = s2.count
let lenMin = min(len1, len2)
for i in 0..<lenMin {
if (s1 as NSString).character(at: i) != (s2 as NSString).character(at: i) {
return .DifferenceAtIndex(i)
}
}
if len1 < len2 {
return .DifferenceAtIndex(len1)
}
if len2 < len1 {
return .DifferenceAtIndex(len2)
}
return .NoDifference
}
/// Create a formatted String representation of difference between strings
///
/// :param: s1 First string
/// :param: s2 Second string
///
/// :returns: a string, possibly containing significant whitespace and newlines
public func prettyFirstDifferenceBetweenStrings(_ s1: String, _ s2: String, previewPrefixLength: Int = 25, previewSuffixLength: Int = 25) -> String {
let firstDifferenceResult = firstDifferenceBetweenStrings(s1, s2)
func diffString(at index: Int, _ s1: String, _ s2: String) -> String {
let markerArrow = "\u{2b06}" // "⬆"
let ellipsis = "\u{2026}" // "…"
/// Given a string and a range, return a string representing that substring.
///
/// If the range starts at a position other than 0, an ellipsis
/// will be included at the beginning.
///
/// If the range ends before the actual end of the string,
/// an ellipsis is added at the end.
func windowSubstring(_ s: String, _ range: NSRange) -> String {
let validRange = NSMakeRange(range.location, min(range.length, s.count - range.location))
let substring = (s as NSString).substring(with: validRange)
let prefix = range.location > 0 ? ellipsis : ""
let suffix = (s.count - range.location > range.length) ? ellipsis : ""
return "\(prefix)\(substring)\(suffix)"
}
// Show this many characters before and after the first difference
let windowLength = previewPrefixLength + 1 + previewSuffixLength
let windowIndex = max(index - previewPrefixLength, 0)
let windowRange = NSMakeRange(windowIndex, windowLength)
let sub1 = windowSubstring(s1, windowRange)
let sub2 = windowSubstring(s2, windowRange)
let markerPosition = min(previewSuffixLength, index) + (windowIndex > 0 ? 1 : 0)
let markerPrefix = String(repeating: " ", count: markerPosition)
let markerLine = "\(markerPrefix)\(markerArrow)"
return "Difference at index \(index):\n\(sub1)\n\(sub2)\n\(markerLine)"
}
switch firstDifferenceResult {
case .NoDifference: return "No difference"
case let .DifferenceAtIndex(index): return diffString(at: index, s1, s2)
}
}
/// Result type for firstDifferenceBetweenStrings()
public enum FirstDifferenceResult {
/// Strings are identical
case NoDifference
/// Strings differ at the specified index.
///
/// This could mean that characters at the specified index are different,
/// or that one string is longer than the other
case DifferenceAtIndex(Int)
}
| yonaskolb/Stringly | 18 | Manage and generate localization files | Swift | yonaskolb | Yonas Kolb | |
Tests/StringlyCLITests/StringlyCLITests.swift | Swift | import XCTest
import StringlyCLI
import PathKit
final class StringlyTests: XCTestCase {
static let fixturePath = Path(#file).parent().parent() + "Fixtures"
static let stringsYamlPath = fixturePath + "Strings.yml"
func generateFileDiff(destination: Path, language: String = "en", file: StaticString = #file, line: UInt = #line) throws {
let previousFile: String = try destination.read()
let cli = StringlyCLI()
let output = cli.run(arguments: ["generate-file", Self.stringsYamlPath.string, destination.string, "--language", language])
XCTAssertEqual(0, output, file: file, line: line)
let newFile: String = try destination.read()
if newFile != previousFile {
let message = prettyFirstDifferenceBetweenStrings(newFile, previousFile)
XCTFail("\(destination.lastComponent) has changed:\n\(message)", file: file, line: line)
}
}
func testStringsGeneration() throws {
try generateFileDiff(destination: Self.fixturePath + "en.lproj/Strings.strings")
}
func testStringsDictGeneration() throws {
try generateFileDiff(destination: Self.fixturePath + "en.lproj/Strings.stringsdict")
}
func testSwiftGeneration() throws {
try generateFileDiff(destination: Self.fixturePath + "Strings.swift")
}
func testfileParsing() throws {
let tomlStrings = try Loader.loadStrings(from: Self.fixturePath + "Strings.yml", baseLanguage: "en")
let yamlStrings = try Loader.loadStrings(from: Self.fixturePath + "Strings.toml", baseLanguage: "en")
XCTAssertEqual(tomlStrings, yamlStrings)
}
func testXGenerate() throws {
let cli = StringlyCLI()
let output = cli.run(arguments: ["generate", Self.stringsYamlPath.string])
XCTAssertEqual(0, output)
}
}
| yonaskolb/Stringly | 18 | Manage and generate localization files | Swift | yonaskolb | Yonas Kolb | |
Tests/StringlyCLITests/TestHelpers.swift | Swift | //
// File.swift
//
//
// Created by Yonas Kolb on 17/10/19.
//
import Foundation
import SwiftCLI
extension CLI {
static func capture(_ block: () -> ()) -> (String, String) {
let out = CaptureStream()
let err = CaptureStream()
Term.stdout = out
Term.stderr = err
block()
Term.stdout = WriteStream.stdout
Term.stderr = WriteStream.stderr
out.closeWrite()
err.closeWrite()
return (out.readAll(), err.readAll())
}
}
| yonaskolb/Stringly | 18 | Manage and generate localization files | Swift | yonaskolb | Yonas Kolb | |
Tests/StringlyKitTests/StringlyKitTests.swift | Swift | import XCTest
import StringlyKit
import PathKit
final class StringlyTests: XCTestCase {
static let fixturePath = Path(#file).parent().parent() + "Fixtures"
static let yamlPath = fixturePath + "Strings.yml"
static let tomlPath = fixturePath + "Strings.toml"
static let stringsPath = fixturePath + "Strings.strings"
func testParsing() throws {
let dictionary: [String: Any] = [
"group": [
"simple": "value",
"group2": [
"simple2": "value"
]
],
"placeholders": [
"string": "Hello {name} how many {numbers:u}",
"escaped": "A \\{brace}",
"unnamed": "Text {}",
]
]
let strings = StringGroup(dictionary, baseLanguage: "en")
let expectedString = StringGroup(groups: [
StringGroup(
path: ["group"],
groups: [
StringGroup(
path: ["group", "group2"],
strings: ["simple2" : .en("value")]
)
],
strings: ["simple": .en("value")]
),
StringGroup(
path: ["placeholders"],
strings: [
"string": StringLocalization(
language: "en",
string: "Hello {name} how many {numbers:u}",
placeholders: [
StringLocalization.Placeholder(name: "name"),
StringLocalization.Placeholder(name: "numbers", type: "u")
]),
"escaped": StringLocalization(
language: "en",
string: "A \\{brace}",
placeholders: []
),
"unnamed": StringLocalization(
language: "en",
string: "Text {}",
placeholders: [StringLocalization.Placeholder(name: ""),]
),
])
])
XCTAssertEqual(strings, expectedString)
}
}
| yonaskolb/Stringly | 18 | Manage and generate localization files | Swift | yonaskolb | Yonas Kolb | |
Example/Example/App.swift | Swift | import SwiftUI
import SwiftComponent
@main
struct ExampleApp: App {
var body: some Scene {
WindowGroup {
ExamplesView()
}
}
}
struct MyPreviewProvider_Previews: PreviewProvider {
static var previews: some View {
ComponentListView(components: components)
}
}
| yonaskolb/SwiftComponent | 16 | Where architecture meets tooling | Swift | yonaskolb | Yonas Kolb | |
Example/Example/Components/Counter.component.swift | Swift | import Foundation
import SwiftComponent
import SwiftUI
@ComponentModel
struct CounterModel {
struct State: Equatable {
var count = 0
var displayingCount = true
}
enum Action {
case updateCount(Int)
case reset
}
func handle(action: Action) async {
switch action {
case .updateCount(let amount):
state.count += amount
case .reset:
mutate(\.self, .init())
}
}
}
struct CounterView: ComponentView {
var model: ViewModel<CounterModel>
var view: some View {
VStack {
HStack {
button(.updateCount(-1)) {
Image(systemName: "chevron.down")
}
.buttonStyle(.borderedProminent)
button(.updateCount(1)) {
Image(systemName: "chevron.up")
}
.buttonStyle(.borderedProminent)
}
HStack {
Toggle("Count", isOn: model.binding(\.displayingCount))
.fixedSize()
if model.displayingCount {
Text(model.count.formatted())
.frame(minWidth: 20, alignment: .leading)
}
}
button(.reset, "Reset")
}
}
}
struct CounterComponent: Component, PreviewProvider {
typealias Model = CounterModel
static func view(model: ViewModel<CounterModel>) -> some View {
CounterView(model: model.logEvents().sendViewBodyEvents())
}
static var preview = PreviewModel(state: .init())
}
| yonaskolb/SwiftComponent | 16 | Where architecture meets tooling | Swift | yonaskolb | Yonas Kolb | |
Example/Example/Components/CounterCombine.component.swift | Swift | import Foundation
import SwiftComponent
import SwiftUI
@ComponentModel
struct CounterCombineModel {
struct State: Equatable {
var counter1 = CounterModel.State()
var counter2 = CounterModel.State()
var displayCount = true
}
}
struct CounterCombineView: ComponentView {
var model: ViewModel<CounterCombineModel>
var view: some View {
VStack(spacing: 20) {
CounterView(model: model.scope(state: \.counter1))
CounterView(model: model.scope(state: \.counter2))
HStack {
Toggle("Count", isOn: model.binding(\.displayCount))
.fixedSize()
if model.displayCount {
Text("Total: \(model.counter1.count + model.counter2.count)")
}
}
}
}
}
struct CounterCombineComponent: Component, PreviewProvider {
typealias Model = CounterCombineModel
static func view(model: ViewModel<CounterCombineModel>) -> some View {
CounterCombineView(model: model.logEvents().sendViewBodyEvents())
}
static var preview: PreviewModel = .init(state: .init())
}
| yonaskolb/SwiftComponent | 16 | Where architecture meets tooling | Swift | yonaskolb | Yonas Kolb | |
Example/Example/Components/Item.component.swift | Swift | import SwiftUI
import SwiftComponent
@ComponentModel
struct ItemModel {
struct Connections {
let detail = Connection<ItemDetailModel>(output: .input(Input.detail))
.connect(state: \.detail)
let presentedDetail = Connection<ItemDetailModel>(output: .input(Input.detail))
.connect(state: \.destination, case: \.detail)
}
struct State {
var name: String
var text: String = "text"
var unreadProperty = 0
@Resource var data: Int?
var presentedDetail: ItemDetailModel.State?
var detail: ItemDetailModel.State = .init(id: "0", name: "0")
var destination: Destination?
}
enum Route {
case detail(ComponentRoute<ItemDetailModel>)
}
enum Destination {
case detail(ItemDetailModel.State)
}
enum Action {
case calculate
case present
case push
case updateDetail
case updateUnread
}
enum Input {
case detail(ItemDetailModel.Output)
}
func connect(route: Route) -> RouteConnection {
switch route {
case .detail(let route):
return connect(route, output: Input.detail)
}
}
func appear() async {
await loadResource(\.$data) {
try await dependencies.continuousClock.sleep(for: .seconds(1))
return Int.random(in: 0...100)
}
}
func handle(action: Action) async {
switch action {
case .calculate:
try? await dependencies.continuousClock.sleep(for: .seconds(1))
state.name = String(UUID().uuidString.prefix(6))
case .present:
state.presentedDetail = state.detail
case .push:
// route(to: Route.detail, state: state.detail)
state.destination = .init(.detail(state.detail))
case .updateDetail:
state.detail.name = Int.random(in: 0...1000).description
case .updateUnread:
state.unreadProperty += 1
}
}
func handle(input: Input) async {
switch input {
case .detail(.finished(let name)):
state.detail.name = name
state.name = name
state.presentedDetail = nil
}
}
}
struct ItemView: ComponentView {
var model: ViewModel<ItemModel>
func presentation(for route: ItemModel.Route) -> Presentation {
switch route {
case .detail:
return .push
}
}
func view(route: ItemModel.Route) -> some View {
switch route {
case .detail(let route):
ItemDetailView(model: route.model)
}
}
var view: some View {
VStack {
Text(model.state.name)
ResourceView(model.state.$data) { state in
Text(state.description)
} error: { error in
Text(error.localizedDescription)
}
.frame(height: 30)
HStack {
Text("Detail name: \(model.state.detail.name)")
button(.updateDetail, "Update Detail")
}
ItemDetailView(model: model.connectedModel(\.detail))
.fixedSize()
TextField("Field", text: model.binding(\.text))
.textFieldStyle(.roundedBorder)
button(.calculate, "Calculate")
button(.updateUnread, "Update unread")
button(.present, "Item")
button(.push, "Push Item")
Spacer()
}
.padding()
.navigationDestination(item: model.presentedModel(\.presentedDetail)) { model in
ItemDetailView(model: model)
.toolbar {
button(.updateDetail) {
Text("Save")
}
}
}
}
}
@ComponentModel
struct ItemDetailModel {
struct State: Identifiable, Equatable {
var id: String
var name: String
}
enum Action {
case save
case updateName
}
enum Output: Equatable {
case finished(String)
}
func appear() async {
}
func binding(keyPath: PartialKeyPath<State>) async {
}
func handle(action: Action) async {
switch action {
case .save:
output(.finished(state.name))
dismiss()
case .updateName:
state.name = Int.random(in: 0...100).description
}
}
}
struct ItemDetailView: ComponentView {
var model: ViewModel<ItemDetailModel>
var view: some View {
VStack {
Text("Item Detail \(model.state.name)")
.bold()
button(.updateName) {
Text("Update name")
}
}
}
}
struct ItemComponent: Component, PreviewProvider {
typealias Model = ItemModel
static func view(model: ViewModel<ItemModel>) -> some View {
ItemView(model: model.sendViewBodyEvents())
}
static var preview = PreviewModel(state: .init(name: "start"))
static var tests: Tests {
Test(state: .init(name: "john")) {
Step.appear()
.expectResourceTask(\.$data)
Step.snapshot("loaded")
Step.action(.updateDetail)
Step.binding(\.text, "yeah")
}
}
}
| yonaskolb/SwiftComponent | 16 | Where architecture meets tooling | Swift | yonaskolb | Yonas Kolb | |
Example/Example/Components/Resource.component.swift | Swift | import Foundation
import SwiftComponent
import SwiftUI
@ComponentModel
struct ResourceLoaderModel {
struct State {
@Resource var itemAutoload: Item?
@Resource var itemLoad: Item?
}
struct Item: Equatable {
var name: String
var count: Int
}
enum Action {
case load
}
func appear() async {
await loadResource(\.$itemAutoload) {
return Item(name: "loaded on appear", count: 1)
}
}
func handle(action: Action) async {
switch action {
case .load:
await loadResource(\.$itemLoad) {
try? await dependencies.continuousClock.sleep(for: .seconds(1))
return Item(name: "loaded from an action", count: .random(in: 0..<100))
}
}
}
}
struct ResourceLoaderView: ComponentView {
var model: ViewModel<ResourceLoaderModel>
var view: some View {
let _ = Self._printChanges()
VStack {
ResourceView(model.$itemAutoload) { item in
Text(item.name)
} error: { error in
Text("\(error)").foregroundStyle(.red)
}
button(.load, "Load")
ResourceView(model.$itemLoad) { item in
Text("\(item.name)\(item.count)")
} error: { error in
Text("\(error)").foregroundStyle(.red)
}
.fixedSize()
Spacer()
}
.padding()
}
}
struct ResourceLoaderComponent: Component, PreviewProvider {
typealias Model = ResourceLoaderModel
static func view(model: ViewModel<Model>) -> some View {
ResourceLoaderView(model: model.logEvents().sendViewBodyEvents())
}
static var preview = PreviewModel(state: .init())
}
| yonaskolb/SwiftComponent | 16 | Where architecture meets tooling | Swift | yonaskolb | Yonas Kolb | |
Example/Example/Examples.swift | Swift | import SwiftUI
import SwiftComponent
struct ExamplesView: View {
var body: some View {
NavigationStack {
Form {
NavigationLink("Counter") {
CounterView(model: ViewModel(state: .init()))
}
NavigationLink("Counter Combine") {
CounterCombineView(model: ViewModel(state: .init()))
}
NavigationLink("Resource Loading") {
ResourceLoaderView(model: ViewModel(state: .init()))
}
}
}
}
}
#Preview {
ExamplesView()
}
| yonaskolb/SwiftComponent | 16 | Where architecture meets tooling | Swift | yonaskolb | Yonas Kolb | |
Package.swift | Swift | // swift-tools-version: 5.9
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
import CompilerPluginSupport
var package = Package(
name: "SwiftComponent",
platforms: [.iOS(.v15), .macOS(.v12)],
products: [
.library(name: "SwiftComponent", targets: ["SwiftComponent"]),
.plugin(name: "SwiftComponentBuildPlugin", targets: ["SwiftComponentBuildPlugin"])
],
dependencies: [
.package(url: "https://github.com/yonaskolb/SwiftGUI", from: "0.3.0"),
.package(url: "https://github.com/pointfreeco/swift-custom-dump", from: "1.3.0"),
.package(url: "https://github.com/yonaskolb/swift-dependencies", from: "1.7.1"),
.package(url: "https://github.com/pointfreeco/swift-case-paths", from: "1.7.0"),
.package(url: "https://github.com/pointfreeco/swift-macro-testing", from: "0.5.0"),
.package(url: "https://github.com/pointfreeco/swift-perception", from: "1.6.0"),
.package(url: "https://github.com/pointfreeco/swift-identified-collections", from: "1.0.0"),
.package(url: "https://github.com/pointfreeco/swift-snapshot-testing", from: "1.18.4"),
.package(url: "https://github.com/wickwirew/Runtime", from: "2.2.7"),
.package(url: "https://github.com/swiftlang/swift-syntax", from: "601.0.1"),
.package(url: "https://github.com/yonaskolb/AccessibilitySnapshot", from: "0.8.1"),
.package(url: "https://github.com/apple/swift-argument-parser.git", from: "1.2.0"),
.package(url: "https://github.com/pointfreeco/swiftui-navigation", from: "1.3.0"),
],
targets: [
.executableTarget(name: "SwiftComponentCLI", dependencies: [
.product(name: "SwiftParser", package: "swift-syntax"),
.product(name: "ArgumentParser", package: "swift-argument-parser"),
]),
.target(
name: "SwiftComponent",
dependencies: [
.product(name: "CustomDump", package: "swift-custom-dump"),
.product(name: "Dependencies", package: "swift-dependencies"),
.product(name: "SwiftParser", package: "swift-syntax"),
.product(name: "CasePaths", package: "swift-case-paths"),
.product(name: "SwiftUINavigation", package: "swiftui-navigation"),
.product(name: "Perception", package: "swift-perception"),
.product(name: "IdentifiedCollections", package: "swift-identified-collections"),
"SwiftGUI",
"SwiftPreview",
"Runtime",
"SwiftComponentMacros",
]),
.target(
name: "SwiftPreview",
dependencies: [
.product(name: "AccessibilitySnapshotCore", package: "AccessibilitySnapshot", condition: .when(platforms: [.iOS])),
]),
.testTarget(
name: "SwiftComponentTests",
dependencies: [
"SwiftComponent",
.product(name: "SnapshotTesting", package: "swift-snapshot-testing"),
.product(name: "InlineSnapshotTesting", package: "swift-snapshot-testing"),
]),
.testTarget(
name: "SwiftComponentMacroTests",
dependencies: [
"SwiftComponentMacros",
.product(name: "MacroTesting", package: "swift-macro-testing"),
]),
.plugin(name: "SwiftComponentBuildPlugin", capability: .buildTool(), dependencies: ["SwiftComponentCLI"]),
.macro(
name: "SwiftComponentMacros",
dependencies: [
.product(name: "SwiftSyntaxMacros", package: "swift-syntax"),
.product(name: "SwiftCompilerPlugin", package: "swift-syntax")
]
),
]
)
| yonaskolb/SwiftComponent | 16 | Where architecture meets tooling | Swift | yonaskolb | Yonas Kolb | |
Plugins/SwiftComponentBuildPlugin/main.swift | Swift | import Foundation
import PackagePlugin
#if canImport(XcodeProjectPlugin)
import XcodeProjectPlugin
#endif
@main
struct ComponentBuilderPlugin {
func generateComponentsCommand(executable: Path, directory: Path, output: Path) -> Command {
.buildCommand(displayName: "Generate Component List",
executable: executable,
arguments: ["generate-components", directory, output],
environment: [:],
inputFiles: [],
outputFiles: [output])
}
}
extension ComponentBuilderPlugin: BuildToolPlugin {
func createBuildCommands(context: PluginContext, target: Target) async throws -> [Command] {
[
generateComponentsCommand(
executable: try context.tool(named: "SwiftComponentCLI").path,
directory: target.directory,
output: context.pluginWorkDirectory.appending("Components.swift")
)
]
}
}
#if canImport(XcodeProjectPlugin)
import XcodeProjectPlugin
extension ComponentBuilderPlugin: XcodeBuildToolPlugin {
func createBuildCommands(context: XcodePluginContext, target: XcodeTarget) throws -> [Command] {
[
generateComponentsCommand(
executable: try context.tool(named: "SwiftComponentCLI").path,
// TODO: The target name may not always be where we want to search for components
directory: context.xcodeProject.directory.appending(target.displayName),
output: context.pluginWorkDirectory.appending("Components.swift")
)
]
}
}
#endif
| yonaskolb/SwiftComponent | 16 | Where architecture meets tooling | Swift | yonaskolb | Yonas Kolb | |
Sources/SwiftComponent/ActionButton.swift | Swift | //
// File.swift
//
//
// Created by Yonas Kolb on 30/1/2023.
//
import Foundation
import SwiftUI
extension ViewModel {
public func button<Label: View>(_ action: @escaping @autoclosure () -> Model.Action, file: StaticString = #filePath, line: UInt = #line, @ViewBuilder label: () -> Label) -> some View {
ActionButtonView(model: self, action: action, file: file, line: line, label: label)
}
public func button(_ action: @escaping @autoclosure () -> Model.Action, _ text: LocalizedStringKey, file: StaticString = #filePath, line: UInt = #line) -> some View {
ActionButtonView(model: self, action: action, file: file, line: line) { Text(text) }
}
public func button(_ action: @escaping @autoclosure () -> Model.Action, _ text: String, file: StaticString = #filePath, line: UInt = #line) -> some View {
ActionButtonView(model: self, action: action, file: file, line: line) { Text(text) }
}
}
extension ComponentView {
public func button<Label: View>(_ action: @escaping @autoclosure () -> Model.Action, file: StaticString = #filePath, line: UInt = #line, @ViewBuilder label: () -> Label) -> some View {
ActionButtonView(model: model, action: action, file: file, line: line, label: label)
}
public func button(_ action: @escaping @autoclosure () -> Model.Action, _ text: LocalizedStringKey, file: StaticString = #filePath, line: UInt = #line) -> some View {
ActionButtonView(model: model, action: action, file: file, line: line) { Text(text) }
}
public func button(_ action: @escaping @autoclosure () -> Model.Action, _ text: String, file: StaticString = #filePath, line: UInt = #line) -> some View {
ActionButtonView(model: model, action: action, file: file, line: line) { Text(text) }
}
}
fileprivate class DispatchWorkContainer {
var work: DispatchWorkItem?
}
private struct ShowActionButtonFlashKey: EnvironmentKey {
static var defaultValue: Bool = false
}
extension EnvironmentValues {
public var showActionButtonFlash: Bool {
get {
self[ShowActionButtonFlashKey.self]
}
set {
self[ShowActionButtonFlashKey.self] = newValue
}
}
}
struct ActionButtonView<Model: ComponentModel, Label: View>: View {
@State var actioned = false
@Environment(\.showActionButtonFlash) var showActionButtonFlash
let dismissAfter: TimeInterval = 0.3
/// Reference to dispatch work, to be able to cancel it when needed
@State fileprivate var dispatchWorkContainer = DispatchWorkContainer()
var model: ViewModel<Model>
var action: () -> Model.Action
var file: StaticString
var line: UInt
var label: Label
init(
model: ViewModel<Model>,
action: @escaping () -> Model.Action,
file: StaticString = #filePath,
line: UInt = #line,
@ViewBuilder label: () -> Label) {
self.model = model
self.action = action
self.file = file
self.line = line
self.label = label()
}
func didAction() {
actioned = true
dispatchWorkContainer.work?.cancel()
dispatchWorkContainer.work = DispatchWorkItem(block: { actioned = false })
if let work = dispatchWorkContainer.work {
DispatchQueue.main.asyncAfter(deadline: .now() + dismissAfter, execute: work)
}
}
var body: some View {
Button {
model.send(action(), file: file, line: line)
} label: { label }
#if DEBUG
.accessibility(hint: Text("action: \(getEnumCase(action()).name)"))
//.accessibilityCustomContent("swift.component.action", getEnumCase(action()).name, importance: .high) // AccessibilitySnapshot doesn't seem to pick this up. Yet?
.onReceive(EventStore.shared.eventPublisher) { event in
guard showActionButtonFlash else { return }
switch event.type {
case .action(let eventAction):
guard let eventAction = eventAction as? Model.Action
else { return }
if areMaybeEqual(action, eventAction) {
didAction()
} else {
if String(describing: action) == String(describing: eventAction) {
didAction()
}
}
default: break
}
}
.overlay {
if actioned {
Color.red.opacity(actioned ? 0.3 : 0)
.animation(.default, value: actioned)
}
}
#endif
}
}
| yonaskolb/SwiftComponent | 16 | Where architecture meets tooling | Swift | yonaskolb | Yonas Kolb | |
Sources/SwiftComponent/Component.swift | Swift | import Foundation
import SwiftUI
public protocol Component: PreviewProvider {
associatedtype Model: ComponentModel
associatedtype ViewType: View
typealias PreviewModel = ComponentSnapshot<Model>
typealias Snapshots = [ComponentSnapshot<Model>]
typealias Snapshot = ComponentSnapshot<Model>
typealias Tests = [Test<Self>]
typealias Route = ComponentModelRoute<Model.Route>
typealias Routes = [Route]
@SnapshotBuilder<Model> static var snapshots: Snapshots { get }
@TestBuilder<Self> static var tests: Tests { get }
@RouteBuilder static var routes: Routes { get }
static var preview: PreviewModel { get }
@ViewBuilder static func view(model: ViewModel<Model>) -> ViewType
static var testAssertions: [TestAssertion] { get }
// provided by tests or snapshots if they exist
static var filePath: StaticString { get }
}
extension Component {
public static var routes: Routes { [] }
public static var testAssertions: [TestAssertion] { .standard }
public static var snapshots: Snapshots { [] }
public static var environmentName: String { String(describing: Model.Environment.self) }
public static var name: String { String(describing: Self.self).replacingOccurrences(of: "Component", with: "") }
}
extension Component {
public static var tests: Tests { [] }
public static var embedInNav: Bool { false }
@MainActor
public static var previews: some View {
Group {
componentPreview
.previewDisplayName(Model.baseName)
view(model: preview.viewModel())
.previewDisplayName("Preview")
.previewLayout(PreviewLayout.device)
ForEach(snapshots, id: \.name) { snapshot in
view(model: snapshot.viewModel())
.previewDisplayName(snapshot.name)
.previewReference()
.previewLayout(PreviewLayout.device)
}
ForEach(testSnapshots, id: \.name) { snapshot in
ComponentSnapshotView<Self>(snapshotName: snapshot.name)
.previewDisplayName(snapshot.name)
.previewReference()
.previewLayout(PreviewLayout.device)
}
}
}
public static var componentPreview: some View {
NavigationView {
ComponentPreview<Self>()
}
#if os(iOS)
.navigationViewStyle(.stack)
#endif
.largePreview()
}
@MainActor
public static func previewModel() -> ViewModel<Model> {
preview.viewModel().dependency(\.context, .preview)
}
/// Returns a view for a snapshot. Dependencies from the `preview` snapshot will be applied first
@MainActor
public static func view(snapshot: ComponentSnapshot<Model>) -> ViewType {
let viewModel = ViewModel<Model>(state: snapshot.state, environment: snapshot.environment, route: snapshot.route)
.apply(preview.dependencies)
.apply(snapshot.dependencies)
return view(model: viewModel)
}
}
extension Component {
public static var filePath: StaticString { preview.source.file } // { tests.first?.source.file ?? allSnapshots.first?.source.file ?? .init() }
static func readSource() -> String? {
guard !filePath.description.isEmpty else { return nil }
guard let data = FileManager.default.contents(atPath: filePath.description) else { return nil }
return String(decoding: data, as: UTF8.self)
}
static func writeSource(_ source: String) {
guard !filePath.description.isEmpty else { return }
let data = Data(source.utf8)
FileManager.default.createFile(atPath: filePath.description, contents: data)
}
}
| yonaskolb/SwiftComponent | 16 | Where architecture meets tooling | Swift | yonaskolb | Yonas Kolb | |
Sources/SwiftComponent/ComponentConnection.swift | Swift | import Foundation
import SwiftUI
import CasePaths
public struct ModelConnection<From: ComponentModel, To: ComponentModel> {
let id = UUID()
var output: OutputHandler<From, To>
var environment: Environment
var action: ActionHandler<From, To>?
var setDependencies: @MainActor (From, inout DependencyValues) -> Void = { _, _ in }
public typealias Environment = @MainActor (From, AnyHashable?) -> To.Environment
public init(output: OutputHandler<From, To>, environment: @escaping Environment) {
self.output = output
self.environment = environment
}
public init() where To.Output == Never, From.Environment == To.Environment {
self.init(output: .ignore) { model, _ in model.environment }
}
public init() where To.Output == Never, From.Environment.Parent == To.Environment {
self.init(output: .ignore) { model, _ in model.environment.parent }
}
public init(environment: @escaping Environment) where To.Output == Never {
self.init(output: .ignore, environment: environment)
}
public init(output: OutputHandler<From, To>) where From.Environment == To.Environment {
self.init(output: output) { model, _ in model.environment }
}
public init(output: OutputHandler<From, To>) where From.Environment.Parent == To.Environment {
self.init(output: output) { model, _ in model.environment.parent }
}
public init(output: @escaping (To.Output) -> From.Input) where From.Environment == To.Environment {
self.init(output: .input(output)) { model, _ in model.environment }
}
public init(output: @escaping (To.Output) -> From.Input) where From.Environment.Parent == To.Environment {
self.init(output: .input(output)) { model, _ in model.environment.parent }
}
public init(output: @escaping (To.Output) -> From.Input, environment: @escaping Environment) {
self.init(output: .input(output), environment: environment)
}
public init(_ output: @MainActor @escaping (ConnectionOutputContext<From, To>) async -> Void) where From.Environment == To.Environment {
self.init(output: .handle(output)) { model, _ in model.environment }
}
public init(_ output: @MainActor @escaping (ConnectionOutputContext<From, To>) async -> Void) where From.Environment.Parent == To.Environment {
self.init(output: .handle(output)) { model, _ in model.environment.parent }
}
public init(_ output: @MainActor @escaping (ConnectionOutputContext<From, To>) async -> Void, environment: @escaping Environment) {
self.init(output: .handle(output), environment: environment)
}
@MainActor
func connectedStore(from: ComponentStore<From>, state: ScopedState<From.State, To.State>, id: AnyHashable? = nil) -> ComponentStore<To> {
let connectionID = ConnectionID(
connectionID: self.id,
storeID: from.id,
childTypeName: String(describing: To.self),
stateID: state.id,
customID: id
)
if let existingStore = from.children[connectionID]?.value as? ComponentStore<To> {
return existingStore
}
var childStore = from.scope(
state: state,
environment: self.environment(from.model, id),
output: self.output
)
// set dependencies
setDependencies(from.model, &childStore.dependencies.dependencyValues)
from.children[connectionID] = .init(childStore)
if let actionHandler = self.action {
childStore = childStore
.onAction { @MainActor action, _ in
switch actionHandler {
case .output(let toOutput):
let output = toOutput(action)
from.output(output, source: .capture())
case .input(let toInput):
let input = toInput(action)
from.processInput(input, source: .capture())
case .handle(let handler):
from.addTask {
await handler((action: action, model: from.model))
}
}
}
}
return childStore
}
public func onAction(_ handle: @MainActor @escaping (ConnectionActionContext<From, To>) -> Void) -> Self {
self.onAction(.handle(handle))
}
public func onAction(_ action: ActionHandler<From, To>) -> Self {
var copy = self
copy.action = action
return copy
}
public func dependency<T>(_ keyPath: WritableKeyPath<DependencyValues, T>, value: T) -> Self {
dependency(keyPath) { _ in value }
}
public func dependency<T>(_ keyPath: WritableKeyPath<DependencyValues, T>, getValue: @MainActor @escaping (From) -> T) -> Self {
var copy = self
let originalSetDependencies = copy.setDependencies
copy.setDependencies = { @MainActor model, dependencies in
originalSetDependencies(model, &dependencies)
dependencies[keyPath: keyPath] = getValue(model)
}
return copy
}
}
public typealias ConnectionOutputContext<Parent: ComponentModel, Child: ComponentModel> = (output: Child.Output, model: Parent)
public typealias ConnectionActionContext<Parent: ComponentModel, Child: ComponentModel> = (action: Child.Action, model: Parent)
struct ConnectionID: Hashable {
let connectionID: UUID
let storeID: UUID
let childTypeName: String
let stateID: AnyHashable?
let customID: AnyHashable?
}
extension ViewModel {
@dynamicMemberLookup
public struct Connections {
let model: ViewModel<Model>
@MainActor
public subscript<Child: ComponentModel>(dynamicMember keyPath: KeyPath<Model.Connections, EmbeddedComponentConnection<Model, Child>>) -> ViewModel<Child> {
model.connectedModel(keyPath)
}
}
public var connections: Connections { Connections(model: self) }
@dynamicMemberLookup
public struct Presentations {
let model: ViewModel<Model>
@MainActor
public subscript<Child: ComponentModel>(dynamicMember keyPath: KeyPath<Model.Connections, PresentedComponentConnection<Model, Child>>) -> Binding<ViewModel<Child>?> {
model.presentedModel(keyPath)
}
@MainActor
public subscript<Child: ComponentModel, Case: CasePathable>(dynamicMember keyPath: KeyPath<Model.Connections, PresentedCaseComponentConnection<Model, Child, Case>>) -> Binding<ViewModel<Child>?> {
model.presentedModel(keyPath)
}
}
public var presentations: Presentations { Presentations(model: self) }
}
extension ComponentView {
public var connections: ViewModel<Model>.Connections { model.connections }
}
extension ViewModel {
@MainActor
func connect<Child: ComponentModel>(to connectionPath: KeyPath<Model.Connections, ModelConnection<Model, Child>>, state: ScopedState<Model.State, Child.State>, id: AnyHashable? = nil) -> ViewModel<Child> {
let connection = store.model.connections[keyPath: connectionPath]
let store = connection.connectedStore(from: store, state: state, id: id)
// cache view models
if let model = children[store.id]?.value as? ViewModel<Child> {
return model
} else {
let model = store.viewModel()
children[store.id] = .init(model)
return model
}
}
}
extension ViewModel {
@MainActor
public func connectedModel<Child: ComponentModel>(_ connection: KeyPath<Model.Connections, ModelConnection<Model, Child>>, state: Child.State, id: AnyHashable?) -> ViewModel<Child> {
connect(to: connection, state: .value(state), id: id)
}
@MainActor
public func connectedModel<Child: ComponentModel>(_ connection: KeyPath<Model.Connections, ModelConnection<Model, Child>>, state: Child.State) -> ViewModel<Child> where Child.State: Hashable {
connect(to: connection, state: .value(state), id: state)
}
@MainActor
public func connectedModel<Child: ComponentModel>(_ connection: KeyPath<Model.Connections, ModelConnection<Model, Child>>, state: Binding<Child.State>) -> ViewModel<Child> {
connect(to: connection, state: .binding(state))
}
@MainActor
public func connectedModel<Child: ComponentModel>(_ connectionPath: KeyPath<Model.Connections, EmbeddedComponentConnection<Model, Child>>) -> ViewModel<Child> {
let connection = store.model.connections[keyPath: connectionPath]
return connect(to: connectionPath.appending(path: \.connection), state: .keyPath(connection.state))
}
@MainActor
public func connectedModel<Child: ComponentModel>(_ connectionPath: KeyPath<Model.Connections, PresentedComponentConnection<Model, Child>>, state: Child.State) -> ViewModel<Child> {
let connection = store.model.connections[keyPath: connectionPath]
return connect(to: connectionPath.appending(path: \.connection), state: .optionalKeyPath(connection.state, fallback: state))
}
@MainActor
public func connectedModel<Child: ComponentModel, Case: CasePathable>(_ connectionPath: KeyPath<Model.Connections, PresentedCaseComponentConnection<Model, Child, Case>>, state: Child.State) -> ViewModel<Child> {
let connection = store.model.connections[keyPath: connectionPath]
return connect(to: connectionPath.appending(path: \.connection), state: store.caseScopedState(state: connection.state, case: connection.casePath, value: state))
}
}
// presentation binding
extension ViewModel {
@MainActor
public func presentedModel<Child: ComponentModel>(_ connectionPath: KeyPath<Model.Connections, PresentedComponentConnection<Model, Child>>) -> Binding<ViewModel<Child>?> {
let connection = store.model.connections[keyPath: connectionPath]
return presentedModel(connectionPath.appending(path: \.connection), state: connection.state)
}
@MainActor
public func presentedModel<Child: ComponentModel, Case: CasePathable>(_ connectionPath: KeyPath<Model.Connections, PresentedCaseComponentConnection<Model, Child, Case>>) -> Binding<ViewModel<Child>?> {
let connection = store.model.connections[keyPath: connectionPath]
return presentedModel(connectionPath.appending(path: \.connection), state: connection.state, case: connection.casePath)
}
@MainActor
public func presentedModel<Child: ComponentModel>(_ connection: KeyPath<Model.Connections, ModelConnection<Model, Child>>, state: WritableKeyPath<Model.State, Child.State?>) -> Binding<ViewModel<Child>?> {
Binding(
get: {
if let presentedState = self.store.state[keyPath: state] {
return self.connect(to: connection, state: .optionalKeyPath(state, fallback: presentedState))
} else {
return nil
}
},
set: { model in
if model == nil, self.state[keyPath: state] != nil {
self.state[keyPath: state] = nil
}
}
)
}
@MainActor
public func presentedModel<Child: ComponentModel, StateEnum: CasePathable>(_ connection: KeyPath<Model.Connections, ModelConnection<Model, Child>>, state statePath: WritableKeyPath<Model.State, StateEnum?>, case casePath: CaseKeyPath<StateEnum, Child.State>) -> Binding<ViewModel<Child>?> {
Binding<ViewModel<Child>?>(
get: {
if let enumCase = self.store.state[keyPath: statePath],
let presentedState = enumCase[case: casePath] {
return self.connect(to: connection, state: self.store.caseScopedState(state: statePath, case: casePath, value: presentedState))
} else {
return nil
}
},
set: { model in
if model == nil, self.state[keyPath: statePath] != nil {
self.state[keyPath: statePath] = nil
}
}
)
}
}
extension ComponentModel {
public func connection<To: ComponentModel>(_ connectionPath: KeyPath<Connections, ModelConnection<Self, To>>, state: ScopedState<State, To.State>, id: AnyHashable? = nil, update: @MainActor (To) async -> Void) async {
let connection = self.connections[keyPath: connectionPath]
let store = connection.connectedStore(from: store, state: state, id: id)
await update(store.model)
}
public func connection<To: ComponentModel>(_ connectionPath: KeyPath<Connections, EmbeddedComponentConnection<Self, To>>, id: AnyHashable? = nil, _ update: @MainActor (To) async -> Void) async {
let connection = store.model.connections[keyPath: connectionPath]
await self.connection(connectionPath.appending(path: \.connection), state: .keyPath(connection.state), id: id, update: update)
}
public func connection<To: ComponentModel>(_ connectionPath: KeyPath<Connections, PresentedComponentConnection<Self, To>>, id: AnyHashable? = nil, _ update: @MainActor (To) async -> Void) async {
let connection = store.model.connections[keyPath: connectionPath]
guard let state = self.store.state[keyPath: connection.state] else { return }
await self.connection(connectionPath.appending(path: \.connection), state: .optionalKeyPath(connection.state, fallback: state), id: id, update: update)
}
public func connection<To: ComponentModel, Case: CasePathable>(_ connectionPath: KeyPath<Connections, PresentedCaseComponentConnection<Self, To, Case>>, id: AnyHashable? = nil, _ update: @MainActor (To) async -> Void) async {
let connection = store.model.connections[keyPath: connectionPath]
guard let `case` = self.store.state[keyPath: connection.state], let state = `case`[case: connection.casePath] else { return }
await self.connection(connectionPath.appending(path: \.connection), state: self.store.caseScopedState(state: connection.state, case: connection.casePath, value: state), id: id, update: update)
}
public func connection<To: ComponentModel>(_ connectionPath: KeyPath<Connections, ModelConnection<Self, To>>, state: WritableKeyPath<Self.State, To.State?>, id: AnyHashable? = nil, _ update: @MainActor (To) async -> Void) async {
guard let childState = store.state[keyPath: state] else { return }
await self.connection(connectionPath, state: .optionalKeyPath(state, fallback: childState), id: id, update: update)
}
public func connection<To: ComponentModel>(_ connectionPath: KeyPath<Connections, ModelConnection<Self, To>>, state: To.State, id: AnyHashable? = nil, _ update: @MainActor (To) async -> Void) async {
await self.connection(connectionPath, state: .value(state), id: id, update: update)
}
}
public enum OutputHandler<Parent: ComponentModel, Child: ComponentModel> {
case output((Child.Output) -> Parent.Output)
case input((Child.Output) -> Parent.Input)
case handle((ConnectionOutputContext<Parent, Child>) async -> Void)
case ignore
}
public enum ActionHandler<Parent: ComponentModel, Child: ComponentModel> {
case output((Child.Action) -> Parent.Output)
case input((Child.Action) -> Parent.Input)
case handle((ConnectionActionContext<Parent, Child>) async -> Void)
}
// ModelConnection
extension TestStep {
@MainActor
public static func connection<Child: ComponentModel>(
_ connection: KeyPath<Model.Connections, ModelConnection<Model, Child>>,
state: Child.State,
file: StaticString = #filePath,
line: UInt = #line,
@TestStepBuilder<Child> steps: @escaping () -> [TestStep<Child>]
) -> Self {
Self.connection(connection, state: .value(state), file: file, line: line, steps: steps)
}
@MainActor
public static func connection<Child: ComponentModel>(
_ connection: KeyPath<Model.Connections, ModelConnection<Model, Child>>,
state: ScopedState<Model.State, Child.State>,
file: StaticString = #filePath,
line: UInt = #line,
@TestStepBuilder<Child> steps: @escaping () -> [TestStep<Child>]
) -> Self {
.init(
title: "Connection",
details: "\(Child.baseName)",
file: file,
line: line
) { context in
if context.delay > 0 {
try? await Task.sleep(nanoseconds: context.delayNanoseconds)
try? await Task.sleep(nanoseconds: UInt64(1_000_000_000.0 * 0.35)) // wait for typical presentation animation duration
}
let steps = steps()
let model = context.model.connect(to: connection, state: state)
var childContext = TestContext<Child>(model: model, delay: context.delay, assertions: context.assertions, state: model.state)
for step in steps {
let results = await step.runTest(context: &childContext)
context.childStepResults.append(results)
}
}
}
@MainActor
public static func connection<Child: ComponentModel>(
_ connection: KeyPath<Model.Connections, ModelConnection<Model, Child>>,
state: ScopedState<Model.State, Child.State>,
output: Child.Output,
file: StaticString = #filePath,
line: UInt = #line
) -> Self {
.init(
title: "Connection Output",
details: "\(Child.baseName).\(getEnumCase(output).name)",
file: file,
line: line
) { context in
let model = context.model.connect(to: connection, state: state)
await model.store.output(output, source: .capture(file: file, line: line))
}
}
@MainActor
public static func connection<Child: ComponentModel>(
_ connection: KeyPath<Model.Connections, ModelConnection<Model, Child>>,
state keyPath: WritableKeyPath<Model.State, Child.State?>,
output: Child.Output,
file: StaticString = #filePath,
line: UInt = #line
) -> Self {
.init(
title: "Connection Output",
details: "\(Child.baseName).\(getEnumCase(output).name)",
file: file,
line: line
) { context in
guard let state = context.model.state[keyPath: keyPath] else {
context.stepErrors.append(.init(error: "\(keyPath.propertyName ?? Child.baseName) not connected", source: .init(file: file, line: line)))
return
}
let model = context.model.connect(to: connection, state: .optionalKeyPath(keyPath, fallback: state))
await model.store.output(output, source: .capture(file: file, line: line))
}
}
@MainActor
public static func connection<Child: ComponentModel, Case: CasePathable>(
_ connection: KeyPath<Model.Connections, ModelConnection<Model, Child>>,
state keyPath: WritableKeyPath<Model.State, Case?>,
case casePath: CaseKeyPath<Case, Child.State>,
output: Child.Output,
file: StaticString = #filePath,
line: UInt = #line
) -> Self {
.init(
title: "Connection Output",
details: "\(Child.baseName).\(getEnumCase(output).name)",
file: file,
line: line
) { context in
guard let `case` = context.model.state[keyPath: keyPath], let state = `case`[case: casePath] else {
context.stepErrors.append(.init(error: "\(keyPath.propertyName ?? Child.baseName) not connected", source: .init(file: file, line: line)))
return
}
let model = context.model.connect(to: connection, state: context.model.store.caseScopedState(state: keyPath, case: casePath, value: state))
await model.store.output(output, source: .capture(file: file, line: line))
}
}
@MainActor
public static func connection<Child: ComponentModel, Case: CasePathable>(
_ connection: KeyPath<Model.Connections, ModelConnection<Model, Child>>,
state keyPath: WritableKeyPath<Model.State, Case?>,
case casePath: CaseKeyPath<Case, Child.State>,
file: StaticString = #filePath,
line: UInt = #line,
@TestStepBuilder<Child> steps: @escaping () -> [TestStep<Child>]
) -> Self {
.init(
title: "Connection",
details: "\(Child.baseName)",
file: file,
line: line
) { context in
guard let `case` = context.model.state[keyPath: keyPath], let state = `case`[case: casePath] else {
context.stepErrors.append(.init(error: "\(keyPath.propertyName ?? Child.baseName) not connected", source: .init(file: file, line: line)))
return
}
if context.delay > 0 {
try? await Task.sleep(nanoseconds: context.delayNanoseconds)
try? await Task.sleep(nanoseconds: UInt64(1_000_000_000.0 * 0.35)) // wait for typical presentation animation duration
}
let steps = steps()
let model = context.model.connect(to: connection, state: context.model.store.caseScopedState(state: keyPath, case: casePath, value: state))
var childContext = TestContext<Child>(model: model, delay: context.delay, assertions: context.assertions, state: model.state)
for step in steps {
let results = await step.runTest(context: &childContext)
context.childStepResults.append(results)
}
}
}
@MainActor
public static func connection<Child: ComponentModel>(
_ connection: KeyPath<Model.Connections, ModelConnection<Model, Child>>,
state keyPath: WritableKeyPath<Model.State, Child.State?>,
file: StaticString = #filePath,
line: UInt = #line,
@TestStepBuilder<Child> steps: @escaping () -> [TestStep<Child>]
) -> Self {
.init(
title: "Connection",
details: "\(Child.baseName)",
file: file,
line: line
) { context in
guard let state = context.model.state[keyPath: keyPath] else {
context.stepErrors.append(.init(error: "\(keyPath.propertyName ?? Child.baseName) not connected", source: .init(file: file, line: line)))
return
}
if context.delay > 0 {
try? await Task.sleep(nanoseconds: context.delayNanoseconds)
try? await Task.sleep(nanoseconds: UInt64(1_000_000_000.0 * 0.35)) // wait for typical presentation animation duration
}
let steps = steps()
let model = context.model.connect(to: connection, state: .optionalKeyPath(keyPath, fallback: state))
var childContext = TestContext<Child>(model: model, delay: context.delay, assertions: context.assertions, state: model.state)
for step in steps {
let results = await step.runTest(context: &childContext)
context.childStepResults.append(results)
}
}
}
}
extension TestStep {
@MainActor
public static func connection<Child: ComponentModel>(
_ connection: KeyPath<Model.Connections, ModelConnection<Model, Child>>,
file: StaticString = #filePath,
line: UInt = #line,
steps: @escaping () -> [TestStep<Child>],
createModel: @escaping (inout TestContext<Model>) -> (ViewModel<Child>?)
) -> Self {
.steps(
title: "Connection",
details: "\(Child.baseName)",
file: file,
line: line,
steps: steps,
createModel: createModel
)
}
@MainActor
public static func connection<Child: ComponentModel>(
_ connection: KeyPath<Model.Connections, ModelConnection<Model, Child>>,
file: StaticString = #filePath,
line: UInt = #line,
output: Child.Output,
createModel: @escaping (inout TestContext<Model>) -> ViewModel<Child>?
) -> Self {
.init(
title: "Connection",
details: "\(Child.baseName)",
file: file,
line: line
) { context in
guard let model = createModel(&context) else { return }
await model.store.output(output, source: .capture(file: file, line: line))
}
}
}
// ModelConnection.connected
extension TestStep {
@MainActor
public static func connection<Child: ComponentModel>(
_ connectionPath: KeyPath<Model.Connections, EmbeddedComponentConnection<Model, Child>>,
output: Child.Output,
file: StaticString = #filePath,
line: UInt = #line
) -> Self {
self.connection(connectionPath.appending(path: \.connection), output: output) { context in
let connection = context.model.store.model.connections[keyPath: connectionPath]
return context.model.connect(to: connectionPath.appending(path: \.connection), state: .keyPath(connection.state))
}
}
@MainActor
public static func connection<Child: ComponentModel>(
_ connectionPath: KeyPath<Model.Connections, EmbeddedComponentConnection<Model, Child>>,
file: StaticString = #filePath,
line: UInt = #line,
@TestStepBuilder<Child> steps: @escaping () -> [TestStep<Child>]
) -> Self {
self.connection(connectionPath.appending(path: \.connection), steps: steps) { context in
let connection = context.model.store.model.connections[keyPath: connectionPath]
return context.model.connect(to: connectionPath.appending(path: \.connection), state: .keyPath(connection.state))
}
}
@MainActor
public static func connection<Child: ComponentModel>(
_ connectionPath: KeyPath<Model.Connections, PresentedComponentConnection<Model, Child>>,
file: StaticString = #filePath,
line: UInt = #line,
@TestStepBuilder<Child> steps: @escaping () -> [TestStep<Child>]
) -> Self {
self.connection(connectionPath.appending(path: \.connection), steps: steps) { context in
let connection = context.model.store.model.connections[keyPath: connectionPath]
guard let state = context.model.state[keyPath: connection.state] else {
context.stepErrors.append(.init(error: "\(connection.state.propertyName ?? Child.baseName) not connected", source: .init(file: file, line: line)))
return nil
}
return context.model.connect(to: connectionPath.appending(path: \.connection), state: .optionalKeyPath(connection.state, fallback: state))
}
}
@MainActor
public static func connection<Child: ComponentModel>(
_ connectionPath: KeyPath<Model.Connections, PresentedComponentConnection<Model, Child>>,
output: Child.Output,
file: StaticString = #filePath,
line: UInt = #line
) -> Self {
self.connection(connectionPath.appending(path: \.connection), output: output) { context in
let connection = context.model.store.model.connections[keyPath: connectionPath]
guard let state = context.model.state[keyPath: connection.state] else {
context.stepErrors.append(.init(error: "\(connection.state.propertyName ?? Child.baseName) not connected", source: .init(file: file, line: line)))
return nil
}
return context.model.connect(to: connectionPath.appending(path: \.connection), state: .optionalKeyPath(connection.state, fallback: state))
}
}
@MainActor
public static func connection<Child: ComponentModel, Case: CasePathable>(
_ connectionPath: KeyPath<Model.Connections, PresentedCaseComponentConnection<Model, Child, Case>>,
file: StaticString = #filePath,
line: UInt = #line,
@TestStepBuilder<Child> steps: @escaping () -> [TestStep<Child>]
) -> Self {
self.connection(connectionPath.appending(path: \.connection), steps: steps) { context in
let connection = context.model.store.model.connections[keyPath: connectionPath]
guard let `case` = context.model.state[keyPath: connection.state], let state = `case`[case: connection.casePath] else {
context.stepErrors.append(.init(error: "\(connection.state.propertyName ?? Child.baseName) not connected", source: .init(file: file, line: line)))
return nil
}
return context.model.connect(to: connectionPath.appending(path: \.connection), state: context.model.store.caseScopedState(state: connection.state, case: connection.casePath, value: state))
}
}
@MainActor
public static func connection<Child: ComponentModel, Case: CasePathable>(
_ connectionPath: KeyPath<Model.Connections, PresentedCaseComponentConnection<Model, Child, Case>>,
output: Child.Output,
file: StaticString = #filePath,
line: UInt = #line
) -> Self {
self.connection(connectionPath.appending(path: \.connection), output: output) { context in
let connection = context.model.store.model.connections[keyPath: connectionPath]
guard let `case` = context.model.state[keyPath: connection.state], let state = `case`[case: connection.casePath] else {
context.stepErrors.append(.init(error: "\(connection.state.propertyName ?? Child.baseName) not connected", source: .init(file: file, line: line)))
return nil
}
return context.model.connect(to: connectionPath.appending(path: \.connection), state: context.model.store.caseScopedState(state: connection.state, case: connection.casePath, value: state))
}
}
}
public struct EmbeddedComponentConnection<From: ComponentModel, To: ComponentModel> {
public let connection: ModelConnection<From, To>
public let state: WritableKeyPath<From.State, To.State>
}
public struct PresentedComponentConnection<From: ComponentModel, To: ComponentModel> {
public let connection: ModelConnection<From, To>
public let state: WritableKeyPath<From.State, To.State?>
}
public struct PresentedCaseComponentConnection<From: ComponentModel, To: ComponentModel, Case: CasePathable> {
public let connection: ModelConnection<From, To>
public let state: WritableKeyPath<From.State, Case?>
public let casePath: CaseKeyPath<Case, To.State>
}
extension ModelConnection {
public func connect(state: WritableKeyPath<From.State, To.State>) -> EmbeddedComponentConnection<From, To> {
EmbeddedComponentConnection(connection: self, state: state)
}
public func connect(state: WritableKeyPath<From.State, To.State?>) -> PresentedComponentConnection<From, To> {
PresentedComponentConnection(connection: self, state: state)
}
public func connect<Case: CasePathable>(state: WritableKeyPath<From.State, Case?>, case casePath: CaseKeyPath<Case, To.State>) -> PresentedCaseComponentConnection<From, To, Case> {
PresentedCaseComponentConnection(connection: self, state: state, casePath: casePath)
}
}
| yonaskolb/SwiftComponent | 16 | Where architecture meets tooling | Swift | yonaskolb | Yonas Kolb | |
Sources/SwiftComponent/ComponentDependencies.swift | Swift | import Foundation
import Dependencies
@dynamicMemberLookup
public class ComponentDependencies {
var dependencyValues: DependencyValues
var accessedDependencies: Set<String> = []
var setDependencies: Set<String> = []
let lock = NSLock()
init() {
dependencyValues = DependencyValues._current
}
func withLock<T>(_ closure: () -> T) -> T {
lock.lock()
defer { lock.unlock() }
return closure()
}
public func setDependency<T>(_ keyPath: WritableKeyPath<DependencyValues, T>, _ dependency: T) {
withLock {
if TestRunTask.running, let name = keyPath.propertyName {
setDependencies.insert(name)
}
dependencyValues[keyPath: keyPath] = dependency
}
}
public subscript<Value>(dynamicMember keyPath: KeyPath<DependencyValues, Value>) -> Value {
withLock {
if TestRunTask.running, let name = keyPath.propertyName {
accessedDependencies.insert(name)
}
return dependencyValues[keyPath: keyPath]
}
}
func apply(_ dependencies: ComponentDependencies) {
withLock {
self.dependencyValues = self.dependencyValues.merging(dependencies.dependencyValues)
}
}
func setValues(_ values: DependencyValues) {
withLock {
self.dependencyValues = values
}
}
func reset() {
withLock {
accessedDependencies = []
setDependencies = []
dependencyValues = DependencyValues._current
}
}
}
@MainActor
public protocol DependencyContainer {
var dependencies: ComponentDependencies { get }
}
extension DependencyContainer {
public func dependency<T>(_ keyPath: WritableKeyPath<DependencyValues, T>, _ value: T) -> Self {
self.dependencies.setDependency(keyPath, value)
return self
}
func apply(_ dependencies: ComponentDependencies) -> Self {
self.dependencies.apply(dependencies)
return self
}
}
extension ViewModel: DependencyContainer { }
extension Test: DependencyContainer { }
extension ComponentSnapshot: DependencyContainer { }
extension ComponentRoute {
@discardableResult
public func dependency<T>(_ keyPath: WritableKeyPath<DependencyValues, T>, _ value: T) -> Self {
if let store {
store.dependencies.setDependency(keyPath, value)
} else {
self.dependencies.setDependency(keyPath, value)
}
return self
}
}
extension TestStep {
public func dependency<T>(_ keyPath: WritableKeyPath<DependencyValues, T>, _ dependency: T, file: StaticString = #filePath, line: UInt = #line) -> Self {
beforeRun { context in
context.model.dependencies.setDependency(keyPath, dependency)
}
}
}
extension Test {
public func dependency<T>(_ keyPath: WritableKeyPath<DependencyValues, T>, _ dependency: T, file: StaticString = #filePath, line: UInt = #line) -> Self {
let test = self
test.dependencies.setDependency(keyPath, dependency)
return test
}
}
| yonaskolb/SwiftComponent | 16 | Where architecture meets tooling | Swift | yonaskolb | Yonas Kolb | |
Sources/SwiftComponent/ComponentEnvironment.swift | Swift | import Foundation
public protocol ComponentEnvironment {
associatedtype Parent
var parent: Parent { get }
static var preview: Self { get }
/// provide a copy of the environment. If this is a class it must be a new instance. This is used for snapshots and test branch resets
func copy() -> Self
}
public struct EmptyEnvironment: ComponentEnvironment {
public var parent: Void = ()
public static var preview: EmptyEnvironment { .init() }
public func copy() -> EmptyEnvironment { .init() }
}
| yonaskolb/SwiftComponent | 16 | Where architecture meets tooling | Swift | yonaskolb | Yonas Kolb | |
Sources/SwiftComponent/ComponentGraph.swift | Swift | import Foundation
@MainActor
class ComponentGraph {
var sendViewBodyEvents = false
private var storesByModelType: [String: [WeakRef]] = [:]
private var viewModelsByPath: [ComponentPath: WeakRef] = [:]
private var routes: [ComponentPath: Any] = [:]
let id = UUID()
init() {
}
func add<Model: ComponentModel>(_ model: ViewModel<Model>) {
viewModelsByPath[model.store.path] = WeakRef(model)
storesByModelType[Model.name, default: []].append(.init(model.store))
}
func remove<Model: ComponentModel>(_ model: ViewModel<Model>) {
remove(model.store)
}
func remove<Model: ComponentModel>(_ store: ComponentStore<Model>) {
viewModelsByPath[store.path] = nil
routes[store.path] = nil
storesByModelType[Model.name]?.removeAll { ($0.value as? ComponentStore<Model>)?.id == store.id }
}
func getScopedModel<Model: ComponentModel, Child: ComponentModel>(model: ViewModel<Model>, child: Child.Type) -> ViewModel<Child>? {
getModel(model.path.appending(child))
}
func getModel<Model: ComponentModel>(_ path: ComponentPath) -> ViewModel<Model>? {
viewModelsByPath[path]?.value as? ViewModel<Model>
}
func getStores<Model: ComponentModel>(for model: Model.Type) -> [ComponentStore<Model>] {
storesByModelType[Model.name]?.compactMap { $0.value as? ComponentStore<Model> } ?? []
}
func addRoute<Model: ComponentModel>(store: ComponentStore<Model>, route: Model.Route) {
routes[store.path] = route
}
func removeRoute<Model: ComponentModel>(store: ComponentStore<Model>) {
routes[store.path] = nil
}
func getRoute<Model: ComponentModel>(store: ComponentStore<Model>) -> Model.Route? {
routes[store.path] as? Model.Route
}
func clearRoutes() {
routes.removeAll()
}
}
final class WeakRef {
weak var value: AnyObject?
init(_ value: AnyObject) {
self.value = value
}
}
| yonaskolb/SwiftComponent | 16 | Where architecture meets tooling | Swift | yonaskolb | Yonas Kolb | |
Sources/SwiftComponent/ComponentModel.swift | Swift | import Foundation
import SwiftUI
import Combine
@MainActor
public protocol ComponentModel<State, Action>: DependencyContainer {
associatedtype State = Void
associatedtype Action = Never
associatedtype Input = Never
associatedtype Output = Never
associatedtype Route = Never
associatedtype Task: ModelTask = Never
associatedtype Environment: ComponentEnvironment = EmptyEnvironment
associatedtype Connections = Void
@MainActor func appear() async
@MainActor func firstAppear() async
@MainActor func disappear() async
@MainActor func binding(keyPath: PartialKeyPath<State>) async
@MainActor func handle(action: Action) async
@MainActor func handle(input: Input) async
var _$connections: Connections { get }
func handle(event: Event)
@discardableResult nonisolated func connect(route: Route) -> RouteConnection
nonisolated init(context: Context)
var _$context: Context { get }
typealias Context = ModelContext<Self>
typealias Connection<Model: ComponentModel> = ModelConnection<Self, Model>
typealias Scope<Model: ComponentModel> = ComponentConnection<Self, Model>
}
public protocol ModelTask {
var taskName: String { get }
}
extension Never: ModelTask {
public var taskName: String { "" }
}
extension RawRepresentable where RawValue == String {
public var taskName: String { rawValue }
}
extension ComponentModel {
public var state: Context { _$context }
var connections: Connections { _$connections }
nonisolated static var name: String {
String(describing: Self.self)
}
nonisolated public static var baseName: String {
var name = self.name
let suffixes: [String] = [
"Component",
"Model",
"Feature",
]
for suffix in suffixes {
if name.hasSuffix(suffix) && name.count > suffix.count {
name = String(name.dropLast(suffix.count))
}
}
return name
}
}
public extension ComponentModel where Connections == Void {
var connections: Connections { () }
}
public extension ComponentModel where Action == Void {
func handle(action: Void) async {}
}
public extension ComponentModel where Input == Void {
func handle(input: Void) async {}
}
public extension ComponentModel where Route == Never {
nonisolated func connect(route: Route) -> RouteConnection { RouteConnection() }
}
// default handlers
public extension ComponentModel {
@MainActor func binding(keyPath: PartialKeyPath<State>) async { }
@MainActor func appear() async { }
@MainActor func firstAppear() async { }
@MainActor func disappear() async { }
@MainActor func handle(event: Event) { }
}
// functions for model to call
extension ComponentModel {
@MainActor var store: ComponentStore<Self>! { _$context.store }
@MainActor public var environment: Environment { store.environment }
@MainActor public var dependencies: ComponentDependencies { store.dependencies }
@MainActor
public func mutate<Value>(_ keyPath: WritableKeyPath<State, Value>, _ value: Value, animation: Animation? = nil, file: StaticString = #filePath, line: UInt = #line) {
store.mutate(keyPath, value: value, animation: animation, source: .capture(file: file, line: line))
}
@MainActor
public func output(_ event: Output, file: StaticString = #filePath, line: UInt = #line) {
store.output(event, source: .capture(file: file, line: line))
}
@MainActor
public func outputAsync(_ event: Output, file: StaticString = #filePath, line: UInt = #line) async {
await store.output(event, source: .capture(file: file, line: line))
}
@discardableResult
@MainActor
/// - Parameters:
/// - taskID: a unique id for this task. Tasks of the same id can be cancelled
/// - cancellable: cancel previous ongoing tasks of the same taskID
public func task<R>(_ taskID: Task, cancellable: Bool = false, file: StaticString = #filePath, line: UInt = #line, _ task: @escaping () async -> R) async -> R {
await store.task(taskID.taskName, cancellable: cancellable, source: .capture(file: file, line: line), task)
}
/// - Parameters:
/// - taskID: a unique id for this task. Tasks of the same id can be cancelled
/// - cancellable: cancel previous ongoing tasks of the same taskID
/// - catchError: This may throw a cancellation error
@MainActor
public func task<R>(_ taskID: Task, cancellable: Bool = false, file: StaticString = #filePath, line: UInt = #line, _ task: @escaping () async throws -> R, catch catchError: (Error) -> Void) async {
await store.task(taskID.taskName, cancellable: cancellable, source: .capture(file: file, line: line), task, catch: catchError)
}
/// - Parameters:
/// - taskID: a unique id for this task. Tasks of the same id can be cancelled
/// - cancellable: cancel previous ongoing tasks of the same taskID
@discardableResult
@MainActor
public func task<R>(_ taskID: Task, cancellable: Bool = false, file: StaticString = #filePath, line: UInt = #line, _ task: @escaping () async throws -> R) async throws -> R {
try await store.task(taskID.taskName, cancellable: cancellable, source: .capture(file: file, line: line)) {
try await task()
}
}
/// Adds a task that will be cancelled upon model deinit. In comparison to `task(_)` you don't have to wait for the result making it useful for never ending tasks like AsyncStreams,
/// and a task event will be sent as soon as the task is created
/// - Parameters:
/// - taskID: a unique id for this task. Tasks of the same id can be cancelled
/// - cancellable: cancel previous ongoing tasks of the same taskID
@MainActor
public func addTask(_ taskID: Task, cancellable: Bool = false, file: StaticString = #filePath, line: UInt = #line, _ task: @escaping () async -> Void) {
store.addTask(taskID.taskName, cancellable: cancellable, source: .capture(file: file, line: line), task)
}
@discardableResult
@MainActor
/// - Parameters:
/// - taskID: a unique id for this task. Tasks of the same id can be cancelled
/// - cancellable: cancel previous ongoing tasks of the same taskID
public func task<R>(_ taskID: String, cancellable: Bool = false, file: StaticString = #filePath, line: UInt = #line, _ task: @escaping () async -> R) async -> R {
await store.task(taskID, cancellable: cancellable, source: .capture(file: file, line: line), task)
}
/// - Parameters:
/// - taskID: a unique id for this task. Tasks of the same id can be cancelled
/// - cancellable: cancel previous ongoing tasks of the same taskID
/// - catchError: This may throw a cancellation error
@MainActor
public func task<R>(_ taskID: String, cancellable: Bool = false, file: StaticString = #filePath, line: UInt = #line, _ task: @escaping () async throws -> R, catch catchError: (Error) -> Void) async {
await store.task(taskID, cancellable: cancellable, source: .capture(file: file, line: line), task, catch: catchError)
}
/// - Parameters:
/// - taskID: a unique id for this task. Tasks of the same id can be cancelled
/// - cancellable: cancel previous ongoing tasks of the same taskID
@discardableResult
@MainActor
public func task<R>(_ taskID: String, cancellable: Bool = false, file: StaticString = #filePath, line: UInt = #line, _ task: @escaping () async throws -> R) async throws -> R {
try await store.task(taskID, cancellable: cancellable, source: .capture(file: file, line: line)) {
try await task()
}
}
/// Adds a task that will be cancelled upon model deinit. In comparison to `task(_)` you don't have to wait for the result making it useful for never ending tasks like AsyncStreams
/// and a task event will be sent as soon as the task is created
/// - Parameters:
/// - taskID: a unique id for this task. Tasks of the same id can be cancelled
/// - cancellable: cancel previous ongoing tasks of the same taskID
@MainActor
public func addTask(_ taskID: String, cancellable: Bool = false, file: StaticString = #filePath, line: UInt = #line, _ task: @escaping () async -> Void) {
store.addTask(taskID, cancellable: cancellable, source: .capture(file: file, line: line), task)
}
@MainActor
public func cancelTask(_ taskID: Task) {
store.cancelTask(cancelID: taskID.taskName)
}
@MainActor
public func cancelTask(_ taskID: String) {
store.cancelTask(cancelID: taskID)
}
@MainActor
public func dismissRoute(file: StaticString = #filePath, line: UInt = #line) {
store.dismissRoute(source: .capture(file: file, line: line))
}
/// dismisses the last view that rendered a body with this model
@MainActor
public func dismiss() {
store.presentationMode?.wrappedValue.dismiss()
}
@MainActor
public func updateView() {
store.stateChanged.send(_$context.state)
}
@MainActor
public func statePublisher() -> AnyPublisher<State, Never> {
store.stateChanged
.eraseToAnyPublisher()
}
// removes duplicates from equatable values, so only changes are published
@MainActor
public func statePublisher<Value: Equatable>(_ keypath: KeyPath<State, Value>) -> AnyPublisher<Value, Never> {
statePublisher()
.map { $0[keyPath: keypath] }
.removeDuplicates()
.eraseToAnyPublisher()
}
/// Calls a closure with any models that are currently children of this model, of a certain type. Not this closure could be called multiple times, if there are multiple models of this type
public func childModel<Model: ComponentModel>(_ modelType: Model.Type, _ model: (Model) async -> Void) async {
let graphStores = store.graph.getStores(for: Model.self)
for graphStore in graphStores {
if graphStore.path.contains(store.path), store.id != graphStore.id {
await model(graphStore.model)
}
}
}
/// Calls a closure with any models that are parents of this model, of a certain type. Not this closure could be called multiple times, if there are multiple models of this type
public func parentModel<Model: ComponentModel>(_ modelType: Model.Type, _ model: (Model) async -> Void) async {
let graphStores = store.graph.getStores(for: Model.self)
for graphStore in graphStores {
if store.path.contains(graphStore.path), store.id != graphStore.id {
await model(graphStore.model)
}
}
}
/// Calls a closure with any other models of a certain type. Not this closure could be called multiple times, if there are multiple models of this type
public func otherModel<Model: ComponentModel>(_ modelType: Model.Type, _ model: (Model) async -> Void) async {
let graphStores = store.graph.getStores(for: Model.self)
for graphStore in graphStores {
if store.id != graphStore.id {
await model(graphStore.model)
}
}
}
}
extension ComponentModel {
/// can be used from environment closures
public func action(_ action: Action) {
self.store.addTask {
await self.handle(action: action)
}
}
}
public struct ComponentConnection<From: ComponentModel, To: ComponentModel> {
private let scope: (ViewModel<From>) -> ViewModel<To>
public init(_ scope: @escaping (ViewModel<From>) -> ViewModel<To>) {
self.scope = scope
}
func convert(_ from: ViewModel<From>) -> ViewModel<To> {
scope(from)
}
}
| yonaskolb/SwiftComponent | 16 | Where architecture meets tooling | Swift | yonaskolb | Yonas Kolb | |
Sources/SwiftComponent/ComponentStore.swift | Swift | import Foundation
import SwiftUI
import Combine
import os
import Dependencies
@MainActor
class ComponentStore<Model: ComponentModel> {
enum StateStorage {
case root(Model.State)
case binding(StateBinding<Model.State>)
var state: Model.State {
get {
switch self {
case .root(let state): return state
case .binding(let binding): return binding.state
}
}
set {
switch self {
case .root:
self = .root(newValue)
case .binding(let binding):
binding.state = newValue
}
}
}
}
var children: [ConnectionID: WeakRef] = [:]
private var stateStorage: StateStorage
var path: ComponentPath
let graph: ComponentGraph
var dependencies: ComponentDependencies
var componentName: String { Model.baseName }
private var eventsInProgress = 0
var previewTaskDelay: TimeInterval = 0
private(set) var tasksByID: [String: CancellableTask] = [:]
var cancelledTasks: Set<String> = []
private var tasks: [UUID: CancellableTask] = [:]
private var appearanceTask: CancellableTask?
let stateChanged = PassthroughSubject<Model.State, Never>()
let routeChanged = PassthroughSubject<Model.Route?, Never>()
let environmentChanged = PassthroughSubject<Model.Environment, Never>()
var environment: Model.Environment {
didSet {
environmentChanged.send(environment)
}
}
let logger: Logger
var logEvents: Set<EventSimpleType> = []
var logChildEvents: Bool = true
var modelCancellables: Set<AnyCancellable> = []
let _$observationRegistrar = PerceptionRegistrar(
isPerceptionCheckingEnabled: _isStorePerceptionCheckingEnabled
)
var state: Model.State {
get {
_$observationRegistrar.access(self, keyPath: \.state)
return stateStorage.state
}
set {
guard !areMaybeEqual(stateStorage.state, newValue) else { return }
if let old = stateStorage.state as? any ObservableState,
let new = newValue as? any ObservableState,
old._$id == new._$id {
stateStorage.state = newValue
} else {
self._$observationRegistrar.withMutation(of: self, keyPath: \.state) {
stateStorage.state = newValue
}
}
stateChanged.send(newValue)
}
}
let id = UUID()
var route: Model.Route? {
didSet {
routeChanged.send(route)
if let route = route {
graph.addRoute(store: self, route: route)
} else {
graph.removeRoute(store: self)
}
}
}
var modelContext: ModelContext<Model>!
var model: Model!
var cancellables: Set<AnyCancellable> = []
private var mutations: [Mutation] = []
var sendGlobalEvents = true
var presentationMode: Binding<PresentationMode>?
private var lastSource: Source? // used to get at the original source of a mutation, due to no source info on dynamic member lookup
public var events = PassthroughSubject<Event, Never>()
private var subscriptions: Set<AnyCancellable> = []
var stateDump: String { dumpToString(state) }
var outputHandler: ((Model.Output, Source) async -> Void)? = nil
convenience init(state: StateStorage, path: ComponentPath?, graph: ComponentGraph, route: Model.Route? = nil) where Model.Environment == EmptyEnvironment {
self.init(state: state, path: path, graph: graph, environment: EmptyEnvironment(), route: route)
}
init(state: StateStorage, path: ComponentPath?, graph: ComponentGraph, environment: Model.Environment, route: Model.Route? = nil) {
self.stateStorage = state
self.graph = graph
self.environment = environment
let path = path?.appending(Model.self) ?? ComponentPath(Model.self)
self.path = path
self.dependencies = ComponentDependencies()
self.logger = Logger(subsystem: "SwiftComponent", category: path.string)
let modelContext = ModelContext(store: self)
self.model = Model(context: modelContext)
self.modelContext = modelContext
if let route = route {
model.connect(route: route)
self.route = route
}
events
.receive(on: DispatchQueue.main)
.sink { [weak self] event in
MainActor.assumeIsolated {
self?.model.handle(event: event)
}
}
.store(in: &subscriptions)
}
deinit {
modelCancellables = []
children = [:]
tasksByID.forEach { $0.value.cancel() }
tasksByID = [:]
tasks.values.forEach { $0.cancel() }
tasks = [:]
// TODO: update to isolated deinit in Swift 6.2
//cancelTasks()
}
func cancelTasks() {
tasksByID.forEach { $0.value.cancel() }
tasksByID = [:]
tasks.values.forEach { $0.cancel() }
tasks = [:]
}
@MainActor
private func startEvent() {
eventsInProgress += 1
}
@MainActor
fileprivate func sendEvent(type: EventType, start: Date, mutations: [Mutation], source: Source) {
eventsInProgress -= 1
if eventsInProgress < 0 {
assertionFailure("Parent count is \(eventsInProgress), but should only be 0 or more")
}
let event = Event(type: type, storeID: id, componentPath: path, start: start, end: Date(), mutations: mutations, depth: eventsInProgress, source: source)
events.send(event)
log(event)
guard sendGlobalEvents else { return }
EventStore.shared.send(event)
}
func log(_ event: Event) {
if logEvents.contains(event.type.type) {
let details = event.type.details
let eventString = "\(event.type.title.lowercased())\(details.isEmpty ? "" : ": ")\(details)"
// let relativePath = event.path.relative(to: self.path).string
// logger.info("\(relativePath)\(relativePath.isEmpty ? "" : ": ")\(eventString)")
print("Component \(event.path.string).\(eventString)")
}
}
@MainActor
func processAction(_ action: Model.Action, source: Source) {
lastSource = source
addTask { @MainActor in
await self.processAction(action, source: source)
}
}
@MainActor
func processAction(_ action: Model.Action, source: Source) async {
let eventStart = Date()
startEvent()
mutations = []
await model.handle(action: action)
sendEvent(type: .action(action), start: eventStart, mutations: mutations, source: source)
}
func processInput(_ input: Model.Input, source: Source) {
lastSource = source
addTask { @MainActor in
await self.processInput(input, source: source)
}
}
@MainActor
func processInput(_ input: Model.Input, source: Source) async {
let eventStart = Date()
startEvent()
mutations = []
await model.handle(input: input)
sendEvent(type: .input(input), start: eventStart, mutations: mutations, source: source)
}
func onOutput(_ handle: @MainActor @escaping (Model.Output, Event) -> Void) -> Self {
self.onEvent(includeGrandchildren: false) { event in
if case let .output(output) = event.type, let output = output as? Model.Output {
handle(output, event)
}
}
}
func onAction(_ handle: @MainActor @escaping (Model.Action, Event) -> Void) -> Self {
self.onEvent(includeGrandchildren: false) { event in
if case let .action(action) = event.type, let action = action as? Model.Action {
handle(action, event)
}
}
}
@discardableResult
func onEvent(includeGrandchildren: Bool, _ handle: @MainActor @escaping (Event) -> Void) -> Self {
self.events
.sink { [id] event in
Task { @MainActor in
if includeGrandchildren || event.storeID == id {
handle(event)
}
}
}
.store(in: &cancellables)
return self
}
}
// MARK: View Accessors
extension ComponentStore {
@MainActor
func binding<Value>(_ keyPath: WritableKeyPath<Model.State, Value>, file: StaticString = #filePath, line: UInt = #line) -> Binding<Value> {
Binding(
get: { self.state[keyPath: keyPath] },
set: { value in
guard self.setBindingValue(keyPath, value, file: file, line: line) else { return }
self.addTask { @MainActor in
await self.model.binding(keyPath: keyPath)
}
}
)
}
/// called from test step
@MainActor
func setBinding<Value>(_ keyPath: WritableKeyPath<Model.State, Value>, _ value: Value, file: StaticString = #filePath, line: UInt = #line) async {
guard self.setBindingValue(keyPath, value, file: file, line: line) else { return }
await self.model.binding(keyPath: keyPath)
}
@MainActor
private func setBindingValue<Value>(_ keyPath: WritableKeyPath<Model.State, Value>, _ value: Value, file: StaticString, line: UInt) -> Bool {
let start = Date()
let oldState = self.state
let oldValue = self.state[keyPath: keyPath]
// don't continue if change doesn't lead to state change
guard !areMaybeEqual(oldValue, value) else { return false }
self.startEvent()
self.state[keyPath: keyPath] = value
let mutation = Mutation(keyPath: keyPath, value: value, oldState: oldState)
self.sendEvent(type: .binding(mutation), start: start, mutations: [mutation], source: .capture(file: file, line: line))
return true
}
}
// MARK: ComponentView Accessors
extension ComponentStore {
@MainActor
func appear(first: Bool, file: StaticString = #filePath, line: UInt = #line) {
appearanceTask = addTask { @MainActor in
await self.appear(first: first, file: file, line: line)
}
}
@MainActor
func appear(first: Bool, file: StaticString = #filePath, line: UInt = #line) async {
let start = Date()
startEvent()
mutations = []
if first {
await model?.firstAppear()
}
await model?.appear()
sendEvent(type: .view(.appear(first: first)), start: start, mutations: self.mutations, source: .capture(file: file, line: line))
}
@MainActor
func disappear(file: StaticString = #filePath, line: UInt = #line) async {
let start = Date()
startEvent()
mutations = []
await model.disappear()
sendEvent(type: .view(.disappear), start: start, mutations: self.mutations, source: .capture(file: file, line: line))
appearanceTask?.cancel()
appearanceTask = nil
}
@MainActor
func disappear(file: StaticString = #filePath, line: UInt = #line) {
addTask { @MainActor in
await self.disappear()
}
}
@MainActor
func bodyAccessed(start: Date, file: StaticString = #filePath, line: UInt = #line) {
if graph.sendViewBodyEvents {
startEvent()
sendEvent(type: .view(.body), start: start, mutations: self.mutations, source: .capture(file: file, line: line))
}
}
@MainActor
func setPresentationMode(_ presentationMode: Binding<PresentationMode>) {
self.presentationMode = presentationMode
}
}
// MARK: Model Accessors
extension ComponentStore {
@MainActor
func mutate<Value>(_ keyPath: WritableKeyPath<Model.State, Value>, value: Value, animation: Animation? = nil, source: Source?) {
// we can't get the source in dynamic member lookup, so just use the original action or input
let source = source ?? lastSource ?? .capture()
let start = Date()
startEvent()
let oldState = stateStorage.state
let mutation = Mutation(keyPath: keyPath, value: value, oldState: oldState)
self.mutations.append(mutation)
if let animation {
withAnimation(animation) {
self.state[keyPath: keyPath] = value
}
} else {
self.state[keyPath: keyPath] = value
}
sendEvent(type: .mutation(mutation), start: start, mutations: [mutation], source: source)
//print(diff(oldState, self.state) ?? " No state changes")
}
@MainActor
func output(_ output: Model.Output, source: Source) {
addTask {
await self.output(output, source: source)
}
}
@MainActor
func output(_ output: Model.Output, source: Source) async {
startEvent()
await self.outputHandler?(output, source)
self.sendEvent(type: .output(output), start: Date(), mutations: [], source: source)
}
@MainActor
func task<R>(_ name: String, cancellable: Bool, source: Source, _ task: @MainActor @escaping () async throws -> R, catch catchError: (Error) -> Void) async {
do {
try await self.task(name, cancellable: cancellable, source: source, task)
} catch {
catchError(error)
}
}
@MainActor
// TODO: combine with bottom
func task<R>(_ name: String, cancellable: Bool, source: Source, _ task: @escaping () async -> R) async -> R {
let cancelID = name
if previewTaskDelay > 0 {
try? await Task.sleep(nanoseconds: UInt64(1_000_000_000.0 * previewTaskDelay))
}
let start = Date()
startEvent()
mutations = []
if cancellable {
cancelTask(cancelID: cancelID)
}
let task = Task { @MainActor in
await task()
}
addTask(task, cancelID: cancelID)
let value = await task.value
tasksByID[cancelID] = nil
let result = TaskResult(name: name, result: .success(value))
sendEvent(type: .task(result), start: start, mutations: mutations, source: source)
return value
}
@MainActor
@discardableResult
func task<R>(_ name: String, cancellable: Bool, source: Source, _ task: @escaping () async throws -> R) async throws -> R {
let cancelID = name
let start = Date()
startEvent()
mutations = []
if previewTaskDelay > 0 {
try? await Task.sleep(nanoseconds: UInt64(1_000_000_000.0 * previewTaskDelay))
}
do {
if cancellable {
cancelTask(cancelID: cancelID)
}
let task = Task { @MainActor in
try await task()
}
addTask(task, cancelID: cancelID)
let value = try await task.value
tasksByID[cancelID] = nil
sendEvent(type: .task(TaskResult(name: name, result: .success(value))), start: start, mutations: mutations, source: source)
return value
} catch {
if !(error is CancellationError) {
sendEvent(type: .task(TaskResult(name: name, result: .failure(error))), start: start, mutations: mutations, source: source)
}
throw error
}
}
@MainActor
func addTask(_ name: String, cancellable: Bool, source: Source, _ task: @escaping () async -> Void) {
let cancelID = name
let start = Date()
startEvent()
mutations = []
if cancellable {
cancelTask(cancelID: cancelID)
}
let task = Task { @MainActor in
await task()
tasksByID[cancelID] = nil
}
addTask(task, cancelID: cancelID)
let result = TaskResult(name: name, result: .success(()))
sendEvent(type: .task(result), start: start, mutations: mutations, source: source)
}
func cancelTask(cancelID: String) {
cancelledTasks.insert(cancelID)
if let previousTask = tasksByID[cancelID] {
previousTask.cancel()
tasksByID[cancelID] = nil
}
}
func addTask(_ task: CancellableTask, cancelID: String) {
cancelledTasks.remove(cancelID)
tasksByID[cancelID] = task
}
@discardableResult
func addTask(_ handle: @escaping () async -> Void) -> CancellableTask {
let taskID = UUID()
let task = Task { @MainActor in
await handle()
tasks[taskID] = nil
}
tasks[taskID] = task
return task
}
@MainActor
func present(_ route: Model.Route, source: Source) {
_ = model.connect(route: route)
self.route = route
startEvent()
sendEvent(type: .route(route), start: Date(), mutations: [], source: source)
}
func dismissRoute(source: Source) {
if route != nil {
DispatchQueue.main.async {
self.startEvent()
self.route = nil
self.sendEvent(type: .dismissRoute, start: Date(), mutations: [], source: source)
}
}
}
}
protocol CancellableTask {
func cancel()
}
extension Task: CancellableTask {}
public enum ScopedState<Parent, Child> {
case value(Child)
case binding(Binding<Child>)
case stateBinding(StateBinding<Child>, id: AnyHashable?)
case keyPath(WritableKeyPath<Parent, Child>)
case optionalKeyPath(WritableKeyPath<Parent, Child?>, fallback: Child)
var id: AnyHashable? {
switch self {
case .value:
nil
case .binding:
nil
case .stateBinding(_, let id):
id
case .keyPath(let keyPath):
keyPath
case .optionalKeyPath(let keyPath, _):
keyPath
}
}
}
// MARK: Scoping
extension ComponentStore {
private func keyPathBinding<Value>(_ keyPath: WritableKeyPath<Model.State, Value>) -> StateBinding<Value> {
StateBinding(
get: { self.stateStorage.state[keyPath: keyPath] },
set: { self.stateStorage.state[keyPath: keyPath] = $0 }
)
}
private func optionalBinding<ChildState>(state stateKeyPath: WritableKeyPath<Model.State, ChildState?>, value: ChildState) -> StateBinding<ChildState> {
let optionalBinding = keyPathBinding(stateKeyPath)
return StateBinding<ChildState> {
optionalBinding.state ?? value
} set: {
optionalBinding.state = $0
}
}
func optionalCaseBinding<ChildState, Enum: CasePathable>(state stateKeyPath: WritableKeyPath<Model.State, Enum?>, `case`: CaseKeyPath<Enum, ChildState>, value: ChildState) -> StateBinding<ChildState> {
StateBinding(
get: { self.stateStorage.state[keyPath: stateKeyPath]?[case: `case`] ?? value },
set: { self.stateStorage.state[keyPath: stateKeyPath]?[case: `case`] = $0 }
)
}
func caseScopedState<ChildState, Enum: CasePathable>(state statePath: WritableKeyPath<Model.State, Enum?>, case casePath: CaseKeyPath<Enum, ChildState>, value: ChildState) -> ScopedState<Model.State, ChildState> {
var hasher = Hasher()
hasher.combine(statePath)
hasher.combine(casePath)
return .stateBinding(optionalCaseBinding(state: statePath, case: casePath, value: value), id: hasher.finalize())
}
func syncEvents<Child: ComponentModel>(_ store: ComponentStore<Child>) -> ComponentStore<Child> {
store.events.sink { [weak self] event in
guard let self else { return }
self.events.send(event)
if self.logChildEvents {
log(event)
}
}
.store(in: &store.subscriptions)
return store
}
func scopedStore<Child: ComponentModel>(state: ScopedState<Model.State, Child.State>, environment: Child.Environment, route: Child.Route?) -> ComponentStore<Child> {
let stateStorage: ComponentStore<Child>.StateStorage
switch state {
case .value(let child):
stateStorage = .root(child)
case .binding(let binding):
stateStorage = .binding(.init(binding : binding))
case .keyPath(let keyPath):
stateStorage = .binding(keyPathBinding(keyPath))
case .optionalKeyPath(let keyPath, let fallback):
stateStorage = .binding(optionalBinding(state: keyPath, value: fallback))
case .stateBinding(let binding, _):
stateStorage = .binding(binding)
}
let store = ComponentStore<Child>(state: stateStorage, path: self.path, graph: graph, environment: environment, route: route)
store.dependencies.apply(self.dependencies)
if route == nil {
if let existingRoute = graph.getRoute(store: store) {
store.route = existingRoute
}
}
return store
}
func scope<Child: ComponentModel>(state: ScopedState<Model.State, Child.State>, route: Child.Route? = nil, output scopedOutput: OutputHandler<Model, Child>) -> ComponentStore<Child> where Model.Environment == Child.Environment {
scope(state: state, environment: self.environment, route: route, output: scopedOutput)
}
func scope<Child: ComponentModel>(state: ScopedState<Model.State, Child.State>, environment: Child.Environment, route: Child.Route? = nil, output scopedOutput: OutputHandler<Model, Child>) -> ComponentStore<Child> {
let childStore: ComponentStore<Child> = scopedStore(state: state, environment: environment, route: route)
childStore.outputHandler = { @MainActor [weak self] output, source in
guard let self else { return }
switch scopedOutput{
case .input(let toInput):
let input = toInput(output)
await self.processInput(input, source: source)
case .output(let toOutput):
let output = toOutput(output)
await self.output(output, source: source)
case .handle(let handle):
await handle((output: output, model: self.model))
case .ignore:
break
}
}
return syncEvents(childStore)
}
func scope<Child: ComponentModel>(state: ScopedState<Model.State, Child.State>, route: Child.Route? = nil) -> ComponentStore<Child> where Child.Output == Never, Model.Environment == Child.Environment {
syncEvents(scopedStore(state: state, environment: self.environment, route: route))
}
func scope<Child: ComponentModel>(state: ScopedState<Model.State, Child.State>, environment: Child.Environment, route: Child.Route? = nil) -> ComponentStore<Child> where Child.Output == Never {
syncEvents(scopedStore(state: state, environment: environment, route: route))
}
}
#if canImport(Perception)
private let _isStorePerceptionCheckingEnabled: Bool = {
if #available(iOS 17, macOS 14, tvOS 17, watchOS 10, *) {
return false
} else {
return true
}
}()
#endif
#if !os(visionOS)
extension ComponentStore: Perceptible {}
#endif
#if canImport(Observation)
@available(iOS 17, macOS 14, tvOS 17, watchOS 10, *)
extension ComponentStore: Observable {}
#endif
// Similar to SwiftUI.Binding but simpler and seems to fix issues with scope bindings and presentations
public struct StateBinding<State> {
let get: () -> State
let set: (State) -> Void
var state: State {
get { get() }
nonmutating set { set(newValue) }
}
}
extension StateBinding {
init(binding: Binding<State>) {
self.init(get: { binding.wrappedValue }, set: { binding.wrappedValue = $0 })
}
}
| yonaskolb/SwiftComponent | 16 | Where architecture meets tooling | Swift | yonaskolb | Yonas Kolb | |
Sources/SwiftComponent/ComponentView.swift | Swift | import Foundation
import SwiftUI
import SwiftGUI
import SwiftPreview
import Perception
@MainActor
public protocol ComponentView: View, DependencyContainer {
associatedtype Model: ComponentModel
associatedtype ComponentView: View
associatedtype DestinationView: View
associatedtype Style = Never
typealias Input = Model.Input
typealias Output = Model.Output
var model: ViewModel<Model> { get }
@ViewBuilder @MainActor var view: Self.ComponentView { get }
@ViewBuilder @MainActor func view(route: Model.Route) -> DestinationView
@MainActor func presentation(route: Model.Route) -> Presentation
}
public extension ComponentView {
func presentation(route: Model.Route) -> Presentation {
.sheet
}
@MainActor
var dependencies: ComponentDependencies { model.dependencies }
@MainActor
var environment: Model.Environment { model.environment }
}
public extension ComponentView where Model.Route == Never {
func view(route: Model.Route) -> EmptyView {
EmptyView()
}
}
struct ComponentViewContainer<Model: ComponentModel, Content: View>: View {
let model: ViewModel<Model>
let view: Content
@State var hasAppeared = false
@State var showDebug = false
@State var viewModes: [ComponentViewMode] = [.view]
@Environment(\.viewAppearanceTask) var viewAppearanceTask
@Environment(\.presentationMode) private var presentationMode
enum ComponentViewMode: String, Identifiable {
case view
case data
case history
case editor
case debug
var id: String { rawValue }
}
@MainActor
func getView() -> some View {
model.store.setPresentationMode(presentationMode)
#if DEBUG
let start = Date()
let view = self.view
model.bodyAccessed(start: start)
return view
#else
return self.view
#endif
}
var body: some View {
WithPerceptionTracking {
getView()
}
.task {
// even though we can manage an appearanceTask in the store, use task instead of onAppear here as there can be race conditions in SwiftUI related to FocusState which means ComponentStore can be deinitialised (as a parent recreated a ViewModel) before the task actually starts.
if viewAppearanceTask {
let first = !hasAppeared
hasAppeared = true
await model.appearAsync(first: first)
}
}
.onDisappear {
if viewAppearanceTask {
model.disappear()
}
}
#if DEBUG
.background {
Color.clear
.contentShape(Rectangle())
.onTapGesture(count: 2) {
showDebug = !showDebug
}
}
.onPreferenceChange(ComponentShowDebugPreference.self) { childDebug in
if childDebug {
// if a child component has already shown the debug due to the simultaneousGesture, don't show it again for a parent
showDebug = false
}
}
.preference(key: ComponentShowDebugPreference.self, value: showDebug)
.sheet(isPresented: $showDebug) {
if #available(iOS 16.0, macOS 13.0, *) {
debugSheet
.presentationDetents([.medium, .large])
} else {
debugSheet
}
}
#endif
}
var debugSheet: some View {
ComponentDebugSheet(model: model)
}
}
private struct ComponentShowDebugPreference: PreferenceKey {
static var defaultValue: Bool = false
static func reduce(value: inout Bool, nextValue: () -> Bool) {
value = value || nextValue()
}
}
extension ComponentView {
@MainActor
private var currentPresentation: Presentation? {
model.route.map { presentation(route: $0) }
}
@MainActor
private func presentationBinding(_ presentation: Presentation) -> Binding<Bool> {
Binding(
get: {
currentPresentation == presentation
},
set: { present in
if currentPresentation == presentation, !present, self.model.route != nil {
self.model.route = nil
}
}
)
}
@MainActor
@ViewBuilder
public var body: some View {
if Model.Route.self == Never.self {
ComponentViewContainer(model: model, view: view)
} else {
routePresentations()
}
}
func routePresentations() -> some View {
ComponentViewContainer(model: model, view: view)
.push(isPresented: presentationBinding(.push)) {
if let route = model.route {
view(route: route)
}
}
.sheet(isPresented: presentationBinding(.sheet)) {
if let route = model.route {
view(route: route)
}
}
#if os(iOS)
.fullScreenCover(isPresented: presentationBinding(.fullScreenCover)) {
if let route = model.route {
view(route: route)
}
}
#endif
}
public func onOutput(_ handle: @escaping (Model.Output) -> Void) -> Self {
_ = model.store.onOutput { output, event in
handle(output)
}
return self
}
}
extension View {
@ViewBuilder
func push<Content: View>(isPresented: Binding<Bool>, @ViewBuilder destination: () -> Content) -> some View {
if #available(iOS 16.0, macOS 13.0, *), !Presentation.useNavigationViewOniOS16 {
self.navigationDestination(isPresented: isPresented, destination: destination)
} else {
self.background {
NavigationLink(isActive: isPresented) {
destination()
} label: {
EmptyView()
}
}
}
}
}
| yonaskolb/SwiftComponent | 16 | Where architecture meets tooling | Swift | yonaskolb | Yonas Kolb | |
Sources/SwiftComponent/Event.swift | Swift | import Foundation
import Combine
import SwiftUI
// TODO: remove
public class EventStore {
public static let shared = EventStore()
public internal(set) var events: [Event] = []
public let eventPublisher = PassthroughSubject<Event, Never>()
#if DEBUG
public var storeEvents = true
#else
public var storeEvents = false
#endif
func componentEvents(for path: ComponentPath, includeChildren: Bool) -> [Event] {
events.filter { includeChildren ? $0.path.contains(path) : $0.path == path }
}
func send(_ event: Event) {
if storeEvents {
events.append(event)
}
eventPublisher.send(event)
}
func clear() {
events = []
}
}
public struct Event: Identifiable {
public var id = UUID()
public let storeID: UUID
public let start: Date
public let end: Date
public let type: EventType
public let depth: Int
public let source: Source
public var modelType: any ComponentModel.Type { path.path.last! }
public var componentName: String { modelType.baseName }
public var path: ComponentPath
public var mutations: [Mutation]
init(type: EventType, storeID: UUID, componentPath: ComponentPath, start: Date, end: Date, mutations: [Mutation], depth: Int, source: Source) {
self.type = type
self.storeID = storeID
self.start = start
self.end = end
self.mutations = mutations
self.path = componentPath
self.depth = depth
self.source = source
}
public var duration: TimeInterval {
end.timeIntervalSince1970 - start.timeIntervalSince1970
}
public var formattedDuration: String {
let seconds = duration
if seconds < 2 {
return Int(seconds*1000).formatted(.number) + " ms"
} else {
return (start ..< end).formatted(.components(style: .abbreviated))
}
}
}
extension Event: CustomStringConvertible {
public var description: String {
"\(path) \(type.title.lowercased()): \(type.details)"
}
}
public enum ModelEvent<Model: ComponentModel> {
case mutation(Mutation)
case binding(Mutation)
case action(Model.Action)
case input(Model.Input)
case output(Model.Output)
case view(ViewEvent)
case task(TaskResult)
case route(Model.Route)
case dismissRoute
}
extension Event {
public func asModel<Model: ComponentModel>(_ model: Model.Type) -> ModelEvent<Model>? {
guard modelType == model else { return nil }
switch type {
case .mutation(let mutation):
return .mutation(mutation)
case .binding(let mutation):
return .mutation(mutation)
case .action(let action):
return .action(action as! Model.Action)
case .input(let input):
return .input(input as! Model.Input)
case .output(let output):
return .output(output as! Model.Output)
case .view(let event):
return .view(event)
case .task(let result):
return .task(result)
case .route(let route):
return .route(route as! Model.Route)
case .dismissRoute:
return .dismissRoute
}
}
public func forModel<Model: ComponentModel>(_ model: Model.Type = Model.self, _ run: (ModelEvent<Model>) -> Void) {
guard let event = self.asModel(Model.self) else { return }
run(event)
}
}
public enum EventType {
case mutation(Mutation)
case binding(Mutation)
case action(Any)
case input(Any)
case output(Any)
case view(ViewEvent)
case task(TaskResult)
case route(Any)
case dismissRoute
var type: EventSimpleType {
switch self {
case .mutation: return .mutation
case .action: return .action
case .binding: return .binding
case .output: return .output
case .input: return .input
case .view: return .view
case .task: return .task
case .route: return .route
case .dismissRoute: return .dismissRoute
}
}
}
public enum ViewEvent {
case appear(first: Bool)
case disappear
case body
var name: String {
switch self {
case .appear:
return "appear"
case .disappear:
return "disappear"
case .body:
return "body"
}
}
}
extension EventType {
public var title: String { type.title }
var color: Color {
switch self {
case .task(let result):
switch result.result {
case .success: return .green
case .failure: return .red
}
default: return type.color
}
}
public var detailsTitle: String {
switch self {
case .action:
return "Action Name"
case .binding:
return "Property"
case .output:
return "Output"
case .input:
return "Input Name"
case .view:
return "View"
case .task:
return "Name"
case .mutation:
return "Property"
case .route:
return "Route"
case .dismissRoute:
return ""
}
}
public var valueTitle: String {
switch self {
case .action:
return "Action"
case .binding:
return "Value"
case .mutation:
return "Value"
case .output:
return "Output"
case .input:
return "Input"
case .view:
return ""
case .task(let result):
switch result.result {
case .success: return "Success"
case .failure: return "Failure"
}
case .route:
return "Destination"
case .dismissRoute:
return ""
}
}
public var details: String {
switch self {
case .action(let action):
return getEnumCase(action).name
case .binding(let mutation):
return mutation.property
case .mutation(let mutation):
return mutation.property
case .output(let event):
return getEnumCase(event).name
case .input(let event):
return getEnumCase(event).name
case .view(let event):
return event.name
case .task(let result):
return result.name
case .route(let route):
return getEnumCase(route).name
case .dismissRoute:
return ""
}
}
public var value: Any {
switch self {
case .action(let action):
return action
case .binding(let mutation):
return mutation.value
case .mutation(let mutation):
return mutation.value
case .output(let output):
return output
case .input(let input):
return input
case .view:
return ""
case .task(let result):
switch result.result {
case .success(let value): return value
case .failure(let error): return error
}
case .route(let route):
return route
case .dismissRoute:
return ""
}
}
}
public enum EventSimpleType: String, CaseIterable {
case view
case action
case binding
case mutation
case task
case input
case output
case route
case dismissRoute
static var set: Set<EventSimpleType> { Set(allCases) }
var title: String {
switch self {
case .action: return "Action"
case .binding: return "Binding"
case .output: return "Output"
case .input: return "Input"
case .view: return "View"
case .task: return "Task"
case .mutation: return "Mutation"
case .route: return "Route"
case .dismissRoute: return "Dismiss Route"
}
}
var color: Color {
switch self {
case .action:
return .purple
case .binding:
return .yellow
case .output:
return .cyan
case .input:
return .cyan
case .view:
return .blue
case .task:
return .green // changed to green or red in event
case .mutation:
return .yellow
case .route, .dismissRoute:
return .orange
}
}
}
public struct TaskResult {
public let name: String
public let result: Result<Any, Error>
public var successful: Bool {
switch result {
case .success:
return true
case .failure:
return false
}
}
}
// TODO: add before and after state
// TODO: then add a typed version for the typed event
public struct Mutation: Identifiable {
public let value: Any
public let oldState: Any
public let property: String
public var valueType: String { String(describing: type(of: value)) }
public let id = UUID()
public var newState: Any { getNewState() }
public var oldValue: Any { getOldValue() }
private var getOldValue: () -> Any
private var getNewState: () -> Any
init<State, T>(keyPath: WritableKeyPath<State, T>, value: T, oldState: State) {
self.oldState = oldState
self.value = value
self.property = keyPath.propertyName ?? "self"
self.getOldValue = { oldState[keyPath: keyPath] }
self.getNewState = {
var state = oldState
state[keyPath: keyPath] = value
return state
}
}
public var stateDiff: [String]? {
StateDump.diff(oldState, newState)
}
public var valueDiff: [String]? {
StateDump.diff(oldValue, value)
}
}
| yonaskolb/SwiftComponent | 16 | Where architecture meets tooling | Swift | yonaskolb | Yonas Kolb |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.