Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions playground/nuxt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@ export default defineNuxtConfig({
],
colorMode: {
// storage: 'cookie',
// cookieAttrs: {
// path: '/',
// domain: 'localhost',
// secure: true,
// samesite: 'None',
// },
},
compatibilityDate: '2024-09-11',
})
5 changes: 5 additions & 0 deletions src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ const DEFAULTS: ModuleOptions = {
dataValue: '',
storageKey: 'nuxt-color-mode',
storage: 'localStorage',
cookieAttrs: {},
disableTransition: false,
}

Expand Down Expand Up @@ -178,6 +179,10 @@ export interface ModuleOptions {
* @default `localStorage`
*/
storage?: ColorModeStorage
/**
* Storage cookie's attributes
*/
cookieAttrs?: object
/**
* The script that will be injected into the head of the page
*/
Expand Down
14 changes: 12 additions & 2 deletions src/runtime/plugin.client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { computed, reactive, watch } from 'vue'

import type { ColorModeInstance } from './types'
import { defineNuxtPlugin, isVue2, isVue3, useRouter, useHead, useState } from '#imports'
import { globalName, storageKey, dataValue, disableTransition, storage } from '#color-mode-options'
import { globalName, storageKey, dataValue, disableTransition, storage, cookieAttrs } from '#color-mode-options'

// Initialise to empty object to avoid hard error when hydrating app in test mode
const helper = (window[globalName] || {}) as unknown as {
Expand Down Expand Up @@ -79,7 +79,17 @@ export default defineNuxtPlugin((nuxtApp) => {
function setPreferenceToStorage(storageType: typeof storage, preference: string) {
switch (storageType) {
case 'cookie':
window.document.cookie = storageKey + '=' + preference

if (Object.keys(cookieAttrs).length) {
let cookieString = storageKey + '=' + preference
for (const key in cookieAttrs) {
cookieString += `; ${key}=${cookieAttrs[key]}`
}
window.document.cookie = cookieString
}
else {
window.document.cookie = storageKey + '=' + preference
}
break
case 'sessionStorage':
window.sessionStorage?.setItem(storageKey, preference)
Expand Down
Loading