From 76448d70504b52676aec362c08bcd380a8494832 Mon Sep 17 00:00:00 2001 From: Markus Hatvan Date: Sun, 3 Jan 2021 16:28:55 +0100 Subject: [PATCH] feat: create word count metrics page - bootstrapped from default sapper-template - add wordCount.js to project and do minor adaptions - add calendar, progress bars for each article and words per day and doc target length inputs to index.svelte - added formatDate and mergeDays helper functions - implemented first working iteration for detail view, word count per file and calendar X day logic - words per day and document target length are set through cookies now - X elements on calendar are dynamically added and removed based on words per day now - added reasonable tags - blog posts are generated from markdown files now instead of standard Sapper posts.js - added various dependencies to package.json and updated to latest --- .editorconfig | 8 + .gitignore | 6 + .prettierrc.js | 8 + README.md | 140 +- logfile.json | 24 + package.json | 61 + postcss.config.js | 16 + rollup.config.js | 134 + scripts/setupTypeScript.js | 306 ++ src/ambient.d.ts | 39 + src/client.js | 5 + src/components/CustomFullCalendar.svelte | 106 + src/components/DayDetailView.svelte | 68 + src/components/Nav.svelte | 67 + src/components/WordCountDetailView.svelte | 80 + src/global.pcss | 39 + src/helpers.js | 20 + src/posts/cool-post-copy.md | 20 + src/posts/cool-post-test.md | 15 + src/posts/cool-post.md | 19 + src/routes/_error.svelte | 41 + src/routes/_layout.svelte | 21 + src/routes/blog/[slug].json.js | 28 + src/routes/blog/[slug].svelte | 64 + src/routes/blog/_posts.js | 20 + src/routes/blog/index.json.js | 16 + src/routes/blog/index.svelte | 32 + src/routes/index.svelte | 23 + src/server.js | 17 + src/service-worker.js | 86 + src/stores.js | 11 + src/template.html | 33 + static/favicon.png | Bin 0 -> 3127 bytes static/logo-192.png | Bin 0 -> 4760 bytes static/logo-512.png | Bin 0 -> 13928 bytes static/manifest.json | 20 + tailwind.config.js | 82 + wordCount.js | 80 + yarn.lock | 3677 +++++++++++++++++++++ 39 files changed, 5431 insertions(+), 1 deletion(-) create mode 100644 .editorconfig create mode 100644 .gitignore create mode 100644 .prettierrc.js create mode 100644 logfile.json create mode 100644 package.json create mode 100644 postcss.config.js create mode 100644 rollup.config.js create mode 100644 scripts/setupTypeScript.js create mode 100644 src/ambient.d.ts create mode 100644 src/client.js create mode 100644 src/components/CustomFullCalendar.svelte create mode 100644 src/components/DayDetailView.svelte create mode 100644 src/components/Nav.svelte create mode 100644 src/components/WordCountDetailView.svelte create mode 100644 src/global.pcss create mode 100644 src/helpers.js create mode 100644 src/posts/cool-post-copy.md create mode 100644 src/posts/cool-post-test.md create mode 100644 src/posts/cool-post.md create mode 100644 src/routes/_error.svelte create mode 100644 src/routes/_layout.svelte create mode 100644 src/routes/blog/[slug].json.js create mode 100644 src/routes/blog/[slug].svelte create mode 100644 src/routes/blog/_posts.js create mode 100644 src/routes/blog/index.json.js create mode 100644 src/routes/blog/index.svelte create mode 100644 src/routes/index.svelte create mode 100644 src/server.js create mode 100644 src/service-worker.js create mode 100644 src/stores.js create mode 100644 src/template.html create mode 100644 static/favicon.png create mode 100644 static/logo-192.png create mode 100644 static/logo-512.png create mode 100644 static/manifest.json create mode 100644 tailwind.config.js create mode 100644 wordCount.js create mode 100644 yarn.lock diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..78c6dde --- /dev/null +++ b/.editorconfig @@ -0,0 +1,8 @@ +root = true + +[*] +end_of_line = lf +insert_final_newline = true +charset = utf-8 +indent_style = space +indent_size = 2 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9321b0a --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +.DS_Store +/node_modules/ +/src/node_modules/@sapper/ +yarn-error.log +/__sapper__/ +/static/global.min.css diff --git a/.prettierrc.js b/.prettierrc.js new file mode 100644 index 0000000..ef0ce2c --- /dev/null +++ b/.prettierrc.js @@ -0,0 +1,8 @@ +module.exports = { + singleQuote: true, + trailingComma: "all", + svelteSortOrder: "scripts-markup-styles", + svelteStrictMode: true, + svelteBracketNewLine: true, + svelteAllowShorthand: true, +}; diff --git a/README.md b/README.md index 0cdbbf2..13958fe 100644 --- a/README.md +++ b/README.md @@ -1 +1,139 @@ -# Content_Ops \ No newline at end of file +# sapper-template + +The default template for setting up a [Sapper](https://github.com/sveltejs/sapper) project. Can use either Rollup or webpack as bundler. + +## Getting started + +### Using `degit` + +To create a new Sapper project based on Rollup locally, run + +```bash +npx degit "sveltejs/sapper-template#rollup" my-app +``` + +For a webpack-based project, instead run + +```bash +npx degit "sveltejs/sapper-template#webpack" my-app +``` + +[`degit`](https://github.com/Rich-Harris/degit) is a scaffolding tool that lets you create a directory from a branch in a repository. + +Replace `my-app` with the path where you wish to create the project. + +### Using GitHub templates + +Alternatively, you can create the new project as a GitHub repository using GitHub's template feature. + +Go to either [sapper-template-rollup](https://github.com/sveltejs/sapper-template-rollup) or [sapper-template-webpack](https://github.com/sveltejs/sapper-template-webpack) and click on "Use this template" to create a new project repository initialized by the template. + +### Running the project + +Once you have created the project, install dependencies and run the project in development mode: + +```bash +cd my-app +npm install # or yarn +npm run dev +``` + +This will start the development server on [localhost:3000](http://localhost:3000). Open it and click around. + +You now have a fully functional Sapper project! To get started developing, consult [sapper.svelte.dev](https://sapper.svelte.dev). + +### Using TypeScript + +By default, the template uses plain JavaScript. If you wish to use TypeScript instead, you need some changes to the project: + +- Add `typescript` as well as typings as dependences in `package.json` +- Configure the bundler to use [`svelte-preprocess`](https://github.com/sveltejs/svelte-preprocess) and transpile the TypeScript code. +- Add a `tsconfig.json` file +- Update the project code to TypeScript + +The template comes with a script that will perform these changes for you by running + +```bash +node scripts/setupTypeScript.js +``` + +`@sapper` dependencies are resolved through `src/node_modules/@sapper`, which is created during the build. You therefore need to run or build the project once to avoid warnings about missing dependencies. + +The script does not support webpack at the moment. + +## Directory structure + +Sapper expects to find two directories in the root of your project — `src` and `static`. + +### src + +The [src](src) directory contains the entry points for your app — `client.js`, `server.js` and (optionally) a `service-worker.js` — along with a `template.html` file and a `routes` directory. + +#### src/routes + +This is the heart of your Sapper app. There are two kinds of routes — _pages_, and _server routes_. + +**Pages** are Svelte components written in `.svelte` files. When a user first visits the application, they will be served a server-rendered version of the route in question, plus some JavaScript that 'hydrates' the page and initialises a client-side router. From that point forward, navigating to other pages is handled entirely on the client for a fast, app-like feel. (Sapper will preload and cache the code for these subsequent pages, so that navigation is instantaneous.) + +**Server routes** are modules written in `.js` files, that export functions corresponding to HTTP methods. Each function receives Express `request` and `response` objects as arguments, plus a `next` function. This is useful for creating a JSON API, for example. + +There are three simple rules for naming the files that define your routes: + +- A file called `src/routes/about.svelte` corresponds to the `/about` route. A file called `src/routes/blog/[slug].svelte` corresponds to the `/blog/:slug` route, in which case `params.slug` is available to the route +- The file `src/routes/index.svelte` (or `src/routes/index.js`) corresponds to the root of your app. `src/routes/about/index.svelte` is treated the same as `src/routes/about.svelte`. +- Files and directories with a leading underscore do _not_ create routes. This allows you to colocate helper modules and components with the routes that depend on them — for example you could have a file called `src/routes/_helpers/datetime.js` and it would _not_ create a `/_helpers/datetime` route. + +#### src/node_modules/images + +Images added to `src/node_modules/images` can be imported into your code using `import 'images/<filename>'`. They will be given a dynamically generated filename containing a hash, allowing for efficient caching and serving the images on a CDN. + +See [`index.svelte`](src/routes/index.svelte) for an example. + +#### src/node_modules/@sapper + +This directory is managed by Sapper and generated when building. It contains all the code you import from `@sapper` modules. + +### static + +The [static](static) directory contains static assets that should be served publicly. Files in this directory will be available directly under the root URL, e.g. an `image.jpg` will be available as `/image.jpg`. + +The default [service-worker.js](src/service-worker.js) will preload and cache these files, by retrieving a list of `files` from the generated manifest: + +```js +import { files } from "@sapper/service-worker"; +``` + +If you have static files you do not want to cache, you should exclude them from this list after importing it (and before passing it to `cache.addAll`). + +Static files are served using [sirv](https://github.com/lukeed/sirv). + +## Bundler configuration + +Sapper uses Rollup or webpack to provide code-splitting and dynamic imports, as well as compiling your Svelte components. With webpack, it also provides hot module reloading. As long as you don't do anything daft, you can edit the configuration files to add whatever plugins you'd like. + +## Production mode and deployment + +To start a production version of your app, run `npm run build && npm start`. This will disable live reloading, and activate the appropriate bundler plugins. + +You can deploy your application to any environment that supports Node 10 or above. As an example, to deploy to [Vercel Now](https://vercel.com) when using `sapper export`, run these commands: + +```bash +npm install -g vercel +vercel +``` + +If your app can't be exported to a static site, you can use the [now-sapper](https://github.com/thgh/now-sapper) builder. You can find instructions on how to do so in its [README](https://github.com/thgh/now-sapper#basic-usage). + +## Using external components + +When using Svelte components installed from npm, such as [@sveltejs/svelte-virtual-list](https://github.com/sveltejs/svelte-virtual-list), Svelte needs the original component source (rather than any precompiled JavaScript that ships with the component). This allows the component to be rendered server-side, and also keeps your client-side app smaller. + +Because of that, it's essential that the bundler doesn't treat the package as an _external dependency_. You can either modify the `external` option under `server` in [rollup.config.js](rollup.config.js) or the `externals` option in [webpack.config.js](webpack.config.js), or simply install the package to `devDependencies` rather than `dependencies`, which will cause it to get bundled (and therefore compiled) with your app: + +```bash +npm install -D @sveltejs/svelte-virtual-list +``` + +## Bugs and feedback + +Sapper is in early development, and may have the odd rough edge here and there. Please be vocal over on the [Sapper issue tracker](https://github.com/sveltejs/sapper/issues). diff --git a/logfile.json b/logfile.json new file mode 100644 index 0000000..14a8200 --- /dev/null +++ b/logfile.json @@ -0,0 +1,24 @@ +{ + "cool-post-copy": { + "2021-01-02T16:41:48.766Z": { + "diff": 279, + "currentWords": 279 + } + }, + "cool-post-test": { + "2021-01-02T16:41:48.768Z": { + "diff": 41, + "currentWords": 41 + }, + "2021-01-02T16:46:32.517Z": { + "diff": 2, + "currentWords": 43 + } + }, + "cool-post": { + "2021-01-02T16:41:48.773Z": { + "diff": 107, + "currentWords": 107 + } + } +} \ No newline at end of file diff --git a/package.json b/package.json new file mode 100644 index 0000000..38aae79 --- /dev/null +++ b/package.json @@ -0,0 +1,61 @@ +{ + "name": "content_ops", + "description": "", + "version": "1.0.0", + "private": "true", + "scripts": { + "dev": "run-p sapper:dev watch:css", + "sapper:dev": "sapper dev", + "watch:css": "NODE_ENV=development postcss src/global.pcss -o static/global.min.css -w", + "build": "run-s build:css sapper:build", + "sapper:build": "sapper build --legacy", + "build:css": "NODE_ENV=production postcss src/global.pcss -o static/global.min.css", + "export": "run-s build:css sapper:export", + "sapper:export": "sapper export --legacy", + "start": "node __sapper__/build", + "update-word-count": "node wordCount.js" + }, + "dependencies": { + "@rollup/plugin-json": "^4.1.0", + "compression": "^1.7.1", + "polka": "next", + "sirv": "^1.0.0" + }, + "devDependencies": { + "@babel/core": "^7.0.0", + "@babel/plugin-syntax-dynamic-import": "^7.0.0", + "@babel/plugin-transform-runtime": "^7.0.0", + "@babel/preset-env": "^7.0.0", + "@babel/runtime": "^7.0.0", + "@fullcalendar/core": "^5.5.0", + "@fullcalendar/daygrid": "^5.5.0", + "@fullcalendar/timegrid": "^5.5.0", + "@rollup/plugin-babel": "^5.0.0", + "@rollup/plugin-commonjs": "^17.0.0", + "@rollup/plugin-node-resolve": "^11.0.1", + "@rollup/plugin-replace": "^2.2.0", + "@rollup/plugin-url": "^6.0.0", + "@tailwindcss/forms": "^0.2.1", + "autoprefixer": "^10.1.0", + "cssnano": "^4.1.10", + "date-fns": "^2.16.1", + "front-matter": "^4.0.2", + "glob": "^7.1.6", + "js-cookie": "^2.2.1", + "marked": "^1.2.7", + "npm-run-all": "^4.1.5", + "postcss": "^8.2.2", + "postcss-cli": "^8.3.1", + "prettier": "^2.2.1", + "prettier-plugin-svelte": "^1.4.2", + "reading-time": "^1.2.1", + "rollup": "^2.3.4", + "rollup-plugin-svelte": "^7.0.0", + "rollup-plugin-terser": "^7.0.0", + "sapper": "^0.28.0", + "svelte": "^3.31.1", + "svelte-fullcalendar": "^1.1.0", + "svelte-previous": "^2.0.0", + "tailwindcss": "^2.0.2" + } +} diff --git a/postcss.config.js b/postcss.config.js new file mode 100644 index 0000000..0314865 --- /dev/null +++ b/postcss.config.js @@ -0,0 +1,16 @@ +const tailwindcss = require("tailwindcss"); + +const cssnano = require("cssnano")({ + preset: ["default", { discardComments: { removeAll: true } }], +}); + +const autoprefixer = require("autoprefixer")(); + +module.exports = { + plugins: [ + tailwindcss("./tailwind.config.js"), + autoprefixer, + // only needed if you want to purge + ...(process.env.NODE_ENV === "production" ? [cssnano] : []), + ], +}; diff --git a/rollup.config.js b/rollup.config.js new file mode 100644 index 0000000..3aae03e --- /dev/null +++ b/rollup.config.js @@ -0,0 +1,134 @@ +import path from "path"; +import resolve from "@rollup/plugin-node-resolve"; +import replace from "@rollup/plugin-replace"; +import commonjs from "@rollup/plugin-commonjs"; +import url from "@rollup/plugin-url"; +import svelte from "rollup-plugin-svelte"; +import babel from "@rollup/plugin-babel"; +import json from "@rollup/plugin-json"; +import { terser } from "rollup-plugin-terser"; +import config from "sapper/config/rollup.js"; +import pkg from "./package.json"; + +const mode = process.env.NODE_ENV; +const dev = mode === "development"; +const legacy = !!process.env.SAPPER_LEGACY_BUILD; + +const onwarn = (warning, onwarn) => + (warning.code === "MISSING_EXPORT" && /'preload'/.test(warning.message)) || + (warning.code === "CIRCULAR_DEPENDENCY" && + /[/\\]@sapper[/\\]/.test(warning.message)) || + onwarn(warning); + +export default { + client: { + input: config.client.input(), + output: config.client.output(), + plugins: [ + replace({ + "process.browser": true, + "process.env.NODE_ENV": JSON.stringify(mode), + }), + svelte({ + compilerOptions: { + dev, + hydratable: true, + }, + }), + url({ + sourceDir: path.resolve(__dirname, "src/node_modules/images"), + publicPath: "/client/", + }), + resolve({ + browser: true, + dedupe: ["svelte"], + }), + commonjs(), + + legacy && + babel({ + extensions: [".js", ".mjs", ".html", ".svelte"], + babelHelpers: "runtime", + exclude: ["node_modules/@babel/**"], + presets: [ + [ + "@babel/preset-env", + { + targets: "> 0.25%, not dead", + }, + ], + ], + plugins: [ + "@babel/plugin-syntax-dynamic-import", + [ + "@babel/plugin-transform-runtime", + { + useESModules: true, + }, + ], + ], + }), + + !dev && + terser({ + module: true, + }), + json(), + ], + + preserveEntrySignatures: false, + onwarn, + }, + + server: { + input: config.server.input(), + output: config.server.output(), + plugins: [ + replace({ + "process.browser": false, + "process.env.NODE_ENV": JSON.stringify(mode), + }), + svelte({ + compilerOptions: { + dev, + generate: "ssr", + hydratable: true, + }, + emitCss: false, + }), + url({ + sourceDir: path.resolve(__dirname, "src/node_modules/images"), + publicPath: "/client/", + emitFiles: false, // already emitted by client build + }), + resolve({ + dedupe: ["svelte"], + }), + commonjs(), + json(), + ], + external: Object.keys(pkg.dependencies).concat( + require("module").builtinModules + ), + + preserveEntrySignatures: "strict", + onwarn, + }, + + serviceworker: { + input: config.serviceworker.input(), + output: config.serviceworker.output(), + plugins: [ + resolve(), + replace({ + "process.browser": true, + "process.env.NODE_ENV": JSON.stringify(mode), + }), + commonjs(), + !dev && terser(), + ], + + preserveEntrySignatures: false, + onwarn, + }, +}; diff --git a/scripts/setupTypeScript.js b/scripts/setupTypeScript.js new file mode 100644 index 0000000..45fb596 --- /dev/null +++ b/scripts/setupTypeScript.js @@ -0,0 +1,306 @@ +/** + * Run this script to convert the project to TypeScript. This is only guaranteed to work + * on the unmodified default template; if you have done code changes you are likely need + * to touch up the generated project manually. + */ + +// @ts-check +const fs = require('fs'); +const path = require('path'); +const { argv } = require('process'); + +const projectRoot = argv[2] || path.join(__dirname, '..'); + +const isRollup = fs.existsSync(path.join(projectRoot, "rollup.config.js")); + +function warn(message) { + console.warn('Warning: ' + message); +} + +function replaceInFile(fileName, replacements) { + if (fs.existsSync(fileName)) { + let contents = fs.readFileSync(fileName, 'utf8'); + let hadUpdates = false; + + replacements.forEach(([from, to]) => { + const newContents = contents.replace(from, to); + + const isAlreadyApplied = typeof to !== 'string' || contents.includes(to); + + if (newContents !== contents) { + contents = newContents; + hadUpdates = true; + } else if (!isAlreadyApplied) { + warn(`Wanted to update "${from}" in ${fileName}, but did not find it.`); + } + }); + + if (hadUpdates) { + fs.writeFileSync(fileName, contents); + } else { + console.log(`${fileName} had already been updated.`); + } + } else { + warn(`Wanted to update ${fileName} but the file did not exist.`); + } +} + +function createFile(fileName, contents) { + if (fs.existsSync(fileName)) { + warn(`Wanted to create ${fileName}, but it already existed. Leaving existing file.`); + } else { + fs.writeFileSync(fileName, contents); + } +} + +function addDepsToPackageJson() { + const pkgJSONPath = path.join(projectRoot, 'package.json'); + const packageJSON = JSON.parse(fs.readFileSync(pkgJSONPath, 'utf8')); + packageJSON.devDependencies = Object.assign(packageJSON.devDependencies, { + ...(isRollup ? { '@rollup/plugin-typescript': '^6.0.0' } : { 'ts-loader': '^8.0.4' }), + '@tsconfig/svelte': '^1.0.10', + '@types/compression': '^1.7.0', + '@types/node': '^14.11.1', + '@types/polka': '^0.5.1', + 'svelte-check': '^1.0.46', + 'svelte-preprocess': '^4.3.0', + tslib: '^2.0.1', + typescript: '^4.0.3' + }); + + // Add script for checking + packageJSON.scripts = Object.assign(packageJSON.scripts, { + validate: 'svelte-check --ignore src/node_modules/@sapper' + }); + + // Write the package JSON + fs.writeFileSync(pkgJSONPath, JSON.stringify(packageJSON, null, ' ')); +} + +function changeJsExtensionToTs(dir) { + const elements = fs.readdirSync(dir, { withFileTypes: true }); + + for (let i = 0; i < elements.length; i++) { + if (elements[i].isDirectory()) { + changeJsExtensionToTs(path.join(dir, elements[i].name)); + } else if (elements[i].name.match(/^[^_]((?!json).)*js$/)) { + fs.renameSync(path.join(dir, elements[i].name), path.join(dir, elements[i].name).replace('.js', '.ts')); + } + } +} + +function updateSingleSvelteFile({ view, vars, contextModule }) { + replaceInFile(path.join(projectRoot, 'src', `${view}.svelte`), [ + [/(?:<script)(( .*?)*?)>/gm, (m, attrs) => `<script${attrs}${!attrs.includes('lang="ts"') ? ' lang="ts"' : ''}>`], + ...(vars ? vars.map(({ name, type }) => [`export let ${name};`, `export let ${name}: ${type};`]) : []), + ...(contextModule ? contextModule.map(({ js, ts }) => [js, ts]) : []) + ]); +} + +// Switch the *.svelte file to use TS +function updateSvelteFiles() { + [ + { + view: 'components/Nav', + vars: [{ name: 'segment', type: 'string' }] + }, + { + view: 'routes/_layout', + vars: [{ name: 'segment', type: 'string' }] + }, + { + view: 'routes/_error', + vars: [ + { name: 'status', type: 'number' }, + { name: 'error', type: 'Error' } + ] + }, + { + view: 'routes/blog/index', + vars: [{ name: 'posts', type: '{ slug: string; title: string, html: any }[]' }], + contextModule: [ + { + js: '.then(r => r.json())', + ts: '.then((r: { json: () => any; }) => r.json())' + }, + { + js: '.then(posts => {', + ts: '.then((posts: { slug: string; title: string, html: any }[]) => {' + } + ] + }, + { + view: 'routes/blog/[slug]', + vars: [{ name: 'post', type: '{ slug: string; title: string, html: any }' }] + } + ].forEach(updateSingleSvelteFile); +} + +function updateRollupConfig() { + // Edit rollup config + replaceInFile(path.join(projectRoot, 'rollup.config.js'), [ + // Edit imports + [ + /'rollup-plugin-terser';\n(?!import sveltePreprocess)/, + `'rollup-plugin-terser'; +import sveltePreprocess from 'svelte-preprocess'; +import typescript from '@rollup/plugin-typescript'; +` + ], + // Edit inputs + [ + /(?<!THIS_IS_UNDEFINED[^\n]*\n\s*)onwarn\(warning\);/, + `(warning.code === 'THIS_IS_UNDEFINED') ||\n\tonwarn(warning);` + ], + [/input: config.client.input\(\)(?!\.replace)/, `input: config.client.input().replace(/\\.js$/, '.ts')`], + [ + /input: config.server.input\(\)(?!\.replace)/, + `input: { server: config.server.input().server.replace(/\\.js$/, ".ts") }` + ], + [ + /input: config.serviceworker.input\(\)(?!\.replace)/, + `input: config.serviceworker.input().replace(/\\.js$/, '.ts')` + ], + // Add preprocess + [/compilerOptions/g, 'preprocess: sveltePreprocess(),\n\t\t\t\tcompilerOptions'], + // Add TypeScript + [/commonjs\(\)(?!,\n\s*typescript)/g, 'commonjs(),\n\t\t\ttypescript({ sourceMap: dev })'] + ]); +} + +function updateWebpackConfig() { + // Edit webpack config + replaceInFile(path.join(projectRoot, 'webpack.config.js'), [ + // Edit imports + [ + /require\('webpack-modules'\);\n(?!const sveltePreprocess)/, + `require('webpack-modules');\nconst sveltePreprocess = require('svelte-preprocess');\n` + ], + // Edit extensions + [ + /\['\.mjs', '\.js', '\.json', '\.svelte', '\.html'\]/, + `['.mjs', '.js', '.ts', '.json', '.svelte', '.html']` + ], + // Edit entries + [ + /entry: config\.client\.entry\(\)/, + `entry: { main: config.client.entry().main.replace(/\\.js$/, '.ts') }` + ], + [ + /entry: config\.server\.entry\(\)/, + `entry: { server: config.server.entry().server.replace(/\\.js$/, '.ts') }` + ], + [ + /entry: config\.serviceworker\.entry\(\)/, + `entry: { 'service-worker': config.serviceworker.entry()['service-worker'].replace(/\\.js$/, '.ts') }` + ], + // Add preprocess to the svelte config, this is tricky because there's no easy signifier. + // Instead we look for 'hydratable: true,' + [ + /hydratable: true(?!,\n\s*preprocess)/g, + 'hydratable: true,\n\t\t\t\t\t\t\tpreprocess: sveltePreprocess()' + ], + // Add TypeScript rules for client and server + [ + /module: {\n\s*rules: \[\n\s*(?!{\n\s*test: \/\\\.ts\$\/)/g, + `module: {\n\t\t\trules: [\n\t\t\t\t{\n\t\t\t\t\ttest: /\\.ts$/,\n\t\t\t\t\tloader: 'ts-loader'\n\t\t\t\t},\n\t\t\t\t` + ], + // Add TypeScript rules for serviceworker + [ + /output: config\.serviceworker\.output\(\),\n\s*(?!module)/, + `output: config.serviceworker.output(),\n\t\tmodule: {\n\t\t\trules: [\n\t\t\t\t{\n\t\t\t\t\ttest: /\\.ts$/,\n\t\t\t\t\tloader: 'ts-loader'\n\t\t\t\t}\n\t\t\t]\n\t\t},\n\t\t` + ], + // Edit outputs + [ + /output: config\.serviceworker\.output\(\),\n\s*(?!resolve)/, + `output: config.serviceworker.output(),\n\t\tresolve: { extensions: ['.mjs', '.js', '.ts', '.json'] },\n\t\t` + ] + ]); +} + +function updateServiceWorker() { + replaceInFile(path.join(projectRoot, 'src', 'service-worker.ts'), [ + [`shell.concat(files);`, `(shell as string[]).concat(files as string[]);`], + [`self.skipWaiting();`, `((self as any) as ServiceWorkerGlobalScope).skipWaiting();`], + [`self.clients.claim();`, `((self as any) as ServiceWorkerGlobalScope).clients.claim();`], + [`fetchAndCache(request)`, `fetchAndCache(request: Request)`], + [`self.addEventListener('activate', event =>`, `self.addEventListener('activate', (event: ExtendableEvent) =>`], + [`self.addEventListener('install', event =>`, `self.addEventListener('install', (event: ExtendableEvent) =>`], + [`addEventListener('fetch', event =>`, `addEventListener('fetch', (event: FetchEvent) =>`], + ]); +} + +function createTsConfig() { + const tsconfig = `{ + "extends": "@tsconfig/svelte/tsconfig.json", + "compilerOptions": { + "lib": ["DOM", "ES2017", "WebWorker"] + }, + "include": ["src/**/*", "src/node_modules/**/*"], + "exclude": ["node_modules/*", "__sapper__/*", "static/*"] + }`; + + createFile(path.join(projectRoot, 'tsconfig.json'), tsconfig); +} + +// Adds the extension recommendation +function configureVsCode() { + const dir = path.join(projectRoot, '.vscode'); + + if (!fs.existsSync(dir)) { + fs.mkdirSync(dir); + } + + createFile(path.join(projectRoot, '.vscode', 'extensions.json'), `{"recommendations": ["svelte.svelte-vscode"]}`); +} + +function deleteThisScript() { + fs.unlinkSync(path.join(__filename)); + + // Check for Mac's DS_store file, and if it's the only one left remove it + const remainingFiles = fs.readdirSync(path.join(__dirname)); + if (remainingFiles.length === 1 && remainingFiles[0] === '.DS_store') { + fs.unlinkSync(path.join(__dirname, '.DS_store')); + } + + // Check if the scripts folder is empty + if (fs.readdirSync(path.join(__dirname)).length === 0) { + // Remove the scripts folder + fs.rmdirSync(path.join(__dirname)); + } +} + +console.log(`Adding TypeScript with ${isRollup ? "Rollup" : "webpack" }...`); + +addDepsToPackageJson(); + +changeJsExtensionToTs(path.join(projectRoot, 'src')); + +updateSvelteFiles(); + +if (isRollup) { + updateRollupConfig(); +} else { + updateWebpackConfig(); +} + +updateServiceWorker(); + +createTsConfig(); + +configureVsCode(); + +// Delete this script, but not during testing +if (!argv[2]) { + deleteThisScript(); +} + +console.log('Converted to TypeScript.'); + +if (fs.existsSync(path.join(projectRoot, 'node_modules'))) { + console.log(` +Next: +1. run 'npm install' again to install TypeScript dependencies +2. run 'npm run build' for the @sapper imports in your project to work +`); +} diff --git a/src/ambient.d.ts b/src/ambient.d.ts new file mode 100644 index 0000000..ec71cae --- /dev/null +++ b/src/ambient.d.ts @@ -0,0 +1,39 @@ +/** + * These declarations tell TypeScript that we allow import of images, e.g. + * ``` + <script lang='ts'> + import successkid from 'images/successkid.jpg'; + </script> + + <img src="{successkid}"> + ``` + */ +declare module "*.gif" { + const value: string; + export = value; +} + +declare module "*.jpg" { + const value: string; + export = value; +} + +declare module "*.jpeg" { + const value: string; + export = value; +} + +declare module "*.png" { + const value: string; + export = value; +} + +declare module "*.svg" { + const value: string; + export = value; +} + +declare module "*.webp" { + const value: string; + export = value; +} diff --git a/src/client.js b/src/client.js new file mode 100644 index 0000000..cec9172 --- /dev/null +++ b/src/client.js @@ -0,0 +1,5 @@ +import * as sapper from '@sapper/app'; + +sapper.start({ + target: document.querySelector('#sapper') +}); \ No newline at end of file diff --git a/src/components/CustomFullCalendar.svelte b/src/components/CustomFullCalendar.svelte new file mode 100644 index 0000000..a81fecd --- /dev/null +++ b/src/components/CustomFullCalendar.svelte @@ -0,0 +1,106 @@ +<script> + import FullCalendar from 'svelte-fullcalendar'; + import { selectedDateStr, selectedDate } from '../stores'; + import logfile from '../../logfile.json'; + import { wordsPerDay } from '../stores'; + import { usePrevious } from 'svelte-previous'; + import { mergeDays } from '../helpers'; + + let loading = true; + + let options = { + dateClick: handleDateClick, + viewDidMount: () => { + loading = false; + }, + editable: false, + initialView: 'dayGridMonth', + plugins: [], + height: 'auto', + weekends: true, + eventDisplay: 'background', + }; + + let calendarComponentRef; + + const [currentWordsPerDay, previousWordsPerDay] = usePrevious($wordsPerDay); + + const markCalendarDaysWithX = async () => { + let daysWithDiff = []; + + Object.entries(logfile).map(([_filename, timestampKeys]) => { + let foundTimestamps = Object.keys(timestampKeys); + + for (let index = 0; index < foundTimestamps.length; index++) { + // Shorten timestamps to YYYY-MM-DD format so they can be merged into one later + let shortenedDay = foundTimestamps[index].slice(0, 10); + + daysWithDiff = [ + ...daysWithDiff, + { + [shortenedDay]: timestampKeys[foundTimestamps[index]].diff, + }, + ]; + } + }); + + const eventsWithX = Object.entries(mergeDays(daysWithDiff)) + // Remove dates where words per day goal was not met + .filter(([_date, totalWordCount]) => { + return totalWordCount >= $wordsPerDay; + }) + // Create correct data structure for fullcalendar + .map(([date, _totalWordCount]) => { + return { + title: 'X', + start: date, + allDay: true, + classNames: ['awesome-x'], + }; + }); + + options.events = eventsWithX; + options.plugins = [ + (await import('@fullcalendar/daygrid')).default, + (await import('@fullcalendar/interaction')).default, + ]; + options = { ...options }; + }; + + function handleDateClick(event) { + selectedDateStr.set(event.dateStr); + selectedDate.set(event.date.toISOString()); + } + + $: $currentWordsPerDay = $wordsPerDay; + + $: if ($currentWordsPerDay !== $previousWordsPerDay) { + markCalendarDaysWithX(); + } +</script> + +<div class="card min-cal-height"> + {#if loading}Loading word count calendar...{/if} + + <FullCalendar bind:this="{calendarComponentRef}" options="{options}" /> +</div> + +<style> + :global(.awesome-x > .fc-event-title) { + color: red; + position: absolute; + left: 50%; + transform: translate(-50%, -50%); + font-size: 45px !important; + margin: 0 !important; + top: 50%; + } + + :global(.fc .fc-bg-event) { + opacity: 1 !important; + } + + .min-cal-height { + min-height: 600px; + } +</style> diff --git a/src/components/DayDetailView.svelte b/src/components/DayDetailView.svelte new file mode 100644 index 0000000..426f1ee --- /dev/null +++ b/src/components/DayDetailView.svelte @@ -0,0 +1,68 @@ +<script> + import { selectedDateStr, selectedDate, wordsPerDay } from '../stores'; + import { formatDate } from '../helpers'; + import logfile from '../../logfile.json'; + import { usePrevious } from 'svelte-previous'; + + let filesWithNewWordCount = []; + + let totalWordsWrittenPerDay = 0; + + const [currentDateStr, previousDateStr] = usePrevious($selectedDateStr); + + $: $currentDateStr = $selectedDateStr; + + $: if ($previousDateStr && $currentDateStr !== $previousDateStr) { + filesWithNewWordCount = []; + totalWordsWrittenPerDay = 0; + } + + $: Object.entries(logfile).map(([filename, timestampKeys]) => { + let foundTimestamps = Object.keys(timestampKeys) + // We want to make sure to show the file diffs in chronological order + .sort() + .filter((value) => value.includes($selectedDateStr)); + + for (let i = 0; i < foundTimestamps.length; i++) { + filesWithNewWordCount = [ + ...filesWithNewWordCount, + { [filename]: timestampKeys[foundTimestamps[i]] }, + ]; + totalWordsWrittenPerDay += timestampKeys[foundTimestamps[i]].diff; + } + }); + + $: formattedDate = $selectedDate + ? formatDate($selectedDate) + : 'No date selected'; +</script> + +<div class="card"> + <h2>Detail view</h2> + + {#if $selectedDate} + <p>{formattedDate}</p> + + {#if filesWithNewWordCount.length > 0} + {#each Object.entries(filesWithNewWordCount) as [_filename, timestampKeys]} + <h3>{Object.keys(timestampKeys)}</h3> + <p + class="{timestampKeys[Object.keys(timestampKeys)].diff > 0 ? 'text-green-700' : 'text-red-700'}" + > + {timestampKeys[Object.keys(timestampKeys)].diff} + </p> + {/each} + <hr class="mb-4" /> + <p + class="{totalWordsWrittenPerDay >= $wordsPerDay ? 'text-green-700' : 'text-red-700'}" + > + {totalWordsWrittenPerDay} + / + {$wordsPerDay} + words written + </p> + {:else}No file changes found{/if} + {:else} + <p>No day selected</p> + {/if} +</div> diff --git a/src/components/Nav.svelte b/src/components/Nav.svelte new file mode 100644 index 0000000..895743f --- /dev/null +++ b/src/components/Nav.svelte @@ -0,0 +1,67 @@ +<script> + export let segment; +</script> + +<nav> + <ul> + <li> + <a + aria-current="{segment === undefined ? 'page' : undefined}" + href="." + >Dashboard</a> + </li> + <li> + <a + rel="prefetch" + aria-current="{segment === 'blog' ? 'page' : undefined}" + href="blog" + >Blog</a> + </li> + </ul> +</nav> + +<style> + nav { + border-bottom: 1px solid rgba(255, 62, 0, 0.1); + font-weight: 300; + padding: 0 1em; + } + + ul { + margin: 0; + padding: 0; + } + + /* clearfix */ + ul::after { + content: ''; + display: block; + clear: both; + } + + li { + display: block; + float: left; + } + + [aria-current] { + position: relative; + display: inline-block; + } + + [aria-current]::after { + position: absolute; + content: ''; + width: calc(100% - 1em); + height: 2px; + background-color: rgb(255, 62, 0); + display: block; + bottom: -1px; + } + + a { + text-decoration: none; + padding: 1em 0.5em; + display: block; + } +</style> diff --git a/src/components/WordCountDetailView.svelte b/src/components/WordCountDetailView.svelte new file mode 100644 index 0000000..829f0b1 --- /dev/null +++ b/src/components/WordCountDetailView.svelte @@ -0,0 +1,80 @@ +<script> + import logfile from '../../logfile.json'; + import { onMount } from 'svelte'; + import { documentTargetLength, wordsPerDay } from '../stores'; + import cookies from 'js-cookie'; + + let entryWithWords = []; + + onMount(() => { + Object.entries(logfile).map(([filename, timestampKeys]) => { + let newestTimestamp = Object.keys(timestampKeys)[ + Object.keys(timestampKeys).length - 1 + ]; + entryWithWords = [ + ...entryWithWords, + { [filename]: timestampKeys[newestTimestamp] }, + ]; + }); + }); + + const handleWordsPerDayChange = () => { + setTimeout(() => { + cookies.set('initialWordsPerDay', $wordsPerDay); + }, 1000); + }; + + const handledocumentTargetLengthChange = () => { + setTimeout(() => { + cookies.set('initialDocumentTargetLength', $wordsPerDay); + }, 1000); + }; + + var option = { + style: 'percent', + minimumFractionDigits: 0, + maximumFractionDigits: 0, + }; + var formatter = new Intl.NumberFormat('en-US', option); + + let formatPercentage = (value) => { + return value > 1 ? '100%' : formatter.format(value); + }; +</script> + +<div class="flex flex-wrap card"> + {#if entryWithWords.length > 0} + <div class="w-full py-2 md:w-1/2"> + <div class="mb-3"> + <label for="wordsPerDay" class="block">Words per day</label> + <input + type="number" + id="wordsPerDay" + bind:value="{$wordsPerDay}" + min="1" + on:change="{handleWordsPerDayChange}" + /> + </div> + + <label for="documentTargetLength" class="block">Document target length</label> + <input + type="number" + id="documentTargetLength" + bind:value="{$documentTargetLength}" + min="1" + on:change="{handledocumentTargetLengthChange}" + /> + </div> + + <div class="w-full py-2 md:w-1/2"> + {#each Object.entries(entryWithWords) as [_filename, timestampKeys]} + <div>{Object.keys(timestampKeys)}</div> + <progress + value="{timestampKeys[Object.keys(timestampKeys)].currentWords}" + max="{$documentTargetLength}" + ></progress> + {formatPercentage(timestampKeys[Object.keys(timestampKeys)].currentWords / $documentTargetLength)} + {/each} + </div> + {:else}No files found to display, did you run the word count script?{/if} +</div> diff --git a/src/global.pcss b/src/global.pcss new file mode 100644 index 0000000..4e9a3b6 --- /dev/null +++ b/src/global.pcss @@ -0,0 +1,39 @@ +@tailwind base; +@tailwind components; +@tailwind utilities; + +h1, +h2, +h3, +h4, +h5, +h6 { + @apply font-bold; +} + +h1 { + @apply text-5xl mb-6; +} + +h2 { + @apply text-3xl mb-4; +} + +h3, +h4, +h5, +h6 { + @apply text-xl mb-2; +} + +p { + @apply mb-4; +} + +.card { + @apply relative bg-white border rounded shadow-xl w-full p-3 h-full; +} + +[data-date]:hover { + background-color: rgba(128, 128, 128, 0.25); +} diff --git a/src/helpers.js b/src/helpers.js new file mode 100644 index 0000000..2735ec4 --- /dev/null +++ b/src/helpers.js @@ -0,0 +1,20 @@ +import { format, parseISO } from 'date-fns'; + +export const formatDate = (isoString, dateFormat = 'MMMM do, yyyy') => { + return format(parseISO(isoString), dateFormat); +}; + +export const mergeDays = (data) => { + const result = {}; + + data.forEach((basket) => { + for (let [key, value] of Object.entries(basket)) { + if (result[key]) { + result[key] += value; + } else { + result[key] = value; + } + } + }); + return result; +}; diff --git a/src/posts/cool-post-copy.md b/src/posts/cool-post-copy.md new file mode 100644 index 0000000..d70e626 --- /dev/null +++ b/src/posts/cool-post-copy.md @@ -0,0 +1,20 @@ +--- +title: 'Test' +slug: 'test' +--- + +Lorem ipsum dolor, sit amet consectetur adipisicing elit. Veniam reprehenderit numquam ea, optio nostrum repellat quidem expedita asperiores atque soluta non fugit neque assumenda, nihil distinctio deserunt explicabo unde culpa! +Magni dignissimos rerum distinctio dolore consequuntur hic architecto, inventore illum eaque error at expedita quis, rem neque a nihil. Asperiores, sequi. Nobis consequuntur officia esse suscipit, dolorem numquam aspernatur praesentium. +Vero accusamus, architecto provident possimus ipsum asperiores quidem culpa officia libero eum omnis dicta pariatur animi earum magni quibusdam, autem ab rem similique? Quidem nisi dolore suscipit. Quasi, dolore provident! + +Lorem ipsum dolor, sit amet consectetur adipisicing elit. Veniam reprehenderit numquam ea, optio nostrum repellat quidem expedita asperiores atque soluta non fugit neque assumenda, nihil distinctio deserunt explicabo unde culpa! +Magni dignissimos rerum distinctio dolore consequuntur hic architecto, inventore illum eaque error at expedita quis, rem neque a nihil. Asperiores, sequi. Nobis consequuntur officia esse suscipit, dolorem numquam aspernatur praesentium. +Vero accusamus, architecto provident possimus ipsum asperiores quidem culpa officia libero eum omnis dicta pariatur animi earum magni quibusdam, autem ab rem similique? Quidem nisi dolore suscipit. Quasi, dolore provident! + +Lorem ipsum dolor, sit amet consectetur adipisicing elit. Veniam reprehenderit numquam ea, optio nostrum repellat quidem expedita asperiores atque soluta non fugit neque assumenda, nihil distinctio deserunt explicabo unde culpa! +Magni dignissimos rerum distinctio dolore consequuntur hic architecto, inventore illum eaque error at expedita quis, rem neque a nihil. Asperiores, sequi. Nobis consequuntur officia esse suscipit, dolorem numquam aspernatur praesentium. +Vero accusamus, architecto provident possimus ipsum asperiores quidem culpa officia libero eum omnis dicta pariatur animi earum magni quibusdam, autem ab rem similique? Quidem nisi dolore suscipit. Quasi, dolore provident! + +lorem +lorem +lorem diff --git a/src/posts/cool-post-test.md b/src/posts/cool-post-test.md new file mode 100644 index 0000000..7e5691d --- /dev/null +++ b/src/posts/cool-post-test.md @@ -0,0 +1,15 @@ +--- +title: 'Test 2' +slug: 'test-2' +--- + +Lorem ipsum dolor, sit amet consectetur adipisicing elit. Veniam reprehenderit numquam ea, optio nostrum repellat quidem expedita asperiores atque soluta non fugit neque assumenda, nihil distinctio deserunt explicabo unde culpa! + +eee +qwdqwd +qwd +qw + +wgewegwge + +wgwe diff --git a/src/posts/cool-post.md b/src/posts/cool-post.md new file mode 100644 index 0000000..890b4dc --- /dev/null +++ b/src/posts/cool-post.md @@ -0,0 +1,19 @@ +--- +title: 'Test 3' +slug: 'test-3' +--- + +Lorem ipsum dolor, sit amet consectetur adipisicing elit. Veniam reprehenderit numquam ea, optio nostrum repellat quidem expedita asperiores atque soluta non fugit neque assumenda, nihil distinctio deserunt explicabo unde culpa! +Magni dignissimos rerum distinctio dolore consequuntur hic architecto, inventore illum eaque error at expedita quis, rem neque a nihil. Asperiores, sequi. Nobis consequuntur officia esse suscipit, dolorem numquam aspernatur praesentium. +Vero accusamus, architecto provident possimus ipsum asperiores quidem culpa officia libero eum omnis dicta pariatur animi earum magni quibusdam, autem ab rem similique? Quidem nisi dolore suscipit. Quasi, dolore provident! + +qeqeqeq +qeqeqeq +qeqeqeq +qeqeqeq +qeqeqeq +qeqeqeq +qeqeqeq +qeqeqeq +qeqeqeq +qeqeqeq diff --git a/src/routes/_error.svelte b/src/routes/_error.svelte new file mode 100644 index 0000000..c0c648b --- /dev/null +++ b/src/routes/_error.svelte @@ -0,0 +1,41 @@ +<script> + export let status; + export let error; + + const dev = process.env.NODE_ENV === 'development'; +</script> + +<svelte:head> + <title>{status} | Content Ops + + +

{status}

+ +

{error.message}

+ +{#if dev && error.stack} +
{error.stack}
+{/if} + + diff --git a/src/routes/_layout.svelte b/src/routes/_layout.svelte new file mode 100644 index 0000000..3d71480 --- /dev/null +++ b/src/routes/_layout.svelte @@ -0,0 +1,21 @@ + + +