From 22fd3afd160d27c9ab43fcc8d1270db455403f8e Mon Sep 17 00:00:00 2001 From: Sean King Date: Thu, 30 Mar 2023 15:30:03 -0600 Subject: Change selenium server path to use require instead of hardcoding it --- test/e2e/nightwatch.conf.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'test') diff --git a/test/e2e/nightwatch.conf.js b/test/e2e/nightwatch.conf.js index 4041c698..fdd2fda2 100644 --- a/test/e2e/nightwatch.conf.js +++ b/test/e2e/nightwatch.conf.js @@ -9,7 +9,7 @@ module.exports = { selenium: { start_process: true, - server_path: 'node_modules/selenium-server/lib/runner/selenium-server-standalone-2.53.1.jar', + server_path: require('selenium-server').path, host: '127.0.0.1', port: 4444, cli_args: { -- cgit v1.2.3-70-g09d2 From 388a7ac1750e4e9284263dcd123451ebc4a1b577 Mon Sep 17 00:00:00 2001 From: Henry Jameson Date: Thu, 16 Nov 2023 21:28:02 +0200 Subject: remove a test --- test/unit/specs/modules/statuses.spec.js | 76 -------------------------------- 1 file changed, 76 deletions(-) (limited to 'test') diff --git a/test/unit/specs/modules/statuses.spec.js b/test/unit/specs/modules/statuses.spec.js index a8d0e5a3..0d83a9f8 100644 --- a/test/unit/specs/modules/statuses.spec.js +++ b/test/unit/specs/modules/statuses.spec.js @@ -77,24 +77,6 @@ describe('Statuses module', () => { expect(state.timelines.public.newStatusCount).to.equal(0) }) - it('removes statuses by tag on deletion', () => { - const state = defaultState() - const status = makeMockStatus({ id: '1' }) - const otherStatus = makeMockStatus({ id: '3' }) - status.uri = 'xxx' - const deletion = makeMockStatus({ id: '2', type: 'deletion' }) - deletion.text = 'Dolus deleted notice {{tag:gs.smuglo.li,2016-11-18:noticeId=1038007:objectType=note}}.' - deletion.uri = 'xxx' - - mutations.addNewStatuses(state, { statuses: [status, otherStatus], showImmediately: true, timeline: 'public' }) - mutations.addNewStatuses(state, { statuses: [deletion], showImmediately: true, timeline: 'public' }) - - expect(state.allStatuses).to.eql([otherStatus]) - expect(state.timelines.public.statuses).to.eql([otherStatus]) - expect(state.timelines.public.visibleStatuses).to.eql([otherStatus]) - expect(state.timelines.public.maxId).to.eql('3') - }) - it('does not update the maxId when the noIdUpdate flag is set', () => { const state = defaultState() const status = makeMockStatus({ id: '1' }) @@ -315,62 +297,4 @@ describe('Statuses module', () => { expect(state.timelines.user.userId).to.eql(123) }) }) - - describe('notifications', () => { - it('removes a notification when the notice gets removed', () => { - const user = { id: '1' } - const state = defaultState() - const status = makeMockStatus({ id: '1' }) - const otherStatus = makeMockStatus({ id: '3' }) - const mentionedStatus = makeMockStatus({ id: '2' }) - mentionedStatus.attentions = [user] - mentionedStatus.uri = 'xxx' - otherStatus.attentions = [user] - - const deletion = makeMockStatus({ id: '4', type: 'deletion' }) - deletion.text = 'Dolus deleted notice {{tag:gs.smuglo.li,2016-11-18:noticeId=1038007:objectType=note}}.' - deletion.uri = 'xxx' - const newNotificationSideEffects = () => {} - mutations.addNewStatuses(state, { statuses: [status, otherStatus], user }) - mutations.addNewNotifications( - state, - { - notifications: [{ - from_profile: { id: '2' }, - id: '998', - type: 'mention', - status: otherStatus, - action: otherStatus, - seen: false - }], - newNotificationSideEffects - }) - - expect(state.notifications.data.length).to.eql(1) - mutations.addNewNotifications( - state, - { - notifications: [{ - from_profile: { id: '2' }, - id: '999', - type: 'mention', - status: mentionedStatus, - action: mentionedStatus, - seen: false - }], - newNotificationSideEffects - }) - - mutations.addNewStatuses(state, { statuses: [mentionedStatus], user }) - expect(state.allStatuses.length).to.eql(3) - expect(state.notifications.data.length).to.eql(2) - expect(state.notifications.data[1].status).to.eql(mentionedStatus) - expect(state.notifications.data[1].action).to.eql(mentionedStatus) - expect(state.notifications.data[1].type).to.eql('mention') - - mutations.addNewStatuses(state, { statuses: [deletion], user }) - expect(state.allStatuses.length).to.eql(2) - expect(state.notifications.data.length).to.eql(1) - }) - }) }) -- cgit v1.2.3-70-g09d2 From cdc0959135a1bb9c3fd0c4750a9cb6ede5d189cb Mon Sep 17 00:00:00 2001 From: Henry Jameson Date: Sun, 19 Nov 2023 17:27:51 +0200 Subject: fix tests --- .../notification_utils/notification_utils.spec.js | 66 ++++++++++------------ 1 file changed, 31 insertions(+), 35 deletions(-) (limited to 'test') diff --git a/test/unit/specs/services/notification_utils/notification_utils.spec.js b/test/unit/specs/services/notification_utils/notification_utils.spec.js index 00628d83..ba7f7d75 100644 --- a/test/unit/specs/services/notification_utils/notification_utils.spec.js +++ b/test/unit/specs/services/notification_utils/notification_utils.spec.js @@ -5,26 +5,24 @@ describe('NotificationUtils', () => { it('should return sorted notifications with configured types', () => { const store = { state: { - statuses: { - notifications: { - data: [ - { - id: 1, - action: { id: '1' }, - type: 'like' - }, - { - id: 2, - action: { id: '2' }, - type: 'mention' - }, - { - id: 3, - action: { id: '3' }, - type: 'repeat' - } - ] - } + notifications: { + data: [ + { + id: 1, + action: { id: '1' }, + type: 'like' + }, + { + id: 2, + action: { id: '2' }, + type: 'mention' + }, + { + id: 3, + action: { id: '3' }, + type: 'repeat' + } + ] }, config: { notificationVisibility: { @@ -55,21 +53,19 @@ describe('NotificationUtils', () => { it('should return only notifications not marked as seen', () => { const store = { state: { - statuses: { - notifications: { - data: [ - { - action: { id: '1' }, - type: 'like', - seen: false - }, - { - action: { id: '2' }, - type: 'mention', - seen: true - } - ] - } + notifications: { + data: [ + { + action: { id: '1' }, + type: 'like', + seen: false + }, + { + action: { id: '2' }, + type: 'mention', + seen: true + } + ] }, config: { notificationVisibility: { -- cgit v1.2.3-70-g09d2 From c25170d7d9cb35d7209a63628905136e5fcab80a Mon Sep 17 00:00:00 2001 From: Henry Jameson Date: Wed, 22 Nov 2023 21:56:48 +0200 Subject: fix tests and make utils consistent in where they pull configuration from --- .../notification_utils/notification_utils.js | 41 +++++++++++++--------- .../notification_utils/notification_utils.spec.js | 12 ++++--- 2 files changed, 32 insertions(+), 21 deletions(-) (limited to 'test') diff --git a/src/services/notification_utils/notification_utils.js b/src/services/notification_utils/notification_utils.js index 959d28db..5ec98d9f 100644 --- a/src/services/notification_utils/notification_utils.js +++ b/src/services/notification_utils/notification_utils.js @@ -10,18 +10,21 @@ let cachedBadgeUrl = null export const notificationsFromStore = store => store.state.notifications.data export const visibleTypes = store => { - const rootState = store.rootState || store.state + // When called from within a module we need rootGetters to access wider scope + // however when called from a component (i.e. this.$store) we already have wider scope + const rootGetters = store.rootGetters || store.getters + const { notificationVisibility } = rootGetters.mergedConfig return ([ - rootState.config.notificationVisibility.likes && 'like', - rootState.config.notificationVisibility.mentions && 'mention', - rootState.config.notificationVisibility.repeats && 'repeat', - rootState.config.notificationVisibility.follows && 'follow', - rootState.config.notificationVisibility.followRequest && 'follow_request', - rootState.config.notificationVisibility.moves && 'move', - rootState.config.notificationVisibility.emojiReactions && 'pleroma:emoji_reaction', - rootState.config.notificationVisibility.reports && 'pleroma:report', - rootState.config.notificationVisibility.polls && 'poll' + notificationVisibility.likes && 'like', + notificationVisibility.mentions && 'mention', + notificationVisibility.repeats && 'repeat', + notificationVisibility.follows && 'follow', + notificationVisibility.followRequest && 'follow_request', + notificationVisibility.moves && 'move', + notificationVisibility.emojiReactions && 'pleroma:emoji_reaction', + notificationVisibility.reports && 'pleroma:report', + notificationVisibility.polls && 'poll' ].filter(_ => _)) } @@ -54,17 +57,19 @@ const sortById = (a, b) => { const isMutedNotification = (store, notification) => { if (!notification.status) return - return notification.status.muted || muteWordHits(notification.status, store.rootGetters.mergedConfig.muteWords).length > 0 + const rootGetters = store.rootGetters || store.getters + return notification.status.muted || muteWordHits(notification.status, rootGetters.mergedConfig.muteWords).length > 0 } export const maybeShowNotification = (store, notification) => { const rootState = store.rootState || store.state + const rootGetters = store.rootGetters || store.getters if (notification.seen) return if (!visibleTypes(store).includes(notification.type)) return if (notification.type === 'mention' && isMutedNotification(store, notification)) return - const notificationObject = prepareNotificationObject(notification, store.rootGetters.i18n) + const notificationObject = prepareNotificationObject(notification, rootGetters.i18n) showDesktopNotification(rootState, notificationObject) } @@ -78,7 +83,8 @@ export const filteredNotificationsFromStore = (store, types) => { } export const unseenNotificationsFromStore = store => { - const ignoreInactionableSeen = store.getters.mergedConfig.ignoreInactionableSeen + const rootGetters = store.rootGetters || store.getters + const ignoreInactionableSeen = rootGetters.mergedConfig.ignoreInactionableSeen return filteredNotificationsFromStore(store).filter(({ seen, type }) => { if (!ignoreInactionableSeen) return !seen @@ -149,15 +155,16 @@ export const prepareNotificationObject = (notification, i18n) => { } export const countExtraNotifications = (store) => { - const mergedConfig = store.getters.mergedConfig + const rootGetters = store.rootGetters || store.getters + const mergedConfig = rootGetters.mergedConfig if (!mergedConfig.showExtraNotifications) { return 0 } return [ - mergedConfig.showChatsInExtraNotifications ? store.getters.unreadChatCount : 0, - mergedConfig.showAnnouncementsInExtraNotifications ? store.getters.unreadAnnouncementCount : 0, - mergedConfig.showFollowRequestsInExtraNotifications ? store.getters.followRequestCount : 0 + mergedConfig.showChatsInExtraNotifications ? rootGetters.unreadChatCount : 0, + mergedConfig.showAnnouncementsInExtraNotifications ? rootGetters.unreadAnnouncementCount : 0, + mergedConfig.showFollowRequestsInExtraNotifications ? rootGetters.followRequestCount : 0 ].reduce((a, c) => a + c, 0) } diff --git a/test/unit/specs/services/notification_utils/notification_utils.spec.js b/test/unit/specs/services/notification_utils/notification_utils.spec.js index ba7f7d75..60db7380 100644 --- a/test/unit/specs/services/notification_utils/notification_utils.spec.js +++ b/test/unit/specs/services/notification_utils/notification_utils.spec.js @@ -23,8 +23,10 @@ describe('NotificationUtils', () => { type: 'repeat' } ] - }, - config: { + } + }, + getters: { + mergedConfig: { notificationVisibility: { likes: true, repeats: true, @@ -66,8 +68,10 @@ describe('NotificationUtils', () => { seen: true } ] - }, - config: { + } + }, + getters: { + mergedConfig: { notificationVisibility: { likes: true, repeats: true, -- cgit v1.2.3-70-g09d2 From 0729b529d7da2002f25039e1dad2732302009cf3 Mon Sep 17 00:00:00 2001 From: Henry Jameson Date: Tue, 23 Jan 2024 00:43:46 +0200 Subject: some more stuff, generating CSS selectors from rules --- src/components/button.style.js | 1 + src/components/icon.style.js | 3 +- src/components/panel.style.js | 1 + src/components/text.style.js | 4 +- src/components/underlay.style.js | 3 +- src/services/theme_data/pleromafe.t3.js | 26 +++++++++ src/services/theme_data/theme_data_3.service.js | 62 +++++++++++++++++----- .../specs/services/theme_data/theme_data3.spec.js | 26 +++++++++ 8 files changed, 109 insertions(+), 17 deletions(-) create mode 100644 src/services/theme_data/pleromafe.t3.js create mode 100644 test/unit/specs/services/theme_data/theme_data3.spec.js (limited to 'test') diff --git a/src/components/button.style.js b/src/components/button.style.js index 8f2e8f82..1c229f43 100644 --- a/src/components/button.style.js +++ b/src/components/button.style.js @@ -1,5 +1,6 @@ export default { name: 'Button', + selector: '.btn', states: { hover: ':hover', disabled: ':disabled', diff --git a/src/components/icon.style.js b/src/components/icon.style.js index 1e2781d6..732cf16f 100644 --- a/src/components/icon.style.js +++ b/src/components/icon.style.js @@ -1,3 +1,4 @@ export default { - name: 'Icon' + name: 'Icon', + selector: '.icon' } diff --git a/src/components/panel.style.js b/src/components/panel.style.js index 1666d923..d34d5434 100644 --- a/src/components/panel.style.js +++ b/src/components/panel.style.js @@ -1,5 +1,6 @@ export default { name: 'Panel', + selector: '.panel', validInnerComponents: [ 'Text', 'Icon', diff --git a/src/components/text.style.js b/src/components/text.style.js index f87268bb..2aa5e745 100644 --- a/src/components/text.style.js +++ b/src/components/text.style.js @@ -1,9 +1,7 @@ export default { name: 'Text', + selector: '', states: { faint: '.faint' - }, - variants: { - green: '/.greentext' } } diff --git a/src/components/underlay.style.js b/src/components/underlay.style.js index bae9fc0b..426df1d7 100644 --- a/src/components/underlay.style.js +++ b/src/components/underlay.style.js @@ -1,5 +1,6 @@ export default { - name: 'Panel', + name: 'Underlay', + selector: '.underlay', validInnerComponents: [ 'Panel' ] diff --git a/src/services/theme_data/pleromafe.t3.js b/src/services/theme_data/pleromafe.t3.js new file mode 100644 index 00000000..b44a395e --- /dev/null +++ b/src/services/theme_data/pleromafe.t3.js @@ -0,0 +1,26 @@ +export const sampleRules = [ + { + component: 'Underlay', + // variant: 'normal', + // state: 'normal' + directives: { + background: '#000', + opacity: 0.2 + } + }, + { + component: 'Panel', + directives: { + background: '#FFFFFF', + opacity: 0.9 + } + }, + { + component: 'Button', + directives: { + background: '#808080', + text: '#FFFFFF', + opacity: 0.5 + } + } +] diff --git a/src/services/theme_data/theme_data_3.service.js b/src/services/theme_data/theme_data_3.service.js index 3a6fd552..39a9998d 100644 --- a/src/services/theme_data/theme_data_3.service.js +++ b/src/services/theme_data/theme_data_3.service.js @@ -14,7 +14,7 @@ const components = { } // This gives you an array of arrays of all possible unique (i.e. order-insensitive) combinations -const getAllPossibleCombinations = (array) => { +export const getAllPossibleCombinations = (array) => { const combos = [array.map(x => [x])] for (let comboSize = 2; comboSize <= array.length; comboSize++) { const previous = combos[combos.length - 1] @@ -30,15 +30,52 @@ const getAllPossibleCombinations = (array) => { return combos.reduce((acc, x) => [...acc, ...x], []) } -export const init = () => { +export const ruleToSelector = (rule) => { + const component = components[rule.component] + const { states, variants, selector } = component + + const applicableStates = (rule.state.filter(x => x !== 'normal') || []).map(state => states[state]) + + const applicableVariantName = (rule.variant || 'normal') + let applicableVariant = '' + if (applicableVariantName !== 'normal') { + applicableVariant = variants[applicableVariantName] + } + + const selectors = [selector, applicableVariant, ...applicableStates] + .toSorted((a, b) => { + if (a.startsWith(':')) return 1 + else return -1 + }) + .join('') + + if (rule.parent) { + return ruleToSelector(rule.parent) + ' ' + selectors + } + return selectors +} + +export const init = (ruleset) => { const rootName = root.name const rules = [] + const rulesByComponent = {} + + const addRule = (rule) => { + rules.push(rule) + rulesByComponent[rule.component] = rulesByComponent[rule.component] || [] + rulesByComponent.push(rule) + } + + ruleset.forEach(rule => { + + }) const processInnerComponent = (component, parent) => { const { - validInnerComponents, + validInnerComponents = [], states: originalStates = {}, - variants: originalVariants = {} + variants: originalVariants = {}, + name } = component const states = { normal: '', ...originalStates } @@ -51,16 +88,17 @@ export const init = () => { }).reduce((acc, x) => [...acc, ...x], []) stateVariantCombination.forEach(combination => { - rules.push(({ - parent, - component: component.name, - state: combination.state, - variant: combination.variant - })) - - innerComponents.forEach(innerComponent => processInnerComponent(innerComponent, combination)) + // addRule(({ + // parent, + // component: component.name, + // state: combination.state, + // variant: combination.variant + // })) + + innerComponents.forEach(innerComponent => processInnerComponent(innerComponent, { parent, component: name, ...combination })) }) } processInnerComponent(components[rootName]) + return rules } diff --git a/test/unit/specs/services/theme_data/theme_data3.spec.js b/test/unit/specs/services/theme_data/theme_data3.spec.js new file mode 100644 index 00000000..e76200c0 --- /dev/null +++ b/test/unit/specs/services/theme_data/theme_data3.spec.js @@ -0,0 +1,26 @@ +// import { topoSort } from 'src/services/theme_data/theme_data.service.js' +import { + getAllPossibleCombinations, + init, + ruleToSelector +} from 'src/services/theme_data/theme_data_3.service.js' +import { + sampleRules +} from 'src/services/theme_data/pleromafe.t3.js' + +describe.only('Theme Data 3', () => { + describe('getAllPossibleCombinations', () => { + it('test simple case', () => { + const out = getAllPossibleCombinations([1, 2, 3]).map(x => x.sort((a, b) => a - b)) + expect(out).to.eql([[1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]) + }) + }) + + describe('init', () => { + it('test simple case', () => { + const out = init(sampleRules) + console.log(JSON.stringify(out, null, 2)) + out.forEach(r => console.log(ruleToSelector(r))) + }) + }) +}) -- cgit v1.2.3-70-g09d2 From 22b32f149d7753592fddcfb1cd2679b3fbac33d6 Mon Sep 17 00:00:00 2001 From: Henry Jameson Date: Tue, 23 Jan 2024 19:18:55 +0200 Subject: shit more or less works for the very basic stuff --- src/components/button.style.js | 4 +- src/components/panel.style.js | 3 +- src/components/panel_header.style.js | 9 ++ src/components/text.style.js | 2 +- src/components/underlay.style.js | 2 +- src/services/color_convert/color_convert.js | 1 + src/services/theme_data/pleromafe.t3.js | 10 +- src/services/theme_data/theme_data_3.service.js | 116 +++++++++++++++++++-- .../specs/services/theme_data/theme_data3.spec.js | 7 +- 9 files changed, 132 insertions(+), 22 deletions(-) create mode 100644 src/components/panel_header.style.js (limited to 'test') diff --git a/src/components/button.style.js b/src/components/button.style.js index 1c229f43..51f781e1 100644 --- a/src/components/button.style.js +++ b/src/components/button.style.js @@ -2,10 +2,10 @@ export default { name: 'Button', selector: '.btn', states: { - hover: ':hover', disabled: ':disabled', + toggled: '.toggled', pressed: ':active', - toggled: '.toggled' + hover: ':hover' }, variants: { danger: '.danger', diff --git a/src/components/panel.style.js b/src/components/panel.style.js index d34d5434..e3da4d1a 100644 --- a/src/components/panel.style.js +++ b/src/components/panel.style.js @@ -4,6 +4,7 @@ export default { validInnerComponents: [ 'Text', 'Icon', - 'Button' + 'Button', + 'PanelHeader' ] } diff --git a/src/components/panel_header.style.js b/src/components/panel_header.style.js new file mode 100644 index 00000000..aaa8bea9 --- /dev/null +++ b/src/components/panel_header.style.js @@ -0,0 +1,9 @@ +export default { + name: 'PanelHeader', + selector: '.panel-heading', + validInnerComponents: [ + 'Text', + 'Icon', + 'Button' + ] +} diff --git a/src/components/text.style.js b/src/components/text.style.js index 2aa5e745..050194cb 100644 --- a/src/components/text.style.js +++ b/src/components/text.style.js @@ -1,6 +1,6 @@ export default { name: 'Text', - selector: '', + selector: '/*text*/', states: { faint: '.faint' } diff --git a/src/components/underlay.style.js b/src/components/underlay.style.js index 426df1d7..be1ecc56 100644 --- a/src/components/underlay.style.js +++ b/src/components/underlay.style.js @@ -1,6 +1,6 @@ export default { name: 'Underlay', - selector: '.underlay', + selector: '#app', validInnerComponents: [ 'Panel' ] diff --git a/src/services/color_convert/color_convert.js b/src/services/color_convert/color_convert.js index 47d6344e..23e4ca61 100644 --- a/src/services/color_convert/color_convert.js +++ b/src/services/color_convert/color_convert.js @@ -188,6 +188,7 @@ export const rgba2css = function (rgba) { */ export const getTextColor = function (bg, text, preserve) { const contrast = getContrastRatio(bg, text) + console.log(contrast) if (contrast < 4.5) { const base = typeof text.a !== 'undefined' ? { a: text.a } : {} diff --git a/src/services/theme_data/pleromafe.t3.js b/src/services/theme_data/pleromafe.t3.js index b44a395e..b7b12573 100644 --- a/src/services/theme_data/pleromafe.t3.js +++ b/src/services/theme_data/pleromafe.t3.js @@ -4,7 +4,7 @@ export const sampleRules = [ // variant: 'normal', // state: 'normal' directives: { - background: '#000', + background: '#000000', opacity: 0.2 } }, @@ -15,11 +15,17 @@ export const sampleRules = [ opacity: 0.9 } }, + { + component: 'PanelHeader', + directives: { + background: '#000000', + opacity: 0.9 + } + }, { component: 'Button', directives: { background: '#808080', - text: '#FFFFFF', opacity: 0.5 } } diff --git a/src/services/theme_data/theme_data_3.service.js b/src/services/theme_data/theme_data_3.service.js index 39a9998d..d65d5352 100644 --- a/src/services/theme_data/theme_data_3.service.js +++ b/src/services/theme_data/theme_data_3.service.js @@ -1,5 +1,9 @@ +import { convert } from 'chromatism' +import { alphaBlend, getTextColor, rgba2css } from '../color_convert/color_convert.js' + import Underlay from 'src/components/underlay.style.js' import Panel from 'src/components/panel.style.js' +import PanelHeader from 'src/components/panel_header.style.js' import Button from 'src/components/button.style.js' import Text from 'src/components/text.style.js' import Icon from 'src/components/icon.style.js' @@ -8,6 +12,7 @@ const root = Underlay const components = { Underlay, Panel, + PanelHeader, Button, Text, Icon @@ -34,7 +39,7 @@ export const ruleToSelector = (rule) => { const component = components[rule.component] const { states, variants, selector } = component - const applicableStates = (rule.state.filter(x => x !== 'normal') || []).map(state => states[state]) + const applicableStates = ((rule.state || []).filter(x => x !== 'normal')).map(state => states[state]) const applicableVariantName = (rule.variant || 'normal') let applicableVariant = '' @@ -63,12 +68,37 @@ export const init = (ruleset) => { const addRule = (rule) => { rules.push(rule) rulesByComponent[rule.component] = rulesByComponent[rule.component] || [] - rulesByComponent.push(rule) + rulesByComponent[rule.component].push(rule) } - ruleset.forEach(rule => { + const findRules = (combination) => rule => { + if (combination.component !== rule.component) return false + if (Object.prototype.hasOwnProperty.call(rule, 'variant')) { + if (combination.variant !== rule.variant) return false + } else { + if (combination.variant !== 'normal') return false + } + + if (Object.prototype.hasOwnProperty.call(rule, 'state')) { + const ruleStatesSet = new Set(['normal', ...(rule.state || [])]) + return combination.state.every(state => ruleStatesSet.has(state)) + } else { + if (combination.state.length !== 1 || combination.state[0] !== 'normal') return false + return true + } + } - }) + const findLowerLevelRule = (parent, filter = () => true) => { + let lowerLevelComponent = null + let currentParent = parent + while (currentParent) { + const rulesParent = ruleset.filter(findRules(currentParent, true)) + lowerLevelComponent = rulesParent[rulesParent.length - 1] + currentParent = currentParent.parent + if (lowerLevelComponent && filter(lowerLevelComponent)) currentParent = null + } + return filter(lowerLevelComponent) ? lowerLevelComponent : null + } const processInnerComponent = (component, parent) => { const { @@ -87,18 +117,82 @@ export const init = (ruleset) => { return stateCombinations.map(state => ({ variant, state })) }).reduce((acc, x) => [...acc, ...x], []) + const VIRTUAL_COMPONENTS = new Set(['Text', 'Link', 'Icon']) + stateVariantCombination.forEach(combination => { - // addRule(({ - // parent, - // component: component.name, - // state: combination.state, - // variant: combination.variant - // })) + const existingRules = ruleset.filter(findRules({ component: component.name, ...combination })) + const lastRule = existingRules[existingRules.length - 1] + + if (existingRules.length !== 0) { + const { directives } = lastRule + const rgb = convert(directives.background).rgb + + // TODO: DEFAULT TEXT COLOR + const bg = findLowerLevelRule(parent)?.cache.background || convert('#FFFFFF').rgb + + if (!lastRule.cache?.background) { + const blend = directives.opacity < 1 ? alphaBlend(rgb, directives.opacity, bg) : rgb + lastRule.cache = lastRule.cache || {} + lastRule.cache.background = blend + + addRule(lastRule) + } + } else { + if (VIRTUAL_COMPONENTS.has(component.name)) { + const selector = component.name + ruleToSelector({ component: component.name, ...combination }) + + const lowerLevel = findLowerLevelRule(parent, (r) => { + if (components[r.component].validInnerComponents.indexOf(component.name) < 0) return false + if (r.cache?.background === undefined) return false + if (r.cache.textDefined) { + return !r.cache.textDefined[selector] + } + return true + }) + if (!lowerLevel) return + lowerLevel.cache.textDefined = lowerLevel.cache.textDefined || {} + lowerLevel.cache.textDefined[selector] = true + addRule({ + parent, + component: component.name, + ...combination, + directives: { + // TODO: DEFAULT TEXT COLOR + textColor: getTextColor(convert(lowerLevel.cache.background).rgb, convert('#FFFFFF').rgb, component.name === 'Link'), + // Debug: lets you see what it think background color should be + background: convert(lowerLevel.cache.background).hex + } + }) + } + } innerComponents.forEach(innerComponent => processInnerComponent(innerComponent, { parent, component: name, ...combination })) }) } processInnerComponent(components[rootName]) - return rules + + // console.info(rules.map(x => [ + // (parent?.component || 'root') + ' -> ' + x.component, + // // 'Cached background:' + convert(bg).hex, + // // 'Color: ' + convert(x.directives.background).hex + ' A:' + x.directives.opacity, + // JSON.stringify(x.directives) + // // '=> Blend: ' + convert(x.cache.background).hex + // ].join(' '))) + + return { + raw: rules, + css: rules.map(rule => { + const header = ruleToSelector(rule) + ' {' + const footer = '}' + const directives = Object.entries(rule.directives).map(([k, v]) => { + switch (k) { + case 'background': return 'background-color: ' + rgba2css({ ...convert(v).rgb, a: rule.directives.opacity ?? 1 }) + case 'textColor': return 'color: ' + rgba2css({ ...convert(v).rgb, a: rule.directives.opacity ?? 1 }) + default: return '' + } + }).filter(x => x).map(x => ' ' + x).join(';\n') + return [header, directives, footer].join('\n') + }) + } } diff --git a/test/unit/specs/services/theme_data/theme_data3.spec.js b/test/unit/specs/services/theme_data/theme_data3.spec.js index e76200c0..915bb5ce 100644 --- a/test/unit/specs/services/theme_data/theme_data3.spec.js +++ b/test/unit/specs/services/theme_data/theme_data3.spec.js @@ -1,8 +1,7 @@ // import { topoSort } from 'src/services/theme_data/theme_data.service.js' import { getAllPossibleCombinations, - init, - ruleToSelector + init } from 'src/services/theme_data/theme_data_3.service.js' import { sampleRules @@ -19,8 +18,8 @@ describe.only('Theme Data 3', () => { describe('init', () => { it('test simple case', () => { const out = init(sampleRules) - console.log(JSON.stringify(out, null, 2)) - out.forEach(r => console.log(ruleToSelector(r))) + // console.log(JSON.stringify(out, null, 2)) + console.log('\n' + out.css.join('\n') + '\n') }) }) }) -- cgit v1.2.3-70-g09d2 From 53a4b1f9a6a9aa6bc044609c3accb074d924daf9 Mon Sep 17 00:00:00 2001 From: Henry Jameson Date: Wed, 31 Jan 2024 17:39:51 +0200 Subject: better virtual components and stuff --- src/App.scss | 28 +- src/components/icon.style.js | 13 +- src/components/link.style.js | 25 ++ src/components/notification/notification.vue | 2 +- src/components/notifications/notifications.scss | 16 +- src/components/panel.style.js | 1 + src/components/panel_header.style.js | 1 + src/components/status/status.vue | 2 +- src/components/status_body/status_body.scss | 5 +- src/components/text.style.js | 38 ++- src/components/underlay.style.js | 3 +- src/panel.scss | 11 - src/services/color_convert/color_convert.js | 3 +- src/services/style_setter/style_setter.js | 19 +- src/services/theme_data/pleromafe.t3.js | 16 +- src/services/theme_data/theme_data_3.service.js | 304 ++++++++++++++++----- .../specs/services/theme_data/theme_data3.spec.js | 2 +- 17 files changed, 353 insertions(+), 136 deletions(-) create mode 100644 src/components/link.style.js (limited to 'test') diff --git a/src/App.scss b/src/App.scss index ef68ac50..8e9f3171 100644 --- a/src/App.scss +++ b/src/App.scss @@ -24,8 +24,7 @@ body { font-family: sans-serif; font-family: var(--interfaceFont, sans-serif); margin: 0; - color: $fallback--text; - color: var(--text, $fallback--text); + color: var(--text); -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; overscroll-behavior-y: none; @@ -111,8 +110,7 @@ body { a { text-decoration: none; - color: $fallback--link; - color: var(--link, $fallback--link); + color: var(--link); } h4 { @@ -128,8 +126,7 @@ h4 { i[class*="icon-"], .svg-inline--fa, .iconLetter { - color: $fallback--icon; - color: var(--icon, $fallback--icon); + color: var(--icon); } .button-unstyled:hover, @@ -763,17 +760,11 @@ option { } .faint { - color: $fallback--faint; - color: var(--faint, $fallback--faint); -} - -.faint-link { - color: $fallback--faint; - color: var(--faint, $fallback--faint); + --text: var(--textFaint); + --textGreentext: var(--textGreentextFaint); + --link: var(--linkFaint); - &:hover { - text-decoration: underline; - } + color: var(--text); } .visibility-notice { @@ -816,6 +807,11 @@ option { opacity: 0.25; } +.timeago { + --link: var(--text); + --linkFaint: var(--textFaint); +} + .login-hint { text-align: center; diff --git a/src/components/icon.style.js b/src/components/icon.style.js index 732cf16f..adc72fc5 100644 --- a/src/components/icon.style.js +++ b/src/components/icon.style.js @@ -1,4 +1,15 @@ export default { name: 'Icon', - selector: '.icon' + virtual: true, + selector: '.svg-inline--fa', + defaultRules: [ + { + component: 'Icon', + directives: { + textColor: '--text', + textOpacity: 0.5, + textOpacityMode: 'mixrgb' + } + } + ] } diff --git a/src/components/link.style.js b/src/components/link.style.js new file mode 100644 index 00000000..0128fd91 --- /dev/null +++ b/src/components/link.style.js @@ -0,0 +1,25 @@ +export default { + name: 'Link', + selector: 'a', + virtual: true, + states: { + faint: '.faint' + }, + defaultRules: [ + { + component: 'Link', + directives: { + textColor: '--link' + } + }, + { + component: 'Link', + state: ['faint'], + directives: { + textColor: '--link', + textOpacity: 0.5, + textOpacityMode: 'fake' + } + } + ] +} diff --git a/src/components/notification/notification.vue b/src/components/notification/notification.vue index a8eceab0..5c425200 100644 --- a/src/components/notification/notification.vue +++ b/src/components/notification/notification.vue @@ -155,7 +155,7 @@ .button-default { flex-shrink: 0; diff --git a/src/services/color_convert/color_convert.js b/src/services/color_convert/color_convert.js index 23e4ca61..d92bbbe0 100644 --- a/src/services/color_convert/color_convert.js +++ b/src/services/color_convert/color_convert.js @@ -173,7 +173,7 @@ export const mixrgb = (a, b) => { * @returns {String} CSS rgba() color */ export const rgba2css = function (rgba) { - return `rgba(${Math.floor(rgba.r)}, ${Math.floor(rgba.g)}, ${Math.floor(rgba.b)}, ${rgba.a})` + return `rgba(${Math.floor(rgba.r)}, ${Math.floor(rgba.g)}, ${Math.floor(rgba.b)}, ${rgba.a ?? 1})` } /** @@ -188,7 +188,6 @@ export const rgba2css = function (rgba) { */ export const getTextColor = function (bg, text, preserve) { const contrast = getContrastRatio(bg, text) - console.log(contrast) if (contrast < 4.5) { const base = typeof text.a !== 'undefined' ? { a: text.a } : {} diff --git a/src/services/style_setter/style_setter.js b/src/services/style_setter/style_setter.js index 43fe3c73..ba98c4d9 100644 --- a/src/services/style_setter/style_setter.js +++ b/src/services/style_setter/style_setter.js @@ -1,10 +1,15 @@ import { convert } from 'chromatism' import { rgb2hex, hex2rgb, rgba2css, getCssColor, relativeLuminance } from '../color_convert/color_convert.js' import { getColors, computeDynamicColor, getOpacitySlot } from '../theme_data/theme_data.service.js' +import { init } from '../theme_data/theme_data_3.service.js' +import { + sampleRules +} from 'src/services/theme_data/pleromafe.t3.js' import { defaultState } from '../../modules/config.js' export const applyTheme = (input) => { - const { rules } = generatePreset(input) + const { rules, t3b } = generatePreset(input) + const themes3 = init(sampleRules, t3b) const head = document.head const body = document.body body.classList.add('hidden') @@ -18,6 +23,10 @@ export const applyTheme = (input) => { styleSheet.insertRule(`:root { ${rules.colors} }`, 'index-max') styleSheet.insertRule(`:root { ${rules.shadows} }`, 'index-max') styleSheet.insertRule(`:root { ${rules.fonts} }`, 'index-max') + themes3.css.forEach(rule => { + console.log(rule) + styleSheet.insertRule(rule, 'index-max') + }) body.classList.remove('hidden') } @@ -326,7 +335,7 @@ export const generateShadows = (input, colors) => { } } -export const composePreset = (colors, radii, shadows, fonts) => { +export const composePreset = (colors, radii, shadows, fonts, t3b) => { return { rules: { ...shadows.rules, @@ -339,7 +348,8 @@ export const composePreset = (colors, radii, shadows, fonts) => { ...colors.theme, ...radii.theme, ...fonts.theme - } + }, + t3b } } @@ -349,7 +359,8 @@ export const generatePreset = (input) => { colors, generateRadii(input), generateShadows(input, colors.theme.colors, colors.mod), - generateFonts(input) + generateFonts(input), + colors.theme.colors ) } diff --git a/src/services/theme_data/pleromafe.t3.js b/src/services/theme_data/pleromafe.t3.js index 8d8e19cd..9fadf0ee 100644 --- a/src/services/theme_data/pleromafe.t3.js +++ b/src/services/theme_data/pleromafe.t3.js @@ -11,30 +11,30 @@ export const sampleRules = [ { component: 'Panel', directives: { - background: '#FFFFFF', - opacity: 0.9 + background: '--fg' + // opacity: 0.9 } }, { component: 'PanelHeader', directives: { - background: '#000000', - opacity: 0.9 + background: '--fg' + // opacity: 0.9 } }, { component: 'Button', directives: { - background: '#000000', - opacity: 0.8 + background: '--fg' + // opacity: 0.8 } }, { component: 'Button', state: ['hover'], directives: { - background: '#FF00FF', - opacity: 0.9 + background: '#FFFFFF' + // opacity: 0.9 } } ] diff --git a/src/services/theme_data/theme_data_3.service.js b/src/services/theme_data/theme_data_3.service.js index 2ef5e17f..c9468d07 100644 --- a/src/services/theme_data/theme_data_3.service.js +++ b/src/services/theme_data/theme_data_3.service.js @@ -1,11 +1,12 @@ import { convert } from 'chromatism' -import { alphaBlend, getTextColor, rgba2css } from '../color_convert/color_convert.js' +import { alphaBlend, getTextColor, rgba2css, mixrgb } from '../color_convert/color_convert.js' import Underlay from 'src/components/underlay.style.js' import Panel from 'src/components/panel.style.js' import PanelHeader from 'src/components/panel_header.style.js' import Button from 'src/components/button.style.js' import Text from 'src/components/text.style.js' +import Link from 'src/components/link.style.js' import Icon from 'src/components/icon.style.js' const root = Underlay @@ -15,6 +16,7 @@ const components = { PanelHeader, Button, Text, + Link, Icon } @@ -35,9 +37,9 @@ export const getAllPossibleCombinations = (array) => { return combos.reduce((acc, x) => [...acc, ...x], []) } -export const ruleToSelector = (rule) => { +export const ruleToSelector = (rule, isParent) => { const component = components[rule.component] - const { states, variants, selector } = component + const { states, variants, selector, outOfTreeSelector } = component const applicableStates = ((rule.state || []).filter(x => x !== 'normal')).map(state => states[state]) @@ -47,56 +49,104 @@ export const ruleToSelector = (rule) => { applicableVariant = variants[applicableVariantName] } - const selectors = [selector, applicableVariant, ...applicableStates] + let realSelector + if (isParent) { + realSelector = selector + } else { + if (outOfTreeSelector) realSelector = outOfTreeSelector + else realSelector = selector + } + + const selectors = [realSelector, applicableVariant, ...applicableStates] .toSorted((a, b) => { if (a.startsWith(':')) return 1 - else return -1 + if (!a.startsWith('.')) return -1 + else return 0 }) .join('') if (rule.parent) { - return ruleToSelector(rule.parent) + ' ' + selectors + return ruleToSelector(rule.parent, true) + ' ' + selectors } return selectors } -export const init = (ruleset) => { +export const init = (extraRuleset, palette) => { const rootName = root.name const rules = [] const rulesByComponent = {} + const ruleset = [ + ...Object.values(components).map(c => c.defaultRules || []).reduce((acc, arr) => [...acc, ...arr], []), + ...extraRuleset + ] + const addRule = (rule) => { rules.push(rule) rulesByComponent[rule.component] = rulesByComponent[rule.component] || [] rulesByComponent[rule.component].push(rule) } - const findRules = (combination) => rule => { - if (combination.component !== rule.component) return false - if (Object.prototype.hasOwnProperty.call(rule, 'variant')) { - if (combination.variant !== rule.variant) return false - } else { - if (combination.variant !== 'normal') return false + const findRules = (combination, parent) => rule => { + // inexact search + const doesCombinationMatch = () => { + if (combination.component !== rule.component) return false + if (Object.prototype.hasOwnProperty.call(rule, 'variant')) { + if (combination.variant !== rule.variant) return false + } else { + if (combination.variant !== 'normal') return false + } + + if (Object.prototype.hasOwnProperty.call(rule, 'state')) { + const ruleStatesSet = new Set(['normal', ...(rule.state || [])]) + const combinationSet = new Set(['normal', ...combination.state]) + const setsAreEqual = combination.state.every(state => ruleStatesSet.has(state)) && + [...ruleStatesSet].every(state => combinationSet.has(state)) + return setsAreEqual + } else { + if (combination.state.length !== 1 || combination.state[0] !== 'normal') return false + return true + } } + const combinationMatches = doesCombinationMatch() + if (!parent || !combinationMatches) return combinationMatches - if (Object.prototype.hasOwnProperty.call(rule, 'state')) { - const ruleStatesSet = new Set(['normal', ...(rule.state || [])]) - const combinationSet = new Set(['normal', ...combination.state]) - const setsAreEqual = combination.state.every(state => ruleStatesSet.has(state)) && - [...ruleStatesSet].every(state => combinationSet.has(state)) - return setsAreEqual - } else { - if (combination.state.length !== 1 || combination.state[0] !== 'normal') return false - return true + // exact search + + // unroll parents into array + const unroll = (item) => { + const out = [] + let currentParent = item.parent + while (currentParent) { + const { parent: newParent, ...rest } = currentParent + out.push(rest) + currentParent = newParent + } + return out } + const { parent: _, ...rest } = parent + const pathSearch = [rest, ...unroll(parent)] + const pathRule = unroll(rule) + if (pathSearch.length !== pathRule.length) return false + const pathsMatch = pathSearch.every((searchRule, i) => { + const existingRule = pathRule[i] + if (existingRule.component !== searchRule.component) return false + if (existingRule.variant !== searchRule.variant) return false + const existingRuleStatesSet = new Set(['normal', ...(existingRule.state || [])]) + const searchStatesSet = new Set(['normal', ...(searchRule.state || [])]) + const setsAreEqual = existingRule.state.every(state => searchStatesSet.has(state)) && + [...searchStatesSet].every(state => existingRuleStatesSet.has(state)) + return setsAreEqual + }) + return pathsMatch } const findLowerLevelRule = (parent, filter = () => true) => { let lowerLevelComponent = null let currentParent = parent while (currentParent) { - const rulesParent = ruleset.filter(findRules(currentParent, true)) - rulesParent > 1 && console.log('OOPS') + const rulesParent = ruleset.filter(findRules(currentParent)) + rulesParent > 1 && console.warn('OOPS') lowerLevelComponent = rulesParent[rulesParent.length - 1] currentParent = currentParent.parent if (lowerLevelComponent && filter(lowerLevelComponent)) currentParent = null @@ -104,6 +154,35 @@ export const init = (ruleset) => { return filter(lowerLevelComponent) ? lowerLevelComponent : null } + const findColor = (color) => { + if (typeof color === 'string' && color.startsWith('--')) { + const name = color.substring(2) + return palette[name] + } + return color + } + + const getTextColorAlpha = (rule, lowerRule, value) => { + const opacity = rule.directives.textOpacity + const textColor = convert(findColor(value)).rgb + if (opacity === null || opacity === undefined || opacity >= 1) { + return convert(textColor).hex + } + const backgroundColor = convert(lowerRule.cache.background).rgb + if (opacity === 0) { + return convert(backgroundColor).hex + } + const opacityMode = rule.directives.textOpacityMode + switch (opacityMode) { + case 'fake': + return convert(alphaBlend(textColor, opacity, backgroundColor)).hex + case 'mixrgb': + return convert(mixrgb(backgroundColor, textColor)).hex + default: + return rgba2css({ a: opacity, ...textColor }) + } + } + const processInnerComponent = (component, parent) => { const { validInnerComponents = [], @@ -124,79 +203,156 @@ export const init = (ruleset) => { const VIRTUAL_COMPONENTS = new Set(['Text', 'Link', 'Icon']) stateVariantCombination.forEach(combination => { - const existingRules = ruleset.filter(findRules({ component: component.name, ...combination })) - const lastRule = existingRules[existingRules.length - 1] + let needRuleAdd = false - if (existingRules.length !== 0) { - const { directives } = lastRule - const rgb = convert(directives.background).rgb + if (VIRTUAL_COMPONENTS.has(component.name)) { + const selector = component.name + ruleToSelector({ component: component.name, ...combination }) + const virtualName = [ + '--', + component.name.toLowerCase(), + combination.variant === 'normal' + ? '' + : combination.variant[0].toUpperCase() + combination.variant.slice(1).toLowerCase(), + ...combination.state.filter(x => x !== 'normal').toSorted().map(state => state[0].toUpperCase() + state.slice(1).toLowerCase()) + ].join('') - // TODO: DEFAULT TEXT COLOR - const bg = findLowerLevelRule(parent)?.cache.background || convert('#FFFFFF').rgb + const lowerLevel = findLowerLevelRule(parent, (r) => { + if (components[r.component].validInnerComponents.indexOf(component.name) < 0) return false + if (r.cache.background === undefined) return false + if (r.cache.textDefined) { + return !r.cache.textDefined[selector] + } + return true + }) - if (!lastRule.cache?.background) { - const blend = directives.opacity < 1 ? alphaBlend(rgb, directives.opacity, bg) : rgb - lastRule.cache = lastRule.cache || {} - lastRule.cache.background = blend + if (!lowerLevel) return + + let inheritedTextColorRule + const inheritedTextColorRules = findLowerLevelRule(parent, (r) => { + return r.cache?.textDefined?.[selector] + }) + + if (!inheritedTextColorRule) { + const generalTextColorRules = ruleset.filter(findRules({ component: component.name, ...combination }, null, true)) + inheritedTextColorRule = generalTextColorRules[generalTextColorRules.length - 1] + } else { + inheritedTextColorRule = inheritedTextColorRules[inheritedTextColorRules.length - 1] + } - addRule(lastRule) + let inheritedTextColor + let inheritedTextOpacity = {} + if (inheritedTextColorRule) { + inheritedTextColor = findColor(inheritedTextColorRule.directives.textColor) + // also inherit opacity settings + const { textOpacity, textOpacityMode } = inheritedTextColorRule.directives + inheritedTextOpacity = { textOpacity, textOpacityMode } + } else { + // Emergency fallback + inheritedTextColor = '#000000' } + + const textColor = getTextColor( + convert(lowerLevel.cache.background).rgb, + convert(inheritedTextColor).rgb, + component.name === 'Link' // make it configurable? + ) + + lowerLevel.cache.textDefined = lowerLevel.cache.textDefined || {} + lowerLevel.cache.textDefined[selector] = textColor + lowerLevel.virtualDirectives = lowerLevel.virtualDirectives || {} + lowerLevel.virtualDirectives[virtualName] = getTextColorAlpha(inheritedTextColorRule, lowerLevel, textColor) + + const directives = { + textColor, + ...inheritedTextOpacity + } + + // Debug: lets you see what it think background color should be + directives.background = convert(lowerLevel.cache.background).hex + + addRule({ + parent, + virtual: true, + component: component.name, + ...combination, + cache: { background: lowerLevel.cache.background }, + directives + }) } else { - if (VIRTUAL_COMPONENTS.has(component.name)) { - const selector = component.name + ruleToSelector({ component: component.name, ...combination }) - - const lowerLevel = findLowerLevelRule(parent, (r) => { - if (components[r.component].validInnerComponents.indexOf(component.name) < 0) return false - if (r.cache?.background === undefined) return false - if (r.cache.textDefined) { - return !r.cache.textDefined[selector] - } - return true - }) - if (!lowerLevel) return - lowerLevel.cache.textDefined = lowerLevel.cache.textDefined || {} - lowerLevel.cache.textDefined[selector] = true - addRule({ - parent, - component: component.name, - ...combination, - directives: { - // TODO: DEFAULT TEXT COLOR - textColor: getTextColor(convert(lowerLevel.cache.background).rgb, convert('#FFFFFF').rgb, component.name === 'Link'), - // Debug: lets you see what it think background color should be - background: convert(lowerLevel.cache.background).hex + const existingGlobalRules = ruleset.filter(findRules({ component: component.name, ...combination }, null)) + const existingRules = ruleset.filter(findRules({ component: component.name, ...combination }, parent)) + + // Global (general) rules + if (existingGlobalRules.length !== 0) { + const lastRule = existingGlobalRules[existingGlobalRules.length - 1] + const { directives } = lastRule + lastRule.cache = lastRule.cache || {} + + if (directives.background) { + const rgb = convert(findColor(directives.background)).rgb + + // TODO: DEFAULT TEXT COLOR + const bg = findLowerLevelRule(parent)?.cache.background || convert('#FFFFFF').rgb + + if (!lastRule.cache.background) { + const blend = directives.opacity < 1 ? alphaBlend(rgb, directives.opacity, bg) : rgb + lastRule.cache.background = blend + + needRuleAdd = true } - }) + } + + if (needRuleAdd) { + addRule(lastRule) + } } - } + if (existingRules.length !== 0) { + console.warn('MORE EXISTING RULES', existingRules) + } + } innerComponents.forEach(innerComponent => processInnerComponent(innerComponent, { parent, component: name, ...combination })) }) } processInnerComponent(components[rootName]) - // console.info(rules.map(x => [ - // (parent?.component || 'root') + ' -> ' + x.component, - // // 'Cached background:' + convert(bg).hex, - // // 'Color: ' + convert(x.directives.background).hex + ' A:' + x.directives.opacity, - // JSON.stringify(x.directives) - // // '=> Blend: ' + convert(x.cache.background).hex - // ].join(' '))) - return { raw: rules, css: rules.map(rule => { - const header = ruleToSelector(rule) + ' {' + if (rule.virtual) return '' + + let selector = ruleToSelector(rule).replace(/\/\*.*\*\//g, '') + if (!selector) { + selector = 'body' + } + const header = selector + ' {' const footer = '}' + + const virtualDirectives = Object.entries(rule.virtualDirectives || {}).map(([k, v]) => { + return ' ' + k + ': ' + v + }).join(';\n') + const directives = Object.entries(rule.directives).map(([k, v]) => { switch (k) { - case 'background': return 'background-color: ' + rgba2css({ ...convert(v).rgb, a: rule.directives.opacity ?? 1 }) - case 'textColor': return 'color: ' + rgba2css({ ...convert(v).rgb, a: rule.directives.opacity ?? 1 }) + case 'background': { + return 'background-color: ' + rgba2css({ ...convert(findColor(v)).rgb, a: rule.directives.opacity ?? 1 }) + } + case 'textColor': { + return 'color: ' + v + } default: return '' } }).filter(x => x).map(x => ' ' + x).join(';\n') - return [header, directives, footer].join('\n') - }) + + return [ + header, + directives + ';', + ' color: var(--text);', + '', + virtualDirectives, + footer + ].join('\n') + }).filter(x => x) } } diff --git a/test/unit/specs/services/theme_data/theme_data3.spec.js b/test/unit/specs/services/theme_data/theme_data3.spec.js index 915bb5ce..0d5870cc 100644 --- a/test/unit/specs/services/theme_data/theme_data3.spec.js +++ b/test/unit/specs/services/theme_data/theme_data3.spec.js @@ -17,7 +17,7 @@ describe.only('Theme Data 3', () => { describe('init', () => { it('test simple case', () => { - const out = init(sampleRules) + const out = init(sampleRules, palette) // console.log(JSON.stringify(out, null, 2)) console.log('\n' + out.css.join('\n') + '\n') }) -- cgit v1.2.3-70-g09d2 From 1e467ac6e189ee66ccaf7c2ff2a3d6a16459a86c Mon Sep 17 00:00:00 2001 From: Henry Jameson Date: Thu, 7 Mar 2024 01:08:04 +0200 Subject: update tests --- .../specs/services/theme_data/theme_data3.spec.js | 29 ++++++++++++++++------ 1 file changed, 22 insertions(+), 7 deletions(-) (limited to 'test') diff --git a/test/unit/specs/services/theme_data/theme_data3.spec.js b/test/unit/specs/services/theme_data/theme_data3.spec.js index 0d5870cc..25a9dda4 100644 --- a/test/unit/specs/services/theme_data/theme_data3.spec.js +++ b/test/unit/specs/services/theme_data/theme_data3.spec.js @@ -1,11 +1,13 @@ // import { topoSort } from 'src/services/theme_data/theme_data.service.js' import { - getAllPossibleCombinations, + getAllPossibleCombinations +} from 'src/services/theme_data/iss_utils.js' +import { init } from 'src/services/theme_data/theme_data_3.service.js' import { - sampleRules -} from 'src/services/theme_data/pleromafe.t3.js' + basePaletteKeys +} from 'src/services/theme_data/theme2_to_theme3.js' describe.only('Theme Data 3', () => { describe('getAllPossibleCombinations', () => { @@ -16,10 +18,23 @@ describe.only('Theme Data 3', () => { }) describe('init', () => { - it('test simple case', () => { - const out = init(sampleRules, palette) - // console.log(JSON.stringify(out, null, 2)) - console.log('\n' + out.css.join('\n') + '\n') + it('Test initialization without anything', () => { + const out = init([], '#DEADAF') + + expect(out).to.have.property('eager') + expect(out).to.have.property('lazy') + expect(out).to.have.property('staticVars') + + expect(out.lazy).to.be.an('array') + expect(out.lazy).to.have.lengthOf.above(1) + expect(out.eager).to.be.an('array') + expect(out.eager).to.have.lengthOf.above(1) + expect(out.staticVars).to.be.an('object') + + // check backwards compat/generic stuff + basePaletteKeys.forEach(key => { + expect(out.staticVars).to.have.property(key) + }) }) }) }) -- cgit v1.2.3-70-g09d2 From c1568ad2ba283336378e135ce329bb4c4c1b92f2 Mon Sep 17 00:00:00 2001 From: Henry Jameson Date: Mon, 25 Mar 2024 18:18:48 +0200 Subject: fix massive issue in getAllPossibleCombinations --- src/services/theme_data/iss_utils.js | 16 +++++++++++++--- .../unit/specs/services/theme_data/theme_data3.spec.js | 18 ++++++++++++++++-- 2 files changed, 29 insertions(+), 5 deletions(-) (limited to 'test') diff --git a/src/services/theme_data/iss_utils.js b/src/services/theme_data/iss_utils.js index 6568f576..2d9dd0b5 100644 --- a/src/services/theme_data/iss_utils.js +++ b/src/services/theme_data/iss_utils.js @@ -11,18 +11,28 @@ export const unroll = (item) => { } // This gives you an array of arrays of all possible unique (i.e. order-insensitive) combinations +// Can only accept primitives. Duplicates are not supported and can cause unexpected behavior export const getAllPossibleCombinations = (array) => { const combos = [array.map(x => [x])] for (let comboSize = 2; comboSize <= array.length; comboSize++) { const previous = combos[combos.length - 1] - const selfSet = new Set() const newCombos = previous.map(self => { + const selfSet = new Set() self.forEach(x => selfSet.add(x)) const nonSelf = array.filter(x => !selfSet.has(x)) return nonSelf.map(x => [...self, x]) }) const flatCombos = newCombos.reduce((acc, x) => [...acc, ...x], []) - combos.push(flatCombos) + const uniqueComboStrings = new Set() + const uniqueCombos = flatCombos.map(x => x.toSorted()).filter(x => { + if (uniqueComboStrings.has(x.join())) { + return false + } else { + uniqueComboStrings.add(x.join()) + return true + } + }) + combos.push(uniqueCombos) } return combos.reduce((acc, x) => [...acc, ...x], []) } @@ -31,7 +41,7 @@ export const getAllPossibleCombinations = (array) => { export const genericRuleToSelector = components => (rule, ignoreOutOfTreeSelector, isParent) => { if (!rule && !isParent) return null const component = components[rule.component] - const { states, variants, selector, outOfTreeSelector } = component + const { states = {}, variants = {}, selector, outOfTreeSelector } = component const applicableStates = ((rule.state || []).filter(x => x !== 'normal')).map(state => states[state]) diff --git a/test/unit/specs/services/theme_data/theme_data3.spec.js b/test/unit/specs/services/theme_data/theme_data3.spec.js index 25a9dda4..37d343f9 100644 --- a/test/unit/specs/services/theme_data/theme_data3.spec.js +++ b/test/unit/specs/services/theme_data/theme_data3.spec.js @@ -11,9 +11,23 @@ import { describe.only('Theme Data 3', () => { describe('getAllPossibleCombinations', () => { - it('test simple case', () => { + it('test simple 3 values case', () => { const out = getAllPossibleCombinations([1, 2, 3]).map(x => x.sort((a, b) => a - b)) - expect(out).to.eql([[1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]) + expect(out).to.eql([ + [1], [2], [3], + [1, 2], [1, 3], [2, 3], + [1, 2, 3] + ]) + }) + + it('test simple 4 values case', () => { + const out = getAllPossibleCombinations([1, 2, 3, 4]).map(x => x.sort((a, b) => a - b)) + expect(out).to.eql([ + [1], [2], [3], [4], + [1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4], + [1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4], + [1, 2, 3, 4] + ]) }) }) -- cgit v1.2.3-70-g09d2 From f3d3901a9216efe304cb6fe06d738e4d3e2c78f8 Mon Sep 17 00:00:00 2001 From: Henry Jameson Date: Mon, 25 Mar 2024 19:07:28 +0200 Subject: more tests --- .../specs/services/theme_data/theme_data3.spec.js | 88 ++++++++++++++++++++++ 1 file changed, 88 insertions(+) (limited to 'test') diff --git a/test/unit/specs/services/theme_data/theme_data3.spec.js b/test/unit/specs/services/theme_data/theme_data3.spec.js index 37d343f9..b863e5fe 100644 --- a/test/unit/specs/services/theme_data/theme_data3.spec.js +++ b/test/unit/specs/services/theme_data/theme_data3.spec.js @@ -29,6 +29,37 @@ describe.only('Theme Data 3', () => { [1, 2, 3, 4] ]) }) + + it('test massive 5 values case, using strings', () => { + const out = getAllPossibleCombinations(['a', 'b', 'c', 'd', 'e']).map(x => x.sort((a, b) => a - b)) + expect(out).to.eql([ + // 1 + ['a'], ['b'], ['c'], ['d'], ['e'], + // 2 + ['a', 'b'], ['a', 'c'], ['a', 'd'], ['a', 'e'], + ['b', 'c'], ['b', 'd'], ['b', 'e'], + ['c', 'd'], ['c', 'e'], + ['d', 'e'], + // 3 + ['a', 'b', 'c'], ['a', 'b', 'd'], ['a', 'b', 'e'], + ['a', 'c', 'd'], ['a', 'c', 'e'], + ['a', 'd', 'e'], + + ['b', 'c', 'd'], ['b', 'c', 'e'], + ['b', 'd', 'e'], + + ['c', 'd', 'e'], + // 4 + ['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'e'], + ['a', 'b', 'd', 'e'], + + ['a', 'c', 'd', 'e'], + + ['b', 'c', 'd', 'e'], + // 5 + ['a', 'b', 'c', 'd', 'e'] + ]) + }) }) describe('init', () => { @@ -50,5 +81,62 @@ describe.only('Theme Data 3', () => { expect(out.staticVars).to.have.property(key) }) }) + + it('Test initialization with a basic palette', () => { + const out = init([{ + component: 'Root', + directives: { + '--bg': 'color | #008080', + '--fg': 'color | #00C0A0' + } + }], '#DEADAF') + + expect(out.staticVars).to.have.property('bg').equal('#008080') + expect(out.staticVars).to.have.property('fg').equal('#00C0A0') + + const panelRule = out.eager.filter(x => { + if (x.component !== 'Panel') return false + return true + })[0] + + expect(panelRule).to.have.nested.deep.property('dynamicVars.stacked', { r: 0, g: 128, b: 128 }) + }) + + it('Test initialization with opacity', () => { + const out = init([{ + component: 'Root', + directives: { + '--bg': 'color | #008080' + } + }, { + component: 'Panel', + directives: { + opacity: 0.5 + } + }], '#DEADAF') + + expect(out.staticVars).to.have.property('bg').equal('#008080') + + const panelRule = out.eager.filter(x => { + if (x.component !== 'Panel') return false + return true + })[0] + + expect(panelRule).to.have.nested.deep.property('dynamicVars.background', { r: 0, g: 128, b: 128, a: 0.5 }) + expect(panelRule).to.have.nested.deep.property('dynamicVars.stacked') + // Somewhat incorrect since we don't do gamma correction + // real expectancy should be this: + /* + + expect(panelRule).to.have.nested.deep.property('dynamicVars.stacked.r').that.is.closeTo(147.0, 0.01) + expect(panelRule).to.have.nested.deep.property('dynamicVars.stacked.g').that.is.closeTo(143.2, 0.01) + expect(panelRule).to.have.nested.deep.property('dynamicVars.stacked.b').that.is.closeTo(144.0, 0.01) + + */ + + expect(panelRule).to.have.nested.deep.property('dynamicVars.stacked.r').that.is.closeTo(88.8, 0.01) + expect(panelRule).to.have.nested.deep.property('dynamicVars.stacked.g').that.is.closeTo(133.2, 0.01) + expect(panelRule).to.have.nested.deep.property('dynamicVars.stacked.b').that.is.closeTo(134, 0.01) + }) }) }) -- cgit v1.2.3-70-g09d2 From c298611af2736b0a0d535b6bb47b2c9025e4069a Mon Sep 17 00:00:00 2001 From: Henry Jameson Date: Tue, 26 Mar 2024 18:49:29 +0200 Subject: fix tests and make them pass on shit hardware --- test/unit/specs/services/theme_data/theme_data3.spec.js | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'test') diff --git a/test/unit/specs/services/theme_data/theme_data3.spec.js b/test/unit/specs/services/theme_data/theme_data3.spec.js index b863e5fe..bb8d785c 100644 --- a/test/unit/specs/services/theme_data/theme_data3.spec.js +++ b/test/unit/specs/services/theme_data/theme_data3.spec.js @@ -9,7 +9,7 @@ import { basePaletteKeys } from 'src/services/theme_data/theme2_to_theme3.js' -describe.only('Theme Data 3', () => { +describe('Theme Data 3', () => { describe('getAllPossibleCombinations', () => { it('test simple 3 values case', () => { const out = getAllPossibleCombinations([1, 2, 3]).map(x => x.sort((a, b) => a - b)) @@ -62,7 +62,9 @@ describe.only('Theme Data 3', () => { }) }) - describe('init', () => { + describe('init', function () { + this.timeout(5000) + it('Test initialization without anything', () => { const out = init([], '#DEADAF') -- cgit v1.2.3-70-g09d2 From c6ccab778f78bf65cebcad1c5e0943d427254098 Mon Sep 17 00:00:00 2001 From: Henry Jameson Date: Wed, 10 Jul 2024 22:49:56 +0300 Subject: MASSIVELY streamlined theme setting process, now EVERYTHING happens in a vuex action "setTheme" instead of several different applyTheme()s scattered around --- src/boot/after_store.js | 29 +----- .../settings_modal/tabs/appearance_tab.js | 5 + .../settings_modal/tabs/appearance_tab.vue | 9 ++ .../settings_modal/tabs/theme_tab/theme_tab.js | 9 +- src/modules/config.js | 44 +++++---- src/modules/instance.js | 101 ++++++++++++++++----- src/services/style_setter/style_setter.js | 23 +---- src/services/theme_data/theme2_to_theme3.js | 1 + src/services/theme_data/theme_data_3.service.js | 5 +- .../specs/services/theme_data/theme_data3.spec.js | 44 +++++---- 10 files changed, 159 insertions(+), 111 deletions(-) (limited to 'test') diff --git a/src/boot/after_store.js b/src/boot/after_store.js index b93e28a3..a486bd4c 100644 --- a/src/boot/after_store.js +++ b/src/boot/after_store.js @@ -13,8 +13,7 @@ import VBodyScrollLock from 'src/directives/body_scroll_lock' import { windowWidth, windowHeight } from '../services/window_utils/window_utils' import { getOrCreateApp, getClientToken } from '../services/new_api/oauth.js' import backendInteractorService from '../services/backend_interactor_service/backend_interactor_service.js' -import { CURRENT_VERSION } from '../services/theme_data/theme_data.service.js' -import { applyTheme, applyConfig, tryLoadCache } from '../services/style_setter/style_setter.js' +import { applyConfig } from '../services/style_setter/style_setter.js' import FaviconService from '../services/favicon_service/favicon_service.js' import { initServiceWorker, updateFocus } from '../services/sw/sw.js' @@ -160,8 +159,6 @@ const setSettings = async ({ apiConfig, staticConfig, store }) => { copyInstanceOption('showFeaturesPanel') copyInstanceOption('hideSitename') copyInstanceOption('sidebarRight') - - return store.dispatch('setTheme', config.theme) } const getTOS = async ({ store }) => { @@ -352,29 +349,7 @@ const afterStoreSetup = async ({ store, i18n }) => { store.dispatch('setInstanceOption', { name: 'server', value: server }) await setConfig({ store }) - - const { customTheme, customThemeSource, forceThemeRecompilation, themeDebug } = store.state.config - const { theme } = store.state.instance - const customThemePresent = customThemeSource || customTheme - - console.log('DEBUG INITIAL', themeDebug, forceThemeRecompilation) - - if (!forceThemeRecompilation && !themeDebug && tryLoadCache()) { - store.commit('setThemeApplied') - } else { - if (customThemePresent) { - if (customThemeSource && customThemeSource.themeEngineVersion === CURRENT_VERSION) { - applyTheme(customThemeSource, () => {}, themeDebug) - } else { - applyTheme(customTheme, () => {}, themeDebug) - } - store.commit('setThemeApplied') - } else if (theme) { - // do nothing, it will load asynchronously - } else { - console.error('Failed to load any theme!') - } - } + await store.dispatch('setTheme') applyConfig(store.state.config) diff --git a/src/components/settings_modal/tabs/appearance_tab.js b/src/components/settings_modal/tabs/appearance_tab.js index 3776464a..d340fd00 100644 --- a/src/components/settings_modal/tabs/appearance_tab.js +++ b/src/components/settings_modal/tabs/appearance_tab.js @@ -29,6 +29,11 @@ const AppearanceTab = { key: mode, value: i - 1, label: this.$t(`settings.forced_roundness_mode_${mode}`) + })), + underlayOverrideModes: ['none', 'opaque', 'transparent'].map((mode, i) => ({ + key: mode, + value: mode, + label: this.$t(`settings.underlay_override_mode_${mode}`) })) } }, diff --git a/src/components/settings_modal/tabs/appearance_tab.vue b/src/components/settings_modal/tabs/appearance_tab.vue index fb24cc6b..d3df76a1 100644 --- a/src/components/settings_modal/tabs/appearance_tab.vue +++ b/src/components/settings_modal/tabs/appearance_tab.vue @@ -182,6 +182,15 @@ {{ $t('settings.force_interface_roundness') }} +
  • + + {{ $t('settings.underlay_overrides') }} + +
  • {{ $t('settings.hide_wallpaper') }} diff --git a/src/components/settings_modal/tabs/theme_tab/theme_tab.js b/src/components/settings_modal/tabs/theme_tab/theme_tab.js index 72e2b625..7ca3b066 100644 --- a/src/components/settings_modal/tabs/theme_tab/theme_tab.js +++ b/src/components/settings_modal/tabs/theme_tab/theme_tab.js @@ -502,6 +502,7 @@ export default { this.$store.dispatch('setOption', { name: 'customTheme', value: { + ignore: true, themeFileVersion: this.selectedVersion, themeEngineVersion: CURRENT_VERSION, ...this.previewTheme @@ -699,13 +700,13 @@ export default { } }, updateTheme3Preview () { - console.log(this.previewTheme) const theme2 = convertTheme2To3(this.previewTheme) const theme3 = init({ - extraRuleset: theme2, + inputRuleset: theme2, ultimateBackgroundColor: '#000000', liteMode: true }) + this.themeV3Preview = getCssRules(theme3.eager) .map(x => { if (x.startsWith('html')) { @@ -722,7 +723,7 @@ export default { watch: { currentRadii () { try { - this.previewTheme.radii = generateRadii({ radii: this.currentRadii }).theme + this.previewTheme.radii = generateRadii({ radii: this.currentRadii }).theme.radii this.radiiInvalid = false } catch (e) { this.radiiInvalid = true @@ -744,7 +745,7 @@ export default { fontsLocal: { handler () { try { - this.previewTheme.fonts = generateFonts({ fonts: this.fontsLocal }).theme + this.previewTheme.fonts = generateFonts({ fonts: this.fontsLocal }).theme.fonts this.fontsInvalid = false } catch (e) { this.fontsInvalid = true diff --git a/src/modules/config.js b/src/modules/config.js index 59d056d9..56151d2a 100644 --- a/src/modules/config.js +++ b/src/modules/config.js @@ -1,10 +1,21 @@ import Cookies from 'js-cookie' -import { setPreset, applyTheme, applyConfig } from '../services/style_setter/style_setter.js' +import { applyConfig } from '../services/style_setter/style_setter.js' import messages from '../i18n/messages' import { set } from 'lodash' import localeService from '../services/locale/locale.service.js' const BACKEND_LANGUAGE_COOKIE_NAME = 'userLanguage' +const APPEARANCE_SETTINGS_KEYS = new Set([ + 'sidebarColumnWidth', + 'contentColumnWidth', + 'notifsColumnWidth', + 'textSize', + 'navbarSize', + 'panelHeaderSize', + 'forcedRoundness', + 'emojiSize', + 'emojiReactionsScale' +]) const browserLocale = (window.navigator.language || 'en').split('-')[0] @@ -81,6 +92,11 @@ export const defaultState = { chatMention: true, polls: true }, + palette: null, + theme3hacks: { + underlay: 'none', + badgeColor: null + }, webPushNotifications: false, webPushAlwaysShowNotifications: false, muteWords: [], @@ -185,7 +201,6 @@ const config = { applyConfig(state) }, setOption (state, { name, value }) { - console.log('SET OPTION', state, name, value) set(state, name, value) }, setHighlight (state, { user, color, type }) { @@ -261,30 +276,23 @@ const config = { } } else { commit('setOption', { name, value }) + if ( + name.startsWith('theme3hacks') || + APPEARANCE_SETTINGS_KEYS.has(name) + ) { + applyConfig(state) + } switch (name) { case 'theme': - setPreset(value) - break - case 'sidebarColumnWidth': - case 'contentColumnWidth': - case 'notifsColumnWidth': - case 'textSize': - case 'navbarSize': - case 'panelHeaderSize': - case 'forcedRoundness': - case 'emojiSize': - case 'emojiReactionsScale': - applyConfig(state) + dispatch('setTheme', { themeName: value, recompile: true }) break case 'customTheme': case 'customThemeSource': { - const { themeDebug } = state - applyTheme(value, () => {}, themeDebug) + if (!value.ignore) dispatch('setTheme', { themeData: value }) break } case 'themeDebug': { - const { customTheme, customThemeSource } = state - applyTheme(customTheme || customThemeSource, () => {}, value) + dispatch('setTheme', { recompile: true }) break } case 'interfaceLanguage': diff --git a/src/modules/instance.js b/src/modules/instance.js index 602503ed..85a966b8 100644 --- a/src/modules/instance.js +++ b/src/modules/instance.js @@ -1,5 +1,6 @@ -import { getPreset, applyTheme } from '../services/style_setter/style_setter.js' -import { CURRENT_VERSION } from '../services/theme_data/theme_data.service.js' +import { getPreset, applyTheme, tryLoadCache } from '../services/style_setter/style_setter.js' +import { CURRENT_VERSION, generatePreset } from 'src/services/theme_data/theme_data.service.js' +import { convertTheme2To3 } from 'src/services/theme_data/theme2_to_theme3.js' import apiService from '../services/api/api.service.js' import { instanceDefaultProperties } from './config.js' import { langCodeToCldrName, ensureFinalFallback } from '../i18n/languages.js' @@ -286,9 +287,6 @@ const instance = { dispatch('initializeSocket') } break - case 'theme': - dispatch('setTheme', value) - break } }, async getStaticEmoji ({ commit }) { @@ -378,25 +376,86 @@ const instance = { } }, - setTheme ({ commit, rootState }, themeName) { - commit('setInstanceOption', { name: 'theme', value: themeName }) - getPreset(themeName) - .then(themeData => { - commit('setInstanceOption', { name: 'themeData', value: themeData }) - // No need to apply theme if there's user theme already - const { customTheme, themeDebug } = rootState.config - const { themeApplied } = rootState.interface - if (customTheme || themeApplied) return - - // New theme presets don't have 'theme' property, they use 'source' - const themeSource = themeData.source - if (!themeData.theme || (themeSource && themeSource.themeEngineVersion === CURRENT_VERSION)) { - applyTheme(themeSource, null, themeDebug) + setTheme ({ commit, state, rootState }, { themeName, themeData, recompile } = {}) { + // const { + // themeApplied + // } = rootState.interface + const { + theme: instanceThemeName + } = state + + const { + customTheme: userThemeSnapshot, + customThemeSource: userThemeSource, + forceThemeRecompilation, + themeDebug + } = rootState.config + + const forceRecompile = forceThemeRecompilation || recompile + + // If we're not not forced to recompile try using + // cache (tryLoadCache return true if load successful) + if (!forceRecompile && !themeDebug && tryLoadCache()) { + commit('setThemeApplied') + } + + const normalizeThemeData = (themeData) => { + console.log('NORMAL', themeData) + if (themeData.themeFileVerison === 1) { + return generatePreset(themeData).theme + } + // New theme presets don't have 'theme' property, they use 'source' + const themeSource = themeData.source + + let out // shout, shout let it all out + if (!themeData.theme || (themeSource && themeSource.themeEngineVersion === CURRENT_VERSION)) { + out = themeSource || themeData + } else { + out = themeData.theme + } + + // generatePreset here basically creates/updates "snapshot", + // while also fixing the 2.2 -> 2.3 colors/shadows/etc + return generatePreset(out).theme + } + + let promise = null + + if (themeName) { + // commit('setInstanceOption', { name: 'theme', value: themeName }) + promise = getPreset(themeName) + .then(themeData => { + // commit('setInstanceOption', { name: 'themeData', value: themeData }) + return normalizeThemeData(themeData) + }) + } else if (themeData) { + promise = Promise.resolve(normalizeThemeData(themeData)) + } else { + if (userThemeSource || userThemeSnapshot) { + if (userThemeSource && userThemeSource.themeEngineVersion === CURRENT_VERSION) { + promise = Promise.resolve(normalizeThemeData(userThemeSource)) } else { - applyTheme(themeData.theme, null, themeDebug) + promise = Promise.resolve(normalizeThemeData(userThemeSnapshot)) } - commit('setThemeApplied') + } else if (instanceThemeName) { + promise = getPreset(themeName).then(themeData => normalizeThemeData(themeData)) + } + } + + promise + .then(realThemeData => { + console.log('FR FR 1', realThemeData) + const ruleset = convertTheme2To3(realThemeData) + console.log('FR FR 2', ruleset) + + applyTheme( + ruleset, + () => commit('setThemeApplied'), + themeDebug + ) }) + + return promise }, fetchEmoji ({ dispatch, state }) { if (!state.customEmojiFetched) { diff --git a/src/services/style_setter/style_setter.js b/src/services/style_setter/style_setter.js index 78e7428d..e54a95bf 100644 --- a/src/services/style_setter/style_setter.js +++ b/src/services/style_setter/style_setter.js @@ -1,7 +1,5 @@ import { hex2rgb } from '../color_convert/color_convert.js' -import { generatePreset } from '../theme_data/theme_data.service.js' import { init, getEngineChecksum } from '../theme_data/theme_data_3.service.js' -import { convertTheme2To3 } from '../theme_data/theme2_to_theme3.js' import { getCssRules } from '../theme_data/css_utils.js' import { defaultState } from '../../modules/config.js' import { chunk } from 'lodash' @@ -45,30 +43,20 @@ const adoptStyleSheets = (styles) => { // is nothing to do here. } -export const generateTheme = async (input, callbacks, debug) => { +export const generateTheme = async (inputRuleset, callbacks, debug) => { const { onNewRule = (rule, isLazy) => {}, onLazyFinished = () => {}, onEagerFinished = () => {} } = callbacks - let extraRules - if (input.themeFileVersion === 1) { - extraRules = convertTheme2To3(input) - } else { - const { theme } = generatePreset(input) - extraRules = convertTheme2To3(theme) - } - // Assuming that "worst case scenario background" is panel background since it's the most likely one const themes3 = init({ - extraRules, - ultimateBackgroundColor: extraRules[0].directives['--bg'].split('|')[1].trim(), + inputRuleset, + ultimateBackgroundColor: inputRuleset[0].directives['--bg'].split('|')[1].trim(), debug }) - console.log('DEBUG 2 IS', debug) - getCssRules(themes3.eager, debug).forEach(rule => { // Hacks to support multiple selectors on same component if (rule.match(/::-webkit-scrollbar-button/)) { @@ -162,8 +150,6 @@ export const applyTheme = async (input, onFinish = (data) => {}, debug) => { const eagerStyles = createStyleSheet(EAGER_STYLE_ID) const lazyStyles = createStyleSheet(LAZY_STYLE_ID) - console.log('DEBUG IS', debug) - const { lazyProcessFunc } = await generateTheme( input, { @@ -216,7 +202,6 @@ const extractStyleConfig = ({ textSize } - console.log(forcedRoundness) switch (forcedRoundness) { case 'disable': break @@ -325,5 +310,3 @@ export const getPreset = (val) => { return { theme: data, source: theme.source } }) } - -export const setPreset = (val) => getPreset(val).then(data => applyTheme(data)) diff --git a/src/services/theme_data/theme2_to_theme3.js b/src/services/theme_data/theme2_to_theme3.js index 2c97d18b..b54366bd 100644 --- a/src/services/theme_data/theme2_to_theme3.js +++ b/src/services/theme_data/theme2_to_theme3.js @@ -265,6 +265,7 @@ export const convertTheme2To3 = (data) => { const newRules = [] Object.keys(data.fonts || {}).forEach(key => { if (!fontsKeys.has(key)) return + if (!data.fonts[key]) return const originalFont = data.fonts[key].family const rule = { source: '2to3' } diff --git a/src/services/theme_data/theme_data_3.service.js b/src/services/theme_data/theme_data_3.service.js index e98b19a7..e802a893 100644 --- a/src/services/theme_data/theme_data_3.service.js +++ b/src/services/theme_data/theme_data_3.service.js @@ -150,12 +150,13 @@ const ruleToSelector = genericRuleToSelector(components) export const getEngineChecksum = () => engineChecksum export const init = ({ - extraRuleset, + inputRuleset, ultimateBackgroundColor, debug = false, liteMode = false, rootComponentName = 'Root' }) => { + if (!inputRuleset) throw new Error('Ruleset is null or undefined!') const staticVars = {} const stacked = {} const computed = {} @@ -164,7 +165,7 @@ export const init = ({ ...Object.values(components) .map(c => (c.defaultRules || []).map(r => ({ component: c.name, ...r, source: 'Built-in' }))) .reduce((acc, arr) => [...acc, ...arr], []), - ...extraRuleset + ...inputRuleset ].map(rule => { normalizeCombination(rule) let currentParent = rule.parent diff --git a/test/unit/specs/services/theme_data/theme_data3.spec.js b/test/unit/specs/services/theme_data/theme_data3.spec.js index bb8d785c..92a87de9 100644 --- a/test/unit/specs/services/theme_data/theme_data3.spec.js +++ b/test/unit/specs/services/theme_data/theme_data3.spec.js @@ -66,7 +66,7 @@ describe('Theme Data 3', () => { this.timeout(5000) it('Test initialization without anything', () => { - const out = init([], '#DEADAF') + const out = init({ ruleset: [], ultimateBackgroundColor: '#DEADAF' }) expect(out).to.have.property('eager') expect(out).to.have.property('lazy') @@ -85,13 +85,16 @@ describe('Theme Data 3', () => { }) it('Test initialization with a basic palette', () => { - const out = init([{ - component: 'Root', - directives: { - '--bg': 'color | #008080', - '--fg': 'color | #00C0A0' - } - }], '#DEADAF') + const out = init({ + ruleset: [{ + component: 'Root', + directives: { + '--bg': 'color | #008080', + '--fg': 'color | #00C0A0' + } + }], + ultimateBackgroundColor: '#DEADAF' + }) expect(out.staticVars).to.have.property('bg').equal('#008080') expect(out.staticVars).to.have.property('fg').equal('#00C0A0') @@ -105,17 +108,20 @@ describe('Theme Data 3', () => { }) it('Test initialization with opacity', () => { - const out = init([{ - component: 'Root', - directives: { - '--bg': 'color | #008080' - } - }, { - component: 'Panel', - directives: { - opacity: 0.5 - } - }], '#DEADAF') + const out = init({ + ruleset: [{ + component: 'Root', + directives: { + '--bg': 'color | #008080' + } + }, { + component: 'Panel', + directives: { + opacity: 0.5 + } + }], + ultimateBackgroundColor: '#DEADAF' + }) expect(out.staticVars).to.have.property('bg').equal('#008080') -- cgit v1.2.3-70-g09d2 From 2c7f78a29fd040a655c74951c2d1919e736ce133 Mon Sep 17 00:00:00 2001 From: Henry Jameson Date: Mon, 22 Jul 2024 01:19:05 +0300 Subject: fix tests --- test/unit/specs/services/theme_data/theme_data3.spec.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'test') diff --git a/test/unit/specs/services/theme_data/theme_data3.spec.js b/test/unit/specs/services/theme_data/theme_data3.spec.js index 92a87de9..b76ea596 100644 --- a/test/unit/specs/services/theme_data/theme_data3.spec.js +++ b/test/unit/specs/services/theme_data/theme_data3.spec.js @@ -66,7 +66,7 @@ describe('Theme Data 3', () => { this.timeout(5000) it('Test initialization without anything', () => { - const out = init({ ruleset: [], ultimateBackgroundColor: '#DEADAF' }) + const out = init({ inputRuleset: [], ultimateBackgroundColor: '#DEADAF' }) expect(out).to.have.property('eager') expect(out).to.have.property('lazy') @@ -86,7 +86,7 @@ describe('Theme Data 3', () => { it('Test initialization with a basic palette', () => { const out = init({ - ruleset: [{ + inputRuleset: [{ component: 'Root', directives: { '--bg': 'color | #008080', @@ -109,7 +109,7 @@ describe('Theme Data 3', () => { it('Test initialization with opacity', () => { const out = init({ - ruleset: [{ + inputRuleset: [{ component: 'Root', directives: { '--bg': 'color | #008080' -- cgit v1.2.3-70-g09d2